最长连续序列
2020-06-25 本文已影响0人
windUtterance
题目描述:
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
Java代码:
class Solution {
public static int longestConsecutive(int[] nums) {
if(nums.length <= 1) return nums.length;
int longest_balls = 0;
Set<Integer> array_set = new HashSet<Integer>();
for(int num : nums) array_set.add(num);
for(int num : array_set) {
if(!array_set.contains(num - 1)) {
int cur_num = num;
int cur_balls = 1;
while(array_set.contains(cur_num + 1)) {
cur_num += 1;
cur_balls += 1;
}
longest_balls = Math.max(longest_balls, cur_balls);
}
}
return longest_balls;
}
}