Description:
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.
Ex:
Given nums = [1,1,2,45,46,46], target = 47
return 2
1 + 46 = 47
2 + 45 = 47
解法一:
思路:
双指针 + 哈希表
Code:
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){
return 0;
}
Set<Integer> set = new HashSet<>();
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
int count = 0;
while (left < right){
if (nums[left] + nums[right] == target){
count++;
set.add(nums[left]);
left++;
while ((left < right) && (set.contains(nums[left]))){
left++;
}
} else if (nums[left] + nums[right] < target){
left++;
} else {
right--;
}
}
return count;
}
}
解法二:
思路:
单纯双指针:
Code:
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){
return 0;
}
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
int count = 0;
while (left < right){
if (nums[left] + nums[right] == target){
count++;
right--;
left++;
while ((left < right) && (nums[left - 1] == nums[left])){
left++;
}
// while ((left < right) && (nums[right + 1] == nums[right])){
// right--;
// }
} else if (nums[left] + nums[right] < target){
left++;
} else {
right--;
}
}
return count;
}
}
小贴士:
用双指针处理的Two Sum问题要先排序,同时要注意防止数组越界。