您的位置:首页 > 产品设计 > UI/UE

leetcode做题总结,题目Longest Consecutive Sequence 2013/02/13

2014-08-17 06:07 399 查看
题目是在一个数组中找最长连续队列,一般这种需要迅速找值的题目首先想到的就是HashMap,将数组里的值当成key打入map中,接下来就是找序列了,由于要求复杂度时O(n)所以每个元素只能扫一遍,我的思路是先找到每个序列的起点,只从起点开始向后找序列,如果不是起点就跳过。

public int longestConsecutive(int[] num) {
int stor=1;
int tmp;
int j;
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int amount = num.length;
for(int i=0;i<amount;i++){
m.put(num[i],1);
}
for(int i=0;i<amount;i++){
j=num[i];
if(m.containsKey(j)&&((i==0&&m.containsKey(j+1))||(m.containsKey(j+1)&&!m.containsKey(j-1)))){
tmp=2;
j=j+2;
while(m.containsKey(j++))tmp++;
if(tmp>stor) stor=tmp;
}
}
return stor;
}


Update 2015/08/22: 上面的做法没有必要从每个初始值开始,只需要对每个点向左右同时进行扩展求出最长序列即可,而且使用hashset即可无需使用map

public class Solution {
/**
* @param nums: A list of integers
* @return an integer
*/
public int longestConsecutive(int[] num) {
// write you code here
if (num.length == 0) {
return 0;
}

Set<Integer> set = new HashSet<Integer>();
int max = 1;

for (int e : num)
set.add(e);

for (int e : num) {
int left = e - 1;
int right = e + 1;
int count = 1;

while (set.contains(left)) {
count++;
set.remove(left);
left--;
}

while (set.contains(right)) {
count++;
set.remove(right);
right++;
}

max = Math.max(count, max);
}

return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: