594. Longest Harmonious Subsequence

本题题意:
在一个数组中,找一个这样的和谐数组,他们的最大值和最小值的差值正好是1.
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

就是可以还是不连续的。

第一遍写:

    Map<Integer, Integer>  dc = new HashMap<>();
        int res = 0;
        for (int i = 0; i < nums.length; ++i){
            if (dc.containsKey(nums[i]) )    continue;
            else{
                int tr = 1;
                boolean h = false;
                for (int j = i + 1; j < nums.length; ++j)
                    if (nums[j] == nums[i])
                        tr += 1;
                    else if(nums[j] == nums[i] + 1){
                        tr += 1;
                        h = true;
                    }
                res = Math.max(res, h ? tr: 0);
                
                tr = 1;
                h = false;
                for(int j = i + 1; j < nums.length; ++j)
                    if (nums[j] == nums[i])
                        tr += 1;
                    else if(nums[j] == nums[i] - 1){
                        tr += 1;
                        h = true;
                    }
                res = Math.max(res, h ? tr : 0);
            }
        }
        return res;

上面的思路是:用Hash记录,nums[i]的最大harmonious序列长度
下面修改hash,让他直接记录次数不是更好嘛,然后再算。
第二遍写:

    Map<Integer, Integer>  dc = new HashMap<>();
        for (int i = 0; i < nums.length; ++i)
            if (dc.containsKey(nums[i]))    dc.put(nums[i], dc.get(nums[i]) + 1);
            else    dc.put(nums[i], 1);
        int res = 0;
        for (int i = 0; i < nums.length; ++i){
            if (dc.containsKey(nums[i] - 1))   res = Math.max(res, dc.get(nums[i] - 1) + dc.get(nums[i]));
            if (dc.containsKey(nums[i] + 1))   res = Math.max(res, dc.get(nums[i] + 1) + dc.get(nums[i]));
        }
        return res;

然后又用python写了一遍.

def findLHS(self, nums: List[int]) -> int:
        dc = collections.Counter(nums)
        #nums[i] : counts
        res = 0
        for key, c in dc.items():
            if dc[key - 1] != 0:    res = max(res, dc[key] + dc[key - 1])
            if dc[key + 1] != 0:    res = max(res, dc[key] + dc[key + 1])
        return res

最后嘞,看答案感觉又菜鸡了,其实是不用判定key - 1的,为什么嘞?

  1. 因为只要他没有key - 1,这是当然不用判定的。
  2. 如果要是有key - 1,那么到了key - 1就算的是上一次的。一直到最后。
    然后,字典加入也有小技巧
dc.put(num, dc.getOrDefault(num, 0) + 1);

代码如下:

    Map<Integer, Integer>  dc = new HashMap<>();
        int res = 0;
        for (int num : nums)
            dc.put(num, dc.getOrDefault(num, 0) + 1);
        for (int num : nums)
            if (dc.containsKey(num + 1))   res = Math.max(res, dc.get(num + 1) + dc.get(num));   
        return res;
原文地址:https://www.cnblogs.com/whyaza/p/10860590.html