https://leetcode.com/problems/longest-consecutive-sequence/
一、使用先排序,然后统计最长连续序列的方法。
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
nums = sorted(nums)
max_len = 1
cur_len = 1
for i in range(1, len(nums)):
if nums[i] != nums[i-1]:
if nums[i] == nums[i-1] + 1:
cur_len += 1
else:
max_len = max(max_len, cur_len)
cur_len = 1
return max(max_len, cur_len)
二、使用hashmap,key,value的值分别为当前值与边界的范围。使用left和right的值更新当前的边界范围,更新当前值的时候也更新边界。
import java.util.HashMap;
// 100, 4, 200, 1, 3, 2
class num128 {
public int longestConsecutive(int[] nums) {
int max = 0;
HashMap<Integer, Integer> map = new HashMap<>();
for(int num:nums){
if(map.containsKey(num)) continue;
int left = map.getOrDefault(num-1, 0);
int right = map.getOrDefault(num+1, 0);
int sum = left + right + 1;
max = Math.max(sum, max);
map.put(num, sum);
if(left > 0) map.put(num-left, sum);
if(right > 0) map.put(num+right, sum);
}
return max;
}
public static void main(String[] args) {
num128 solution = new num128();
int[] nums = {100, 4, 200, 1, 3, 2};
int result = solution.longestConsecutive(nums);
System.out.println(result);
}
}