leetcode -- Longest Consecutive Sequence

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)---->使用hash,空间换时间

对于当前数N,我们检查N-1, N-2, N-3....N-K是否在hashmap中

对于当前数N,我们检查N+1, N+2, N+3....N+j是否在hashmap中

这里使用visited数组来记录已经访问过的数,这样减少检查次数,时间复杂度O(n)

 1 public class Solution {
 2     public int longestConsecutive(int[] num) {
 3         int len = num.length;
 4         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 5         for(int i = 0; i < len; i++){
 6             map.put(num[i], i);            
 7         }
 8         int result = 0, count;
 9         int[] visited = new int[len];
10         for(int i = 0; i < len; i++){
11             visited[i] = 0;
12         }
13         for(int i = 0; i < len; i++){
14             count = 1;
15             if(visited[i] == 1){
16                 continue;
17             }
18             int index = num[i];
19             visited[i] = 1;
20             while(map.containsKey(--index)){
21                 count ++;
22                 visited[map.get(index)] = 1;
23             }
24             index = num[i];
25             while(map.containsKey(++index)){
26                 count ++;
27                 visited[map.get(index)] = 1;
28             }
29             if(count > result){
30                 result = count;
31             }            
32         }
33         return result;
34     }
35 }

 

posted @ 2013-08-17 21:44  feiling  阅读(363)  评论(0编辑  收藏  举报