public class Solution {
/**
* @param nums: A list of integers
* @return an integer
*/
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
int longest = 0;
for (int i = 0; i < nums.length; i++) {
int down = nums[i] - 1;
while (set.contains(down)) {
set.remove(down);
down--;
}
int up = nums[i] + 1;
while (set.contains(up)) {
set.remove(up);
up++;
}
longest = Math.max(longest, up - down - 1);
}
return longest;
}
}
public class Solution {
/**
* @param num: A list of integers
* @return: An integer
*/
public int longestConsecutive(int[] num) {
// write your code here
if (num == null || num.length == 0) {
return 0;
}
Map<Integer, Integer> streak = new HashMap<>();
int max = 0;
for (int n : num) {
if (streak.containsKey(n)) {
continue;
}
int leftCount = 0, rightCount = 0;
if (streak.containsKey(n - 1)) {
leftCount = streak.get(n - 1);
}
if (streak.containsKey(n + 1)) {
rightCount = streak.get(n + 1);
}
int count = leftCount + rightCount + 1;
max = Math.max(max, count);
streak.put(n, count);
streak.put(n - leftCount, count);
streak.put(n + rightCount, count);
}
return max;
}
}
Version 3:
pq排了一下序, set去了一下重复, 剩下就没啥难度了, 应该算O(N)的吧
public class Solution {
/**
* @param num: A list of integers
* @return: An integer
*/
public int longestConsecutive(int[] num) {
// write your code here
if (num == null || num.length == 0) {
return 0;
}
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < num.length; i++) {
if (!set.contains(num[i])) {
set.add(num[i]);
pq.offer(num[i]);
}
}
int res = 1;
int temp = 1;
int start = pq.poll();
while (!pq.isEmpty()) {
int curr = pq.poll();
if (curr == start + 1) {
start = curr;
temp++;
} else {
temp = 1;
start = curr;
}
res = Math.max(res, temp);
}
return res;
}
}