题目要求
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
分析:
本题要求时间复杂度为o(n),可以使用哈希表的方法解决。
- 首先遍历数组nums,将nums中的元素全部加入到哈希表中。同时当数组为 [100,4,200,1,3,2] 时,以1或2或3或4开始遍历时遍历到的结果应该是一样的,同时为了防止重复遍历,需要记录当前元素被遍历过。
- 所以使用HashMap<Integer,Boolean> 结构,键表示数组中的元素,值表示遍历到的元素被访问过时需要设置为true。
- 定义一个局部变量设置为max,表示以map中的某一元素开始时的最长序列。此时以map中的某一个元素开始遍历假设为 i ,则查看 i -1,i - 2,··· 和 i + 1,i + 2 , ··· 是否在map中,若在时需要将max++,同时维护一个全局的最大值,表示该数组中的数字连续的最长序列,在每一趟遍历完成时更新。
代码:
class Solution {
public int longestConsecutive(int[] nums) {
int N = nums.length;
if (N == 0) {
return 0;
}
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < N; i++) {
if (map.get(nums[i]) == null) {
map.put(nums[i],1);
}
}
int maxConsecutive = Integer.MIN_VALUE;
for (Integer cur : map.keySet()) {
int max = 1;
if (map.get(cur) == 0) {
continue;
} else {
map.put(cur,0);
int minusCur = cur - 1;
int addCur = cur + 1;
while (map.get(minusCur) != null) {
max++;
map.put(minusCur,0);
minusCur--;
}
while (map.get(addCur) != null) {
max++;
map.put(addCur,0);
addCur += 1;
}
maxConsecutive = Math.max(maxConsecutive,max);
}
}
return maxConsecutive;
}
}