lee128
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
首先想到是arrays排序后count O(n)
需注意的是 ,有相同数 就跳过不算
class Solution {
public int longestConsecutive(int[] nums) {
int n = nums.length ;
if(nums == null || nums.length==0) return 0;
Arrays.sort(nums);
int count = 1;
int maxCount = 1;
for(int i=0;i<n-1;i++){
if(nums[i+1] == nums[i]+1){
count++;
}else if(nums[i+1] == nums[i]){
continue;
}else{
count=1;
}
maxCount = Math.max(maxCount,count);
}
return maxCount;
}
}
O(n)方法,hashset存,遍历一遍取并删
注意:set.remove(num) 如果有num就true,无就false,根据这个条件可以得出以下简单写法。
- 先把元素都装到set中,
- 遍历数组
每次看当前元素 有没有 有的话就 先看小于它得,累加,再看大于它的,累加, - 每次更新最大值max
class Solution {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length==0) return 0;
HashSet<Integer> set = new HashSet<>();
for(int num:nums){
set.add(num);
}
// System.out.println(set);
int maxCount = 0;
for(int num:nums){
if(set.remove(num)){
int count = 1,cur = num;
while(set.remove(cur-1)) {
count++;
cur--;
// System.out.println(count);
}
// System.out.println("dangqian"+count+" "+maxCount);
cur = num;
while(set.remove(cur+1)) {
cur++;
count++;
}
maxCount = Math.max(maxCount,count);
// System.out.println(count+" "+maxCount);
}
}
return maxCount;
}
}