题目来源:
https://leetcode.com/problems/longest-harmonious-subsequence/description/
转载请注明出处:
http://write.blog.csdn.net/postedit/78011611
题目:
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.
注意:可以不是连续的数字
参考答案:
JAVA版
public int findLHS(int[] nums) {
Map<Long, Integer> map = new HashMap<>();
for (long num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int result = 0;
for (long key : map.keySet()) {
if (map.containsKey(key + 1)) {
result = Math.max(result, map.get(key + 1) + map.get(key));
}
}
return result;
}
使用hashmap存储结构,只需要比较key和key+1的value数量
getOrDefault 函数查询不到结果,返回默认值,这里默认是返回0
C++版
int findLHS(vector<int>& nums) {
unordered_map<int,int>m;
for(auto i: nums)
m[i]++;
int res = 0;
for(auto it:m)
if(m.count(it.first-1)>0)
res = max(res, it.second+m[it.first-1]);
return res;
}
说明:
count 函数查询到结果返回 1,查询不到结果返回 0