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;
    }

}

猜你喜欢

转载自blog.csdn.net/better_girl/article/details/83583991