leetcode - 128 最長連續序列
阿新 • • 發佈:2022-05-24
給定一個未排序的整數陣列 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; } }