leetcode 128. Longest Consecutive Sequence 最长连续序列(中等)

2年前 (2022) 程序员胖胖胖虎阿
176 0 0

一、题目大意

https://leetcode.cn/problems/longest-consecutive-sequence

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

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

输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
 

提示:

0 <= nums.length <= 105
-109 <= nums[i] <= 109

二、解题思路

可以把所有数字放到一个哈希表,然后不断地从哈希表中任意取一个值,并删除掉其之前之后的所有连续数字,然后更新目前的最长连续序列长度。重复这一过程,就可以找到所有的连续数字序列,顺便找出最长的。

三、解题方法

3.1 Java实现-超时版

public class Solution1 {
    public int longestConsecutive(int[] nums) {
        Set<Integer> intSet = new HashSet<>();
        for (int num : nums) {
            intSet.add(num);
        }
        int ans = 0;
        while (!intSet.isEmpty()) {
            int cur = intSet.stream().findFirst().get();
            intSet.remove(cur);
            int pre = cur - 1;
            int next = cur + 1;
            while(intSet.contains(pre)) {
                intSet.remove(pre--);
            }
            while(intSet.contains(next)) {
                intSet.remove(next++);
            }
            ans = Math.max(ans, next - pre - 1);
        }
        return ans;
    }
}

3.2 Java实现-通过版

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

四、总结小记

  • 2022/8/16 Map的好些方法在处理大数据量时要慎用呀

相关文章

暂无评论

暂无评论...