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.
思路来自Code_ganker:http://blog.csdn.net/linhuanmars/article/details/22964467
注意:关于时间复杂度的解释,双层loop是O(n*n),但是不同层的2个loop是O(2*n)=O(n)。
以及Souldak:http://blog.csdn.net/souldak/article/details/11473425
注意:对于HashSet和HashMap的理解!
<span style="font-size:14px;">public class Solution {
public int longestConsecutive(int[] num) {
if(num.length==0 || num==null)
return 0;
int res=1;
HashSet<Integer> set = new HashSet<Integer>();
for(int i=0; i<num.length; i++){//遍历Array,把元素放入HashSet
set.add(num[i]);
}
while(!set.isEmpty()){
Iterator<Integer> it = set.iterator();
int item = it.next(); //迭代器获取当前元素并删之
set.remove(item); //【注意1】
int len=1;
int i=item-1; //比当前值小1的连续Integer
while(set.contains(i)){
set.remove(i--);
len++;
}
i=item+1; //比当前值大1的连续Integer
while(set.contains(i)){
set.remove(i++);
len++;
}
if(len>res)
res=len;
}
return res;//Math.max(res,len),compile Error【注意3】
}
}</span>
【注意1】没写remove,OJ时候[0,0]的TestCase超时了。在JDK上run过,num=[0,0]的结果是1。
【注意2】此处的return表达式不可以含len,因为len在while内定义,只限于循环内部使用!
【注意3】HashSet和Iterator要import java.util.*;HashSet不可以存相同值,否则第二次set.add(sameItem),会返回false。
【后记】用HashMap的做法,来源于“【LV3】霸yx”
<span style="font-size:14px;">public class Solution {
public int longestConsecutive(int[] num) {
if(num.length==0 || num==null)
return 0;
int maxl=1;
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int item:num)
map.put(item,0);
for(int i:num){
if(map.get(i)==1)
continue;
int temp=i;
int currentMax=1;
while(map.containsKey(temp+1)){
currentMax++;
temp++;
map.put(temp,1);
}
temp=i;
while(map.containsKey(temp-1)){
currentMax++;
temp--;
map.put(temp,1);
}
maxl=Math.max(maxl,currentMax);
}
return maxl;
}
}</span>