• LeetCode——最长连续序列


    public int longestConsecutive(int[] nums) {
            int result = 0;
    
            Set<Integer> set = new HashSet<>();
            for(int i = 0 ; i < nums.length ; i++)
            {
                set.add(nums[i]);
               
            }
            for(int i = 0; i < nums.length ; i++)
            {
                if(!set.contains(nums[i] -1)) //找到起点
                {
                    int curValue = nums[i];
                    int curLen = 1;
                    while(set.contains(curValue+1)) //寻找最长的连续序列
                    {
                        curLen++;
                        curValue++;
                    }
                    result = Math.max(result,curLen);
                }
            }
            return result;
        }

    利用Hashset查找元素时间复杂度近似为O(1)

  • 相关阅读:
    从Python到Web开发
    源码安装缺少configure文件
    5
    4
    3
    2
    42
    1
    18
    41
  • 原文地址:https://www.cnblogs.com/swqblog/p/13259464.html
Copyright © 2020-2023  润新知