LeetCode Array 128 Longest Consecutive Sequence

4 篇文章 0 订阅

128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.

Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

solution 1: brute force

对于数组中的每个数,检查和它紧连的数是否在数组中。
复杂度分析:
时间: O ( n 3 ) O(n^3) O(n3)
空间: O ( 1 ) O(1) O(1)

solution 2: sorting

对数组进行排序,然后求最大长度

        public int longestConsecutive(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            int len = nums.length;
            Arrays.sort(nums);
            int longest = 1;
            int currentlen = 1;
            for (int i = 1; i < len; i++) {
                if (nums[i] != nums[i-1]) {// skip duplicates
                    if (nums[i] == nums[i-1]+1) {
                        currentlen++;
                    } else {
                        longest = Math.max(currentlen, longest);
                        currentlen = 1;
                    }
                }
            }
            return Math.max(currentlen, longest);
        }

时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn),采用了排序,排序复杂度为 O ( n l o g n ) O(nlogn) O(nlogn),遍历数组复杂度为 O ( n ) O(n) O(n),总体复杂度是 O ( n l o g n ) O(nlogn) O(nlogn)

solution 3: HashSet

HashSet可以解决duplicates的问题,同时把查询某个值是否在数组中的复杂度降到了 O ( 1 ) O(1) O(1). 同时为了进一步控制复杂度,对于已经确定在某一sequence中的元素,不要重复计算。具体方法是,遍历HashSet中的元素,如果set中不存在比这个元素刚好大一的元素,(不存在刚好大一的元素说明这个元素并不在目前任何sequence中),定义长度(currentlen)和sequence的起始元素(currentnum)。然后计算得到以这个元素为起始的sequence的长度。
不存在刚好大一的元素说明这个元素并不在目前任何sequence中:因为我们在判断contains时用的num+1,而在while循环中计算时用的是currentnum - 1,两个遍历的方向恰好相反,确保了我们是新建了一个sequence,而不是任何一个sequence的substring。
同理也可以在 if 判断时用num-1,在while循环中用currentnum + 1

    public class solution2 {
        public int longestConsecutive(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            int len = nums.length;
            HashSet<Integer> set = new HashSet<>();
            for (int i = 0; i < len; i++) {
                set.add(nums[i]);
            }
            int longest = 1;

            for (int num : set) {
                if (!set.contains(num + 1)) {
                    int currentlen = 1;
                    int currentnum = num;
                    while (set.contains(currentnum - 1)) {
                        currentnum--;
                        currentlen++;
                    }
                    longest = Math.max(currentlen, longest);
                }
            }
            return longest;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值