[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
原文地址:https://www.cnblogs.com/immjc/p/7218899.html