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
  • 相关阅读:
    JS学习笔记-OO疑问之对象创建
    文件系统类型:
    Swift 编程语言新手教程
    数组长度计算
    tomcat配置文件server.xml具体解释
    openGL点精灵PointSprite具体解释: 纹理映射,旋转,缩放,移动
    iOS安全攻防(三):使用Reveal分析他人app
    逍遥叹
    oracle存储过程实例
    Java爬虫
  • 原文地址:https://www.cnblogs.com/immjc/p/7218899.html
Copyright © 2011-2022 走看看