532 k-diff pairs in array
求陣列中差值絕對值為k的不重複元素有多少對,使用的思想:two-points(吐槽一句:字母l和1真的太像了。。。)
自己的:分三種情況“k<0;k=0;k>0"set的缺陷在於不能處理k=0的情況,因此相當於寫兩套方案,太麻煩了。
class Solution {
public int findPairs(int[] nums, int k) {
if(nums==null || nums.length<2) return 0;
int count= 0, index=0;
if(k<0) return 0;
if(k==0){
Arrays.sort(nums);
for(int i=0; i<nums.length-1; i++){
if(nums[i]==nums[i+1]){
count++;
while(i+1<nums.length && nums[i]==nums[i+1]){
i++;
}
}
}
return count;
}
Set<Integer> can= new HashSet<Integer>();
for(int i=0; i<nums.length; i++){
can.add(nums[i]);
}
while(!can.isEmpty()){
if(can.contains(nums[index])){
//判斷有無階梯值
if(can.contains(nums[index]-k)){count++;}
if(can.contains(nums[index]+k)){count++;}
can.remove(nums[index]);
}
index++;
}
return count;
}
}
看討論區別人的解法:
class Solution {
public int findPairs(int[] nums, int k) {
if (nums == null || nums.length <= 1) {
return 0;
}
if (k < 0) {
return 0;
}
int count = 0;
Arrays.sort(nums);
int l = 0, r = 1;
while (r < nums.length) {
if (nums[r] - nums[l] == k) {
count++;
l++;
// skip duplicates
while (r + 1 < nums.length && nums[r] == nums[r + 1]) {
r++;
}
r++;
} else if (nums[r] - nums[l] < k) {
r++;
} else {
l++;
}
if (r == l) {
r++;
}
}
return count;
}
}