Java, 11 line, HashMap, one pass


  • 0
    I

    Build a histogram using HashMap over each element, at the same time update the res.

    public int findLHS(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int res = 0;
        for(int n : nums) {
            if(!map.containsKey(n)) map.put(n, 0);
            map.put(n, map.get(n)+1);
            if(map.containsKey(n-1)) res = Math.max(res, map.get(n) + map.get(n-1));
            if(map.containsKey(n+1)) res = Math.max(res, map.get(n) + map.get(n+1));
        }
        return res;
    }

Log in to reply
 

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