Longest Consecutive Sequence
题目
给出一个无序整数数组,找出最长连续序列的长度。
比如:
给出数组[100, 4, 200, 1, 3, 2],
最长连续序列是[1, 2, 3, 4]. 返回它的最大长度:4.
你的算法复杂度为O(n)。
代码块
class Solution {
public static int longestConsecutive(int[] nums) {
HashMap<Integer,Integer> hs = new HashMap<Integer,Integer>();
if(nums.length == 0)return 0; //数组长度为
for(int i : nums){
hs.put(i,0);//将数组元素放进hashmap
}
int maxl = 1;//将最大长度赋为1
for(int i : nums){
if(hs.get(i)==1)
continue;
int temp = i ;
int current_max = 1;//当前最大长度
while(hs.containsKey(temp+1)){ //找有没有比key值大的连续数
current_max ++;
temp ++;
hs.put(temp,1);
}
temp = i ;//再将key给临时值
while(hs.containsKey(temp-1)){ //找有没有比key值小的连续数
current_max ++;
temp --;
hs.put(temp,1);
}
maxl =Math.max(maxl, current_max); //找出最大长度
}
return maxl;
}
public static void main(String[] args) {
int[] nums = {100,4,200,1,2,3};
System.out.println(longestConsecutive(nums));
}
}
代码分析
本题对算法复杂度进行了要求,所以不能使用排序,需要使用HashMap。
通过关键值来访问value,算法复杂度为O(n).
key | value |
---|---|
0 | a |
1 | b |
2 | c |
hm.get(0)=a
第一步:建立一个HashMap;
第二步:将数组的元素放进HashMap,同时将value值置为0;i为key值,然后将key赋给一个临时值,分别向上向下找连续值,有的话,就将value置为1,并将此作为是否再找的条件。
比如4,向上没有5,向下找到了(3,2,1)这些值的value为1,下次遇到就不再循环。
第三步:返回最大长度。
Math.max是找最大值的函数,也可以直接引用。