哈希表(哈希映射,哈希集合):力扣128. 最长连续序列

1、题目描述:

在这里插入图片描述

2、题解:

方法1:暴力法
先排序,然后判断
python 代码如下:

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        #暴力法
        nums.sort()
        # print(nums)
        res = 0
        for i in range(len(nums)):
            temp = 1
            for j in range(i + 1,len(nums)):
                if nums[j] == nums[j-1] + 1:
                    temp += 1
                elif nums[j] == nums[j - 1]:
                    temp = temp
                else:
                    break
            res = max(res,temp)
        return res

C++代码如下:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        // 朴素法
        int res = 0;
        sort(nums.begin(),nums.end());
        int n = nums.size();
        for (int i = 0;i < n;i++){
            int temp = 1;
            for (int j = i + 1;j < n ;j++)
            {
                if (nums[j] == nums[j - 1] + 1) 
                    temp ++;
                else if (nums[j] == nums[j - 1])
                    temp = temp;
                else
                    break;
            }
            res = max(res,temp);
        }
        return res;
    }
};

方法2:哈希映射,以空间换时间

设置一个哈希映射,
然后遍历nums:
	判断num的左右是否可以连起来,找上一个数的长度left,下一个数的长度right
	然后记录hashmap[num] = left + right + 1
	更新hashmap[num-left],hashmap[num+right]
	更新res
返回res

python 代码如下:

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        #哈希映射
        hashmap = collections.defaultdict(int)
        res = 0
        for num in nums:
            if num not in hashmap:
                #判断左右是否可以连起来
                left = hashmap[num - 1] if num - 1 in hashmap else 0
                right = hashmap[num + 1] if num + 1 in hashmap else 0
                #记录长度
                hashmap[num] = left + right +1
                #更新头尾
                hashmap[num - left] = left + right + 1
                hashmap[num + right] = left + right + 1
                res = max(res,right + left + 1)
        return res

C++代码:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        // 哈希表之哈希映射
        map<int,int> hashmap;
        int res = 0;
        for (auto num : nums){
            if (hashmap.count(num) == 0){
                // int left = hashmap.find(num - 1) != hashmap.end() ? hashmap[num - 1] :0;//h.find(x) == h.end() 表示不存在
                // int right = hashmap.find(num + 1) != hashmap.end() ? hashmap[num + 1] : 0;

                int left = hashmap.count(num - 1) ? hashmap[num - 1] :0; //count()返回出现次数
                int right = hashmap.count(num + 1)? hashmap[num + 1] : 0;
                
                int total = left + right + 1;
                res = max(res,total);
                hashmap[num] = total;
                hashmap[num - left] = total;
                hashmap[num + right] = total;
            }
        }
        return res ;
    }
};

或者:
哈希集合
Python代码:

思路:
先把nums用哈希表去重,定义一个最大值longest_streak
遍历: 
    只有当num为连续序列的第一个值的时候,才进行处理,也即if num - 1 not in num_set
	    记录下当前的数current_num = num,长度current_streak = 1
	    循环判断 如果当前的数 + 1 在哈希表中,就更新current_num,current_streak
	    更新最大值longest_streak
返回最大值longest_streak
class Solution:
    def longestConsecutive(self, nums):
        longest_streak = 0
        num_set = set(nums)
        for num in num_set:
            if num - 1 not in num_set:
                current_num = num
                current_streak = 1

                while current_num + 1 in num_set:
                    current_num += 1
                    current_streak += 1
                longest_streak = max(longest_streak, current_streak)
        return longest_streak

C++代码:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        // 哈希表之哈希集合
        unordered_set<int> sets;
        int res = 0;
        for (auto num : nums){
            sets.insert(num);
        }
        for (auto num : sets){
            if (!sets.count(num - 1)){
                int current_num = num;
                int current_streak = 1;
                while (sets.count(current_num + 1)){
                    current_num ++;
                    current_streak++;
                }
                res = max(res,current_streak);
            }
        }
        return res;
    }
};

3、复杂度分析:

方法1:
时间复杂度:O(NlogN),排序的复杂度
空间复杂度:O(1)
方法2:
时间复杂度:O(N),相当于以空间换时间
空间复杂度:O(N)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值