1. 程式人生 > >594. Longest Harmonious Subsequence - LeetCode

594. Longest Harmonious Subsequence - LeetCode

子序列 leetcode 圖片 iou desc 保存 return moni get

Question

594. Longest Harmonious Subsequence

技術分享圖片

Solution

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

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

Java實現:

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;
}

594. Longest Harmonious Subsequence - LeetCode