给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n)
的算法解决此问题。
最开始我考虑这个题的时候考虑的很简单,就先排序,然后暴力判断
class Solution {
public int longestConsecutive(int[] nums) {
int count;
if(nums!=null){
count=1;}else count=0;
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]-1){
count++;
}
if(nums[i+1]>nums[i]+1){
break;
}
}
System.out.println(count);
return count;
}
}
测试的时候,我发现我并没有考虑存在多个序列的问题,而是认为从最开始的一定是最长的
于是我加了一个比较不同长度的部分代码
class Solution {
public int longestConsecutive(int[] nums) {
int count;int longestcount=0;
if(nums!=null){
count=1;}else count=0;
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]-1){
count++;
}
if(nums[i+1]>nums[i]+1||i==nums.length-2){
longestcount=Math.max(longestcount,count);
count=1;
}
}
if(nums.length==1){
longestcount=count;
}
return longestcount;
}
}
提交通过