leetcode 128. Longest Consecutive Sequence

解法一:

  • 先进行排序,然后比较

但sort不一定让用

解法二:

  • 遍历每一个数nums,定义两个值 pre,next; pre=nums--, next=nums++;找是否存在
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
// 由于不考虑重复的情况,所以用set set<int> s(nums.begin(),nums.end()); int res=0; for(int i=0;i<nums.size();i++) { int pre=nums[i]-1; int next=nums[i]+1; while(s.count(pre)!=0)pre--; while(s.count(next)!=0) next++; res=max(res, (next-pre-1)); // cout<<pre<<" "<<next<<endl; } return res; } };

  但是这个解法里根本没有考虑已经被考虑的元素:

假设为【1,2,3,4】

从1 开始 1 得到0-5;

接着考虑2: 2 也是0-5

所以被考虑过的元素要删除。。。。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> s(nums.begin(),nums.end());
        int res=0;
        for(int i=0;i<nums.size();i++)
        {
            if(s.find(nums[i])==s.end())
                continue;
//删除考虑过的元素 s.erase(nums[i]); int pre=nums[i]-1; int next=nums[i]+1; while(s.count(pre)!=0) s.erase(pre--); while(s.count(next)!=0) s.erase(next++); res=max(res, (next-pre-1)); // cout<<pre<<" "<<next<<endl; } return res; } };

set 为有序且不重复:

set:  nums=[1,2,3,4,3]

set(num.begin(), nums.end())

得到的set为: [1,2,3,4];

nums=[3,2,1,3,4]

得到的set为:[1,2,3,4]

unordered_set

没有顺序

python 解法:

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        maxlen=0;
        numset=set(nums)
        for n in set(nums):
            if(n not in numset):
                continue
                
            prenum=n-1;
            nextnum=n+1;
            while(prenum in numset):
                numset.discard(prenum)
                prenum-=1
                
            while(nextnum in numset):
                numset.discard(nextnum)
                nextnum+=1
            maxlen=max(maxlen, nextnum-prenum-1)
        return maxlen

  

python 中的set操作:

python 中的main 函数:

if __name__=="__main__": 类似java与c中的main主函数。。。

if __name__=="__main__":

nums=[100, 4, 200,1,3,2]
s=Solution()
c=s.longestConsecutive(nums)

print(c)

原文地址:https://www.cnblogs.com/fanhaha/p/7404827.html