We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1
.
Given an integer array nums
, return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
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
Constraints:
1 <= nums.length <= 2 * 10^4
-10^9 <= nums[i] <= 10^9
【C++】
1. sort
class Solution {
public:
int findLHS(vector<int>& nums) {
sort(nums.begin(), nums.end());
int res = 0 , start = 0, newstart = 0;
for (int i=1; i<nums.size(); ++i) {
if (nums[i]-nums[start] > 1) start = newstart;
if (nums[i] != nums[i-1]) newstart = i;
if (nums[i]-nums[start] == 1) res = max(res, i-start+1);
}
return res;
}
};
2. map
class Solution {
public:
int findLHS(vector<int>& nums) {
map<int, int> countForNum;
for (int num : nums) {
if(countForNum.find(num) == countForNum.end()) countForNum[num] = 1;
else countForNum[num]++;
}
int longest = 0;
for(map<int, int>::iterator it=countForNum.begin(); it!=countForNum.end(); ++it) {
int num = it->first;
if(countForNum.find(num+1) != countForNum.end()) {
longest = max(longest, countForNum[num+1] + countForNum[num]);
}
}
return longest;
}
};
【Java】
class Solution {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int res = 0 , start = 0, newstart = 0;
for (int i=1; i<nums.length; ++i) {
if (nums[i]-nums[start] > 1) start = newstart;
if (nums[i] != nums[i-1]) newstart = i;
if (nums[i]-nums[start] == 1) res = Math.max(res, i-start+1);
}
return res;
}
}