594. Longest Harmonious Subsequence - LeetCode

Question

594. Longest Harmonious Subsequencejava

Solution

題目大意:找一個最長子序列,要求子序列中最大值和最小值的差是1。code

思路:構造一個map,保存每一個元素出現的個數,再遍歷這個map,算出每一個元素與其鄰元素出現的次數和,並找到最大的那個數ip

Java實現:leetcode

public int findLHS(int[] nums) {
    if (nums == null || nums.length == 0) return 0;
    Map<Integer, Integer> map = new HashMap<>();
    for (int tmp : nums) {
        Integer cnt = map.get(tmp);
        if (cnt == null) cnt = 0;
        map.put(tmp, cnt + 1);
    }
    int count = 0;
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        int before = map.get(entry.getKey() - 1) != null ? map.get(entry.getKey() - 1) : -entry.getValue();
        int next = map.get(entry.getKey() + 1) != null ? map.get(entry.getKey() + 1) : -entry.getValue();
        if (before + entry.getValue() > count) count = before + entry.getValue();
        if (next + entry.getValue() > count) count = next + entry.getValue();
    }
    return count;
}
相關文章
相關標籤/搜索