Given an array of integers, find how many unique pairs
in the array such that their sum is equal to a specific target number. Please return the number of pairs.
Example
Given nums = [1,1,2,45,46,46]
, target = 47
return 2
1 + 46 = 47
2 + 45 = 47
java
public class Solution {
/*
* @param nums: an array of integer
* @param target: An integer
* @return: An integer
*/
public int twoSum6(int[] nums, int target) {
// write your code here
if (nums == null || nums.length == 0 || nums.length == 1) {
return 0;
}
int left = 0;
int right = nums.length - 1;
int value = 0;
int count = 0;
Arrays.sort(nums);
while (left < right) {
value = nums[left] + nums[right];
if (left < right && value < target) {
left++;
}
if (left < right && value > target) {
right--;
}
if (left < right && value == target) {
count++;
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
return count;
}
}
python
class Solution:
"""
@param: nums: an array of integer
@param: target: An integer
@return: An integer
"""
def twoSum6(self, nums, target):
# write your code here
if nums == None or len(nums) == 0 or len(nums) == 1:
return 0
left, right, value, count = 0, len(nums) - 1, 0, 0
nums.sort()
while left < right:
value = nums[left] + nums[right]
if left < right and value < target:
left += 1
if left < right and value > target:
right -= 1
if left < right and value == target:
count += 1
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return count