[leetcode]594. Longest Harmonious Subsequence
Analysis
ummm~—— [ummmm~]
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.
给定一个数组,求其子数组中最长的平衡数组大小。先排序,然后遍历,没想到打败了96%的solution,hiahia~
Implement
class Solution {
public:
int findLHS(vector<int>& nums) {
sort(nums.begin(), nums.end());
int len = nums.size();
int res = 0;
for(int i=0; i<len; i++){
int cnt = 1;
bool flag = false;
for(int j=i+1; j<len; j++){
if(nums[j] == nums[i])
cnt++;
else if(abs(nums[j]-nums[i]) == 1){
flag = true;
cnt++;
}
else
break;
}
if(!flag)
cnt = 0;
res = max(res, cnt);
}
return res;
}
};