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.
java
public class Solution {
/*
* @param nums: an array of integer
* @param target: an integer
* @return: an integer
*/
public int twoSum5(int[] nums, int target) {
// write your code here
if (nums == null || nums.length < 2) {
return 0;
}
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
int count = 0;
int value = 0;
while (left < right) {
value = nums[left] + nums[right];
if (left < right && value > target) {
right--;
} else {
count += (right - left);
left++;
}
}
return count;
}
}
python
class Solution:
"""
@param: nums: an array of integer
@param: target: an integer
@return: an integer
"""
def twoSum5(self, nums, target):
# write your code here
if nums == None or len(nums) < 2:
return 0
nums.sort()
left, right = 0, len(nums) - 1
count = 0
while left < right:
val = nums[left] + nums[right]
if left < right and val > target:
right -= 1
# while left < right and nums[right] == nums[right + 1]:
# right -= 1
else:
count += (right - left)
left += 1
# while left < right and nums[left] == nums[left - 1]:
# left += 1
return count