一、题目粗心
https://leetcode.cn/problems/longest-consecutive-sequence
给定一个未排序的整数数组 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
二、解题思路
能够把所有数字放到一个哈希表,而后一直地从哈希表中任意取一个值,并删除掉其之前之后的所有间断数字,而后更新目前的最长间断序列长度。反复这一过程,就能够找到所有的间断数字序列,顺便找出最长的。
三、解题办法
3.1 Java实现-超时版
public class Solution1 { public int longestConsecutive(int[] nums) { Set<Integer> intSet = new HashSet<>(); for (int num : nums) { intSet.add(num); } int ans = 0; while (!intSet.isEmpty()) { int cur = intSet.stream().findFirst().get(); intSet.remove(cur); int pre = cur - 1; int next = cur + 1; while(intSet.contains(pre)) { intSet.remove(pre--); } while(intSet.contains(next)) { intSet.remove(next++); } ans = Math.max(ans, next - pre - 1); } return ans; }}
3.2 Java实现-通过版
public class Solution { public int longestConsecutive(int[] nums) { Set<Integer> intSet = new HashSet<>(); for (int num : nums) { intSet.add(num); } int ans = 0; for (int num : nums) { if (intSet.remove(num)) { int pre = num - 1; int next = num + 1; while (intSet.remove(pre)) { pre--; } while (intSet.remove(next)) { next++; } ans = Math.max(ans, next - pre - 1); } } return ans; }}
四、总结小记
- 2022/8/16 Map的好些办法在解决大数据量时要慎用呀