Share my Java O(n) with one Hashmap, hope it will help you understand it easily


  • 0
    A

    The idea is when k is 0, compare the value of the key-value pair in the hashmap to get the answer. If k is not 0, then just check if the hashMap has the key of (num + k) given the key num. Hope it will help you.

    public class Solution {
        public int findPairs(int[] nums, int k) {
            // corner case
            if (k < 0 || nums == null || nums.length == 0) return 0;
            
            
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            int counter = 0;
            
            for (int num : nums) {
                if (!map.containsKey(num)) {
                    map.put(num, 1);
                }
                else {
                    int val = map.get(num);
                    map.put(num, val + 1);
                
                }
            }
            
            if (k == 0) {
                for (Integer num : map.keySet()) {
                    if (map.get(num) >= 2) counter ++;
                }
            }
            else {
                for (Integer num : map.keySet()) {
                    if (map.containsKey(num + k)) counter++;
                }
            }
            
            return counter;
        }
    }
    

Log in to reply
 

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