leetcode - 128 最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-consecutive-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
自己的解法:先排序后统计!时间复杂度竟然超过97.07%
class Solution { public int longestConsecutive(int[] nums) { if (nums.length == 0 || nums.length == 1) { return nums.length; } Arrays.sort(nums); int max = 1; int const_max = 1; for (int i = 0; i < nums.length - 1; i++) { max = 1; while (i < nums.length - 1 && nums[i + 1] - nums[i] <= 1) { if (nums[i + 1] - nums[i] == 1) { max++; } i++; } if (max > const_max) { const_max = max; } } return const_max; } }
官方解答:但时间复杂度很高43.88%,好像不是o(n)
class Solution { public int longestConsecutive(int[] nums) { if (nums.length == 0 || nums.length == 1) { return nums.length; } Set<Integer> set = new HashSet<>(); for (int n : nums) { set.add(n); } int longLength = 0; for (int num : set) { if (!set.contains(num - 1)) { int currentNum = num; int currentLength = 1; while (set.contains(currentNum + 1)) { currentNum += 1; currentLength += 1; } longLength = Math.max(longLength, currentLength); } } return longLength; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步