Two Sum - Less than or equal to target解題報告

Description:

Given an array of integers, find how many pairs in the array such that their sum is less than or equal to a specific target number. Please return the number of pairs.

Example:

Given nums = [2, 7, 11, 15], target = 24.
Return 5.
2 + 7 < 24
2 + 11 < 24
2 + 15 < 24
7 + 11 < 24
7 + 15 < 25

Link:

http://www.lintcode.com/en/problem/two-sum-less-than-or-equal-to-target/

題目解讀:

這道題給定了一個數(shù)組與一個target數(shù),要求返回數(shù)組中“和”小于或者等于target數(shù)的兩個數(shù)組合的個數(shù)。

解題方法:

首先將數(shù)組排序,然后使用頭尾指針解決,當(dāng)頭尾兩個數(shù)相加大于target,尾指針向前移;否則尾指針前面到頭指針?biāo)械臄?shù)與頭指針的數(shù)相加都會小于或等于target,所以count += end - start. 直到頭指針和尾指針相交循環(huán)結(jié)束。

Time Complexity:

O(nlogn)

完整代碼:

int twoSum5(vector<int> &nums, int target) { int count = 0; if(nums.size() < 2) return count; sort(nums.begin(), nums.end()); int start = 0, end = nums.size() - 1; while(start < end) { int temp = nums[start] + nums[end]; if(temp > target) end--; else { count += end - start; start++; } } return count; }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容