leetcode 594. Longest Harmonious Subsequence
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].
题目大意:给定数组,在数组中找到一个序列,使得这个序列的最大值和最小值只差恰好等于1,返回这个序列的最大长度。
思路:先排序,每次查找值为1+x的位置,取最大的即可,时间复杂度O(lgn)
class Solution {
public:
int findLHS(vector<int>& nums) {
sort(nums.begin(), nums.end());
if (nums.size() == 1) return 0;
int ans = 0;
for (int i = 0; i < nums.size(); ++i) {
int x = nums[i] + 1;
int pos = upper_bound(nums.begin()+i, nums.end(), x) - nums.begin();
//cout << pos << endl;
if (nums[pos-1] == x) {
ans = max(ans, pos - i);
}
}
return ans;
}
};
//[1,2,2,2,3,3,5,7]
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号:
![](https://images.cnblogs.com/cnblogs_com/pk28/1069498/o_qrcode_for_gh_db07a03aaa56_344.jpg)