码迷,mamicode.com
首页 > 其他好文 > 详细

128. Longest Consecutive Sequence

时间:2019-03-11 13:06:41      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:NPU   longest   tput   math   class   lex   int   ted   complex   

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.
class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();
        for(int i : nums) set.add(i);
        int res = 0;
        for(int i: nums){
            int len = 1;
            for(int j = i-1; set.contains(j); j--){
                len++;
                set.remove(j);
            }
            for(int k = i+1; set.contains(k); k++){
                len++;
                set.remove(k);
            }
            res = Math.max(len, res);
        }
        return res;
    }
}

划重点!HashSet的查找的效率是O(1),所以加上遍历才能达到O(n)

思想是以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。

128. Longest Consecutive Sequence

标签:NPU   longest   tput   math   class   lex   int   ted   complex   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10509826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!