zoukankan      html  css  js  c++  java
  • [LeetCode] 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].

    Note: The length of the input array will not exceed 20,000.

    判断最长的和谐数组(数组中元素最大值和最小值相差仅为1),结果返回最长和谐数组的长度。首先使用map记录数组中元素出现的次数。然后对数组进行排序,最后遍历数组找出差为1的两个元素出现次数的和,并取最大值。注意判断边界条件,即给定数组长度为0或者1时没有和谐数组,此时应该返回0。

    class Solution {
    public:
        int findLHS(vector<int>& nums) {
            int res = INT_MIN, tmp = 0;
            if (nums.size() == 0 || nums.size() == 1)
                return 0;
            unordered_map<int, int> m;
            for (int num : nums)
                m[num]++;
            sort(nums.begin(), nums.end());
            for (int i = 1; i != nums.size(); i++) {
                if (nums[i] - nums[i - 1] == 1)
                    tmp = m[nums[i]] + m[nums[i - 1]];
                res = max(res, tmp);
            }
            return res;
        }
    };
    // 112 ms
  • 相关阅读:
    EXP8
    EXP7
    数据库作业
    windows下如何编译运行龙脉代码
    CVE-2019-6340 Drupal8's REST RCE 漏洞复现
    小黄衫获奖感言
    Exp6 MSF应用基础
    Exp5
    实验一 密码引擎-4-国䀄算法交叉测试(选做)
    2020-2021-2 20175335 丹增罗布 《网络对抗技术》Exp1 PC平台逆向破解
  • 原文地址:https://www.cnblogs.com/immjc/p/7218899.html
Copyright © 2011-2022 走看看