zoukankan      html  css  js  c++  java
  • 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]
    
  • 相关阅读:
    人机猜拳
    M1分数分配
    postmortem report of period M1
    视频文档分享网站场景测试说明书
    功能规格说明书
    11.9Daily Scrum
    11.6Daily Scrum
    需求博客
    11.5Daily Scrum
    11.3Daily Scrum
  • 原文地址:https://www.cnblogs.com/pk28/p/8483627.html
Copyright © 2011-2022 走看看