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
  • 相关阅读:
    zoj 3627#模拟#枚举
    Codeforces 432D Prefixes and Suffixes kmp
    hdu 4778 Gems Fight! 状压dp
    CodeForces 379D 暴力 枚举
    HDU 4022 stl multiset
    手动转一下田神的2048
    【ZOJ】3785 What day is that day? ——KMP 暴力打表找规律
    poj 3254 状压dp
    C++中运算符的优先级
    内存中的数据对齐
  • 原文地址:https://www.cnblogs.com/immjc/p/7218899.html
Copyright © 2011-2022 走看看