• 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)

  • 相关阅读:
    Golang的值类型和引用类型的范围、存储区域、区别
    ubuntu下ssh使用 与 SCP 使用
    ubuntu 搭建svn服务器
    Java中Math类的几个四舍五入方法的区别
    mongoDB 批量更改数据,某个字段值等于另一个字段值
    mongoDB 查询附近的人的语句
    mongodb常用操作语句
    JAVA 根据经纬度算出附近的正方形的四个角的经纬度
    JAVA 计算地球上任意两点(经纬度)距离
    Mongodb数据备份恢复
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7404827.html
Copyright © 2020-2023  润新知