给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
提示:
0 <= nums.length <= 105-109 <= nums[i] <= 109
解题思路: 两种思路解决这道题
思路一:
不考虑时间复杂度O(n)的前提下,我们可以先对数组进行sort排序,然后线性扫描数组,如果连续,count就加一,如果一样,count 不动,如果不一样,count 置为 1并且比较count与max的值,如果count > max,则更新max。
这样做的时间复杂度应该是排序的时间复杂度,也就是O(nlogn)。虽然不符合进阶要求,但是也能过。
思路二:
可以采用空间换时间的办法,用hashMap存储数组里面的所有数,key为数字本身,value为1。然后遍历数组,用数组里的每一个数,向左向右两边探索 ,如果比它小1或者大1的数字存在,则count++,然后把比他小1或者大1的这个数字在map中的value置0,数组中的元素遍历过程中遇到value为0的便可以直接跳过(因为这个数如果为0,则它向左右俩边延申的结果肯定之前某个数延申的过程中已经计算过了)。
因为存取的时间复杂度是O(1),所以这种算法的时间复杂度是O(n)。
思路一和思路二代码实现以及提交结果如下:
//思路1
class Solution {
public static int longestConsecutive(int[] nums) {
if(nums.length == 0){
return 0;
}
Arrays.sort(nums);
int len = nums.length;
int count = 1;
int max = 0;
for(int i = 0 ; i < len-1 ; i++){
if(nums[i]+1 == nums[i+1]){
count++;
}else if(nums[i]+1 > nums[i+1]){
continue;
}else{
if(count > max){
max = count;
}
count = 1;
}
}
if(count != 0 && count > max){
max = count;
}
return max;
}
}
//思路二
class Solution {
public static int longestConsecutive(int[] nums) {
if(nums.length == 0){
return 0;
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i],1);
}
int max = 1;
for (int i = 0; i < nums.length; i++) {
if(map.get(nums[i]) == 0){
continue;
}
int count = 1;
int temp = nums[i];
while(map.get(--temp) != null){
map.put(temp,0);
count++;
}
temp = nums[i];
while(map.get(++temp) != null){
map.put(temp,0);
count++;
}
if(count > max){
max = count;
}
}
return max;
}
}