問題
給定一個未排序的整數數組
比如對於數組[
public class Solution {
public int longestConsecutive(int[] num) {
//write your code here
}
}
解法思路
因為要求復雜度是O(n)
不多說了
private static class Sequence{
int start;
int end;
int length;
}
public int longestConsecutive(int[] num) {
int len =
if(num==null || (len=num
return
}
Map<Integer
Map<Integer
int maxLength =
for(int i=
Sequence s = null;
int v = num[i];
if(ntainsKey(v) || ntainsKey(v)){
continue;
}
if(ntainsKey(v+
s = start
s
++s
while(ntainsKey(s
Sequence m = end
start
s
s
}
start
}
else if(ntainsKey(v
s = end
s
++s
while(ntainsKey(s
Sequence m = start
end
s
s
}
end
}
else{
s = new Sequence();
s
s
start
end
}
//System
if(maxLength<s
maxLength = s
}
}
return maxLength;
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26932.html