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

128. Longest Consecutive Sequence

时间:2015-04-30 00:58:10      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

保证O(n)时间,通常要用map,这里每次到一个数,向前看+1数是否存在,向后看-1数是否存在,如存在,则继续滚动,length++。

时间和空间复杂度都是O(n)

public class Solution {
  public int longestConsecutive(int[] nums) {
    Map<Integer, Boolean> map = new HashMap<>();
    for (int n : nums) {
      map.put(n, false);
    }
    int maxLength = 0;
    for (int n : nums) {
      if (map.get(n)) {
        continue;
      }
      int i = n + 1;
      int length = 1;
      while(map.containsKey(i)) {
        map.put(i, true);
        length++;
        i++;
      }
      i = n - 1;
      while(map.containsKey(i)) {
        map.put(i, true);
        length++;
        i--;
      }
      if (length > maxLength) {
        maxLength = length;
      }
    }
    return maxLength;
  }
}

128. Longest Consecutive Sequence

标签:

原文地址:http://www.cnblogs.com/shini/p/4467864.html

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