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

LeetCode Longest Consecutive Sequence

2015-10-18 08:03 786 查看
原题链接在这里:https://leetcode.com/problems/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.

题解:

用HashSet把所有点放入hs中,从nums[0]开始检查是否包含这个点,若是包含,就看它往下能走多远,然后看往上能走多远,走过的点从hs中移除,维护最大值。

Time Complexity O(n), Space O(n).

AC Java:

public class Solution {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
HashSet<Integer> hs = new HashSet<Integer>();
//put every element into hashset
for(int i = 0; i<nums.length; i++){
hs.add(nums[i]);
}
int res = 0;
for(int i = 0; i<nums.length; i++){
if(hs.contains(nums[i])){
int count = 1;
//check how many nodes are there in lower branch
int low = nums[i] - 1;
while(hs.contains(low)){
hs.remove(low);
low--;
count++;
}
//check how many nodes are there in higher branch
int high = nums[i] + 1;
while(hs.contains(high)){
hs.remove(high);
high++;
count++;
}
res = Math.max(res,count);
}
}
return res;
}
}


类似Binary Tree Longest Consecutive Sequence.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: