leetcode 594 && 128

 leetcode 594. 最长和谐子序列  easy          

题目描述:

 

解题思路:

hash表统计每个数出现过的次数,然后遍历hash,求以当前数为最小值的最长和谐子序列,其实也就是求当前数 和(当前数+1)的次数之和。

代码:

class Solution {
public:
    int findLHS(vector<int>& nums) {

        unordered_map<int, int> hash;
        for(int i:nums)
            hash[i]++;
        int res = 0;
        for(pair<int, int> p: hash)
        {
            if (hash.count(p.first+1))
            {
                int one = p.second + hash[p.first+1];
                res = max(res, one);
            }

        }
        return res;

    }
};

 leetcode 128. 最长连续序列  medium          

题目描述:

解题思路:

方法一:先排序,那就是在一个有序数组里 找数字连续的最长序列了

方法二:枚举 数组形成的所有序列的起点,然后求这个序列的长度,而只要当前的点的前一点不在数组里,当前这个点就是序列的起点。

代码:

// 方法二
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {

        unordered_set<int> hash(nums.begin(), nums.end());
        int res = 0;
        for (int num: nums){
            if (hash.count(num-1))
                continue;
            int len = 1;
            while (hash.count(num+1)){
                len++;
                num++;
            }

            res = max(res, len);
        }

        return res;

    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值