Simple Java Solution


  • 0
    public class Solution {
        public int findLHS(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            Map<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                map.put(num, map.getOrDefault(num, 0) + 1);
            }
            int max = 0;
            for (int key : map.keySet()) {
                int left = map.getOrDefault(key - 1, 0);
                int right = map.getOrDefault(key + 1, 0);
                if (left == 0 && right == 0) continue;
                max = Math.max(max, Math.max(map.get(key) + left, map.get(key) + right));
            }
            return max;
        }
    }
    

Log in to reply
 

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