当前位置:   article > 正文

LeetCode hot100-3

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

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

我的解法是可以通过的,我觉得比官方解法稍微好理解一点。
思路就是,排序之后判断相邻两个元素是否连续,由于有重复的还需要去重。而Set本身就可以去重+排序。
最常用的HashSet只能实现去重,不能排序的(既不是加进去的顺序,也不是自然排序的顺序),要用TreeSet(TreeSet是自然顺序1到9那种,还有个LinkedHashSet是元素添加顺序)。以及Set是不能直接得到第i个元素的,所以把set转成了List。还有集合的类型不能用int,要用包装成Integer。

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> s = new TreeSet<Integer>();
        for (int i = 0; i < nums.length; i++) {
            s.add(nums[i]);
        }
        List<Integer> l = new ArrayList<Integer>(s);
        // s.addAll(Arrays.asList(nums));
        int max = 1;
        int now = 1;
        for (int i = 0; i < l.size() - 1; i++) {
            if (l.get(i + 1) - l.get(i) == 1) {
                now++;
            } else {
                now = 1;
            }
            if (now > max) {
                max = now;
            }

        }
        if (nums.length == 0) {
            return 0;
        } else {
            return max;
        }

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

官方解法
就是把最常见的两重循环优化了一下做了不必要情况下的跳出。在while循环中当前元素的往更大的找连续元素,看能找到几个。然后外层循环就是一个一个遍历,如果已经有更小的连续元素的话,那整个这个元素已经在while循环中找过了,就不再处理。

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> num_set = new HashSet<Integer>();
        for (int num : nums) {
            num_set.add(num);
        }

        int longestStreak = 0;

        for (int num : num_set) {
            if (!num_set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                while (num_set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/longest-consecutive-sequence/solutions/276931/zui-chang-lian-xu-xu-lie-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/209315
推荐阅读
相关标签
  

闽ICP备14008679号