题目链接:
思路分析:(nlogn)这种方法的复杂度较高(但是能过......)
首先对数组进行去重和排序操作,我直接暴力使用HashSet和ArrayList的对应方法解决,解决这个需求之后,他题目要求的是连续的序列,我使用的是简单动态规划,两个变量new_num,max_num,第一个是当前位置的最长长度,另一个是去掉这一个位置前面所有位置的最长长度.,这个else是当前不连续那么就是0(归零操作),在题目中还需要一个非空判断,同时一个数时的长度是1,最后也要加上1
class Solution {
public int longestConsecutive(int[] nums) {
HashSet hashSet = new HashSet<>();
for (int i=0; i<nums.length;i++){
hashSet.add(nums[i]);
}
List<Integer> list = new ArrayList<>(hashSet);
Collections.sort(list);
int new_num=0;int max_num =0;
if (list.isEmpty()){
return 0;
}else{
for(int i=1;i<list.size();i++){
if(list.get(i)-list.get(i-1)==1){
new_num+=1;
max_num=Math.max(max_num,new_num);
}else{
new_num=0;
}
}
}
return max_num+1;
}
}
改进方案:复杂度(O(N))
不对数据进行排序操作,使用哈希实现跳跃判断的方法解决,原理大致与上一种类似,首先遍历数组,判断其前面没有比这个数小1的(方便作为起始点),如果这个值前一个数也在集合中那就向后继续遍历对该值暂时不做处理,如果是起始点,那就将current变量定位该值,同时将长度定位1,循环判断,循环结束返回的len为此起始点为起点的最长序列。
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int i:nums){
set.add(i);
}
int max_len=0;
for(int num :set){
if(!set.contains(num-1)){
int current=num;
int len = 1;
while(set.contains(current+1)){
current+=1;
len+=1;
}
max_len = Math.max(len,max_len);
}
}
return max_len;
}
}