Java O(n) solution - one Hashmap or one HashSet, easy to understand


  • 0
    public int findPairs(int[] nums, int k) {
        int sum = 0;
        if (k < 0) return 0;
        if (k == 0) {
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int num : nums) {
                if (map.get(num) == null) {
                    map.put(num, 1);
                } else if (map.get(num) == 1) {
                    map.put(num, 2);
                    sum++;
                }
            }
        } else {
            HashSet<Integer> set = new HashSet<Integer>();
            for (int num : nums) {
                if (!set.contains(num)) {
                    if (set.contains(num - k)) {
                        sum++;
                    }
                    if (set.contains(num + k)) {
                        sum++;
                    }
                    set.add(num);
                }
            }
        }
    
        return sum;
    }

Log in to reply
 

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