[LeetCode] 594. Longest Harmonious Subsequence

题:https://leetcode.com/problems/longest-harmonious-subsequence/description/

题目

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.

Example 1:

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

Note: The length of the input array will not exceed 20,000.

题目大意

求最长的和谐序列,和谐序列中最大数和最小数只差正好为 1,应该注意的是序列的元素不一定是数组的连续元素。

思路

把每个元素的存入 map中。
map 中 key为元素,value 为元素的出现次数。

遍历每个map中的元素num,若num+1也在map中。
res = Math.max(map.get(num),map.get(num+1))

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

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83897501
今日推荐