problem
LeetCode 128. Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
solution
思路过程
- 首先没有排序,还不知道最小的值是多少
- 最暴力的方法就是,找到最小值和最大值,然后就使维护一个最大的序列,从最小值遍历到最大值,这样不符合题目中O(n)的复杂度
- 再想出来的就是排序先,这样就可以从第一个直接比较到最后一个,那么排序所用的时间复杂度算到最终的里面去吗?应该不算吧
- 注意为空,和只有一个值的情况
bug
没有想到重复的情况:
- 输入[1,1,1,1,1,1],答案输出是1
- 输入[0,1,1,2],答案是3,表明只要连续的值都存在,有没有重复都没有关系,我的开始的代码很严重的强调了位置
解决方式
- 用set去重 或者再while的判断里面添加一点东西
代码
方法一
python
class Solution:
def longestConsecutive(self, nums) -> int:
nums=set(nums)
length = len(nums)
if length == 0:
return 0
nums=sorted(nums)
print(nums)
maxlength = 1
i = 0
while i < length-1:
templength = 1
while i<length-1 and nums[i] + 1 == nums[i + 1]:
i += 1
templength += 1
maxlength = max(maxlength, templength)
i += 1
return maxlength
方法二
代码
python
class Solution:
def longestConsecutive(self, nums) -> int:
# nums=set(nums)
length = len(nums)
if length == 0:
return 0
nums=sorted(nums)
print(nums)
maxlength = 1
i = 0
while i < length-1:
templength = 1
while i<length-1 and (nums[i] + 1 == nums[i + 1] or nums[i]==nums[i+1]) :
if nums[i]+1==nums[i+1]:
templength += 1
i += 1
maxlength = max(maxlength, templength)
i += 1
return maxlength
Java
class Solution {
public int longestConsecutive(int[] nums) {
int length=nums.length;
if (length==0){
return 0;
}
Arrays.sort(nums);
int maxlength=1,i=0;
while (i<length-1){
int templength=1;
while (i<length-1 && ((nums[i]==nums[i+1]) || (nums[i]+1==nums[i+1]))){
if (nums[i]+1==nums[i+1]){
++templength;
}
++i;
}
maxlength=Math.max(maxlength,templength);
++i;
}
return maxlength;
}
}