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)

posted @   贼心~不死  阅读(105)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示