LeetCode 594. Longest Harmonious Subsequence

594. Longest Harmonious Subsequence

Description

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

Solution

  • 题意即给定一个数组,在其中找到找到一个最长数列,该数列保证只有两种数且两数之差为1。
  • 我的做法就是将nums中的数通过map映射到一个较小的方便遍历的数,然后通过hnum保存这些数的个数,findvalue实现通过key查找value,在遍历的时候,根据差值为1来更新rnt。代码如下,代码比语言更好理解……
  • 由于我对c++不是很熟悉,vector、map用得十分凌乱,代码可能多处冗余,请不吝指教。
class Solution {
public:
    int findLHS(vector<int>& nums) {
        int hnum[20010] = {0},MIN = 100000,MAX = -100000,index = 0,rnt = 0;
        map<int,int> m;
        int findvalue[20010];
        sort(nums.begin(),nums.end());
        for (int i = 0;i < nums.size();i++) {
            if (m.count(nums[i]) > 0) {
                hnum[m[nums[i]]]++;
            }
            else {
                m[nums[i]] = index++;
                hnum[index - 1] = 1;
                findvalue[index - 1] = nums[i]; 
            }
        }

        for (int i = 1;i < index;i++) {
            if (findvalue[i] - findvalue[i - 1] == 1) rnt = max(rnt,hnum[i - 1] + hnum[i]);
        }
        return rnt;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值