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

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