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/
题目解读:
这道题给定了一个数组与一个target数,要求返回数组中“和”小于或者等于target数的两个数组合的个数。
解题方法:
首先将数组排序,然后使用头尾指针解决,当头尾两个数相加大于target,尾指针向前移;否则尾指针前面到头指针所有的数与头指针的数相加都会小于或等于target,所以count += end - start. 直到头指针和尾指针相交循环结束。
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; }