594. Longest Harmonious Subsequence

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Solution:Hashmap

思路:存入Hashmap作为bucket,在遍历Hashmap看相邻的两个key有多少个,作为输入的 subsequence
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class Solution {
    public int findLHS(int[] nums) {
        Map map = new HashMap<>();
        for (long num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        int result = 0;
        for (long key : map.keySet()) {
            if (map.containsKey(key + 1)) {
                result = Math.max(result, map.get(key + 1) + map.get(key));
            }
        }
        return result;
    }
}

你可能感兴趣的:(594. Longest Harmonious Subsequence)