[Leetcode学习-c++&java]Longest Harmonious Subsequence

问题:

难度:easy

说明:

和谐数组,就是里面最大数是最小数差距为 1。

题目连接:https://leetcode.com/problems/longest-harmonious-subsequence/

输入范围:

  • 1 <= nums.length <= 2 * 104
  • -109 <= nums[i] <= 109

输入案例:

Example 1:
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Example 2:
Input: nums = [1,2,3,4]
Output: 2

Example 3:
Input: nums = [1,1,1,1]
Output: 0

我的代码:

好久没水题了,来个滑动窗口最容易

Java:

class Solution {
    public int findLHS(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length, left = 0, right = 0, count = 0;
        while(right < len) {
            while(right > left && nums[right] - nums[left] > 1) left ++;
            if(nums[right] - nums[left] == 1) count = Math.max(count, right - left + 1);
            right ++;
        }
        return count;
    }
}

C++:

class Solution {
public:
    int findLHS(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int right = 0, left = 0, count = 0, len = nums.size();
        while(right < len) {
            while(left < right && nums[right] - nums[left] > 1) left ++;
            if(nums[right] - nums[left]) count = max(count, right - left + 1);
            right ++;
        }
        return count;
    }
};

还可以弄个 cache ,然后判断 任何一个 i - 1, i + 1 长度是否存在,存在则相加判断即可

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

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/113662623