给一整数数组, 找到数组中有多少组 不同的元素对
有相同的和, 且和为给出的 target 值, 返回对数.
样例
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
解题思路:
双指针法。不同的是这次需要找不同的元素对,所以需要对相同的元素跳过。
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 l = 0;
int r = nums.length-1;
int res = 0;
while(l < r){
//用来过滤掉相同的元素
if(l > 0 && nums[l] == nums[l-1]){
l++;
continue;
}
if(r < nums.length-1 && nums[r] == nums[r+1]){
r--;
continue;
}
if(nums[l] + nums[r] == target){
l++;
r--;
res++;
}else if(nums[l] + nums[r] < target)
l++;
else
r--;
}
return res;
}
}