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]
posted on 2018-02-28 14:54  Beserious  阅读(105)  评论(0编辑  收藏  举报