题目描述:
Given an array of integers, find how many pairs in the array such that their sum is bigger than a specific target number. Please return the number of pairs.
Given numbers = [2, 7, 11, 15]
, target = 24
. Return 1
. (11 + 15 is the only pair)
Do it in O(1) extra space and O(nlogn) time.
把array从小到大进行sort,再用两个pointers:l指向array的头,r指向array的尾。当nums[l] + nums[r]的值满足条件时,这也表示l = l...r - 1和r的组合也满足条件,这时可以skip这一段的检查,下一个loop中r = r - 1;当他俩的值不满足条件时,这也表示r = l + 1...r和l的组合也不满足条件,这样也可以skip相应的情况。
Mycode(AC = 66ms):
class Solution {
public:
/**
* @param nums: an array of integer
* @param target: an integer
* @return: an integer
*/
int twoSum2(vector<int> &nums, int target) {
// Write your code here
sort(nums.begin(), nums.end());
int l = 0, r = nums.size() - 1;
int num_pairs = 0;
while (l < r) {
// if sum > target, then
// sum of l = l...r-1 and r = r
// all > target
if (nums[l] + nums[r] > target) {
num_pairs += r - l;
r--;
}
// if sum <= target, then
// don't need to consider r = l + 1...r
else {
l++;
}
}
return num_pairs;
}
};