LeetCode 128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

题目描述

给定一个非排序数组,求出最长连续序列。要求算法的时间复杂度为O(n)

解题思路

遍历一遍非排序数组,时间就要O(n)。想要在O(n)的时间内完成该算法,就需要我们在遍历到一个数据的时候,

查找与之连续的数字是否在该非排序数组中。遍历的时间复杂度已经是O(n),所以查找的时间复杂度只能是O(1),

因此,自然想到hash_set数据结构。

总体思路就是:取出hash_set中的首个元素,删除该元素,判断这个元素+1,-1是否在hash_set结构中

hash_set代码如下:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int ans = 0;
        hahs_set<int> hs;
        for(int i = 0; i < nums.size(); i++) {
        	hs.insert(nums[i]);
    	}
    	while(!hs.empty()) {
    		int val = *hs.begin();
    		int count = 1;
    		hs.erase(val);
    		for(int i = val + 1; hs.find(i) != hs.end(); ++i) {
    			count++;
    			hs.erase(i);
    		}
    		for(int i = val - 1; hs.find(i) != hs.end(); --i) {
    			count++;
    			hs.erase(i);
    		}
    		ans = max(ans,count);
    	}
    	return ans;
    }
};

提交之后发现编译错误  Compile Error

'hahs_set' was not declared in this scope

发现hash_set行不通,于是想尝试一下,直接使用set结构,对数据进行存储。

虽然set查找时间复杂度log(n),只是想尝试一下。结果竟然AC。

set代码如下

int longestConsecutive(vector<int>& nums) {
    int ans = 0;
    hash_set<int> hs;
    for(int i = 0; i < nums.size(); i++) {
    	hs.insert(nums[i]);
	}
	while(!hs.empty()) {
		int val = *hs.begin();
		int count = 1;
		hs.erase(val);
		for(int i = val + 1; hs.find(i) != hs.end(); ++i) {
			count++;
			hs.erase(i);
		}
		for(int i = val - 1; hs.find(i) != hs.end(); --i) {
			count++;
			hs.erase(i);
		}
		ans = max(ans,count);
	}
	return ans;
}

运行结果排名在39.15%

虽然通过,但是并不满足题目要求。因此就出查找hash_set为什么通不过。

网上查阅资料发现:hash_map,hash_set 等已经被废弃了,C++11用unordered_map,unordered_set等来替代

于是就使用unordered_set代替hash_set。

unordered_set代码:

    int longestConsecutive(vector<int>& nums) {
        int ans = 0;
        unordered_set<int> hs;
        for(int i = 0; i < nums.size(); i++) {
        	hs.insert(nums[i]);
    	}
    	while(!hs.empty()) {
    		int val = *hs.begin();
    		int count = 1;
    		hs.erase(val);
    		for(int i = val + 1; hs.find(i) != hs.end(); ++i) {
    			count++;
    			hs.erase(i);
    		}
    		for(int i = val - 1; hs.find(i) != hs.end(); --i) {
    			count++;
    			hs.erase(i);
    		}
    		ans = max(ans,count);
    	}
    	return ans;
    }

从运行结果分析,效率明显优于set,且满足题目要求


有更好的想法,欢迎交流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值