Wednesday, March 11, 2015

LeetCode Longest Consecutive Sequence


Use HashSet
public int longestConsecutive(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();
for (int i : nums) {
set.add(i);
}
int max=0;
for (int i:nums) {
int cnt = 1;
set.remove(i);
int temp = i;
while (set.contains(temp-1)) {
set.remove(temp-1);
temp--;
cnt++;
}
temp=i;
while (set.contains(temp+1)) {
set.remove(temp+1);
temp++;
cnt++;
}
max = Math.max(max, cnt);
}
return max;
}

Use HashMap
This is from Jiaxin's leetcode
http://shanjiaxin.blogspot.com/2014/04/longest-consecutive-sequence-leetcode.html
public int longestConsecutive(int[] num) {
if (num == null || num.length == 0) {
return 0;
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int value : num) {
map.put(value, 0);
}
int maxLength = 1;
for (int i : num) {
if (map.get(i) == 1) {
continue;
}
// Search Increasing sequence for current element(right side)
int temp = i;
int current_max = 1;
while (map.containsKey(temp + 1)) {
current_max++;
temp++;
map.put(temp, 1);
}
// Search Descending sequence for current element(left side)
temp = i;
while (map.containsKey(temp - 1)) {
current_max++;
temp --;
map.put(temp, 1);
}
maxLength = Math.max(current_max, maxLength);
}
return maxLength;
}

No comments:

Post a Comment