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.
public class Solution {
public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, int[]> cache = new HashMap<Integer, int[]>();
int max = 0;
for(int n : num) {
if(cache.containsKey(n)) {
continue;
}
int[] mid = new int[2];
boolean hasLeft = false;
boolean hasRight = false;
int leftBound = 0;
int rightBound = 0;
if(cache.containsKey(n-1)) {
int low = cache.get(n-1)[0];
mid[0] = low+1;
leftBound = n - low -1;
hasLeft = true;
}
if(cache.containsKey(n+1)) {
int high = cache.get(n+1)[1];
mid[1] = high+1;
rightBound = n + high + 1;
hasRight = true;
}
if(hasLeft) {
cache.get(leftBound)[1] += mid[1] + 1;
}
if(hasRight) {
cache.get(rightBound)[0] += mid[0] + 1;
}
cache.put(n, mid);
if(mid[0]+mid[1]+1>max) {
max = mid[0] + mid[1]+1;
}
}
return max;
}
}
public class Solution {
public int longestConsecutive(int[] num) {
int longest = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0;i < num.length;i++){
// if there is no duplicates, these two lines can be commented
if(map.containsKey(num[i])) continue;
map.put(num[i],1);
int end = num[i];
int begin = num[i];
if(map.containsKey(num[i]+1))
end = num[i] + map.get(num[i]+1);
if(map.containsKey(num[i]-1))
begin = num[i] - map.get(num[i]-1);
longest = Math.max(longest, end-begin+1);
map.put(end, end-begin+1);
map.put(begin, end-begin+1);
}
return longest;
}
}
=========
public class Solution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
// the max length of the sequence containing this element
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int max = 1;
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if (map.containsKey(n)) {
continue;
}
int start = n;
int end = n;
if (map.containsKey(n + 1)) {
end = map.get(n + 1) + n;
}
if (map.containsKey(n - 1)) {
start = n - map.get(n - 1);
}
int len = end - start + 1;
max = Math.max(max, len);
map.put(start, len);
map.put(end, len);
map.put(n, len);
}
return max;
}
}
没有评论:
发表评论