LeetCode 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.

题解:

在HashMap<Integer, Integer> hm中计数nums中每个element出现次数.

再看hm的key加一是否也在hm中能找到, 若能计算个数sum更新res.

Time Complexity: O(n). Space: O(n).

AC Java:

 1 class Solution {
 2     public int findLHS(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
 9         for(int n : nums){
10             hm.put(n, hm.getOrDefault(n, 0)+1);
11         }
12         
13         for(int i : hm.keySet()){
14             if(hm.containsKey(i+1)){
15                 res = Math.max(res, hm.get(i)+hm.get(i+1));
16             }
17         }
18         return res;
19     }
20 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7530343.html