Longest Consecutive Sequence ---LeetCode

来源:互联网 发布:mac skype 下载 编辑:程序博客网 时间:2024/05/01 14:21

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

解题思路:
这道题首先可以用排序很直接地解决。遍历排好序的数组,遇到连续的串就使 count 自加,一旦有间断就重置 count。并维护最大值 max。但是排序的时间复杂度是 O(nlogn),不符合题目要求的 O(n)。

solution 1 : Sort

public int longestConsecutive(int[] nums) {        if (nums == null || nums.length == 0) return 0;        Arrays.sort(nums);        int max = 0, count = 1;        for (int i=0; i < nums.length - 1; i++) {            if (nums[i+1] == nums[i] + 1) {                count++;            } else {                count = 1;            }            max = Math.max(max, count);        }        return max;    }

接下来我们想到用 HashSet 来解决,将元素装入 HashSet,接着遍历 HashSet,如果 HashSet 中包含了 n-1,就不用进行接下来的步骤了。

public class Solution {    public int longestConsecutive(int[] nums) {        if (nums == null || nums.length == 0)             return 0;        HashSet<Integer> set = new HashSet<>();        for (int n : nums)             set.add(n);        int max = 0;        for (int n : nums) {            if(set.contains(n-1)) continue;            int length = 0;            while(set.contains(n++)) length++;            max = Math.max(max, length);        }        return max;    }}
0 0