Amazon | OA 2019 | Two Sum - Unique Pairs
Given an int array nums and an int target
, find how many unique pairs in the array such that their sum is equal to target. Return the number of pairs.
Example 1:
Input: nums = [1, 1, 2, 45, 46, 46], target = 47
Output: 2
Explanation:
1 + 46 = 47
2 + 45 = 47
Example 2:
Input: nums = [1, 1], target = 2
Output: 1
Explanation:
1 + 1 = 2
Example 3:
Input: nums = [1, 5, 1, 5], target = 6
Output: 1
Explanation:
[1, 5] and [5, 1] are considered the same.
Related problems:
- https://leetcode.com/problems/two-sum
- https://leetcode.com/problems/two-sum-ii-input-array-is-sorted
Solution1: TwoPointers
1.注意重复元素的去重
注意去重的方法;
如果用nums[start] == nums[start+1] start ++, 如果nums[start+1]还是一个重复的元素,nums[start+2]不是重复的元素,那么这种方法就不能去掉nums[start+1]。
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 < 2) return 0;
Arrays.sort(nums);
int start = 0, end = nums.length -1;
int sum = 0;
while(start < end) {
if(nums[start] + nums[end] == target){
++ sum;
++ start;
-- end;
while(start < end && nums[start] == nums[start - 1] ){
++ start;
}
while(start < end && nums[end] == nums[end + 1] ){
-- end;
}
}
else if(nums[start] + nums[end] > target){
-- end;
}else {
++ start;
}
}
return sum;
}
}