美文网首页
最长连续序列

最长连续序列

作者: 二进制的二哈 | 来源:发表于2019-12-21 23:44 被阅读0次

    题目来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-consecutive-sequence

    给定一个未排序的整数数组,找出最长连续序列的长度。

    要求算法的时间复杂度为 O(n)。

    示例:

    输入: [100, 4, 200, 1, 3, 2]
    输出: 4
    解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
    

    利用HashMap或者HashSet解法:

    class Solution {
        public int longestConsecutive(int[] nums) {
            Set<Integer> set = new HashSet<Integer>();
            for (int num : nums) {
                set.add(num);
            }
            int ans = 0;
            for (int num : nums) {
                if (!set.contains(num-1)){
                    int len = 1;
                    while (set.contains(++num)){
                        len++;
                    }
                    ans = Math.max(ans, len);
                }
            }
            return ans;
        }
    }
    

    相关文章

      网友评论

          本文标题:最长连续序列

          本文链接:https://www.haomeiwen.com/subject/kxvnnctx.html