587.Two Sum - Unique pairs
1.Description(Medium)
Given an array of integers, find how manyunique 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
return2
1 + 46 = 47 2 + 45 = 47
2.Code
老样子,先排序。
一个从左,一个从右,往当中走。
如果加起来等于target,那么左边往右走到不是左边这个数的地方,右边往左走到不是右边这个数字的地方。
然后接着比。
public int twoSum6(int[] nums, int target) {
if(nums==null || nums.length<2){
return 0;
}
Arrays.sort(nums);
int result=0;
int head=0;
int tail=nums.length-1;
while(head<tail){
int sum=nums[head]+nums[tail];
//这里先判断sum==target,因为不等于的话--或者++不影响结果
if(sum==target){
result++;
head++;
tail--;
//这里因为head和tail已经先变化了,所以要注意比较的对象
while(head<tail && nums[head]==nums[head-1]){
head++;
}
while(head<tail && nums[tail]==nums[tail+1]){
tail--;
}
}
else if(sum>target){
tail--;
}else{
head++;
}
}
return result;
}
Last updated
Was this helpful?