A clean Java solution


  • 0
    L
      //1, 3, 1, 5, 4], k = 0
        public int findPairs(int[] nums, int k) {
            //abs distance can't be negative.
            if(k<0) {
                return 0;
            }
            Set<Integer> set = new HashSet<>();
            Set<pair> uniquepairs = new HashSet<>();
            for(int i: nums) {
                pair minus = new pair(i,i-k);
                pair plus = new pair(i,i+k);
                if(set.contains(i-k)) {
                    if(!uniquepairs.contains(minus)) {
                        uniquepairs.add(minus);
                    }
                }
                if(set.contains(i+k)) {
                    if(!uniquepairs.contains(plus)) {
                        uniquepairs.add(plus);
                    }
                }
    
                set.add(i);
    
            }
            return uniquepairs.size();
        }
        
        private class pair {
            int left;
            int right;
            pair(int left,int right) {
                this.left = left;
                this.right =right;
            }
            public int hashCode() {
                return left+right;
            }
            public boolean equals(Object o) {
                if(o==this) {
                    return true;
                }
                
                pair p = (pair)o;
                return (p.left==this.left && p.right ==this.right)
                ||(p.left==this.right && p.right ==this.left) ;
            }
            
            public String toString() {
                return "left="+left + " right="+right;
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.