題目:
給定一個未排序的整數(shù)數(shù)組 nums 蛾绎,找出數(shù)字連續(xù)的最長序列(不要求序列元素在原數(shù)組中連續(xù))的長度慨蛙。
進階:你可以設(shè)計并實現(xiàn)時間復(fù)雜度為 O(n) 的解決方案嗎?
示例 1:
輸入:nums = [100,4,200,1,3,2]
輸出:4
解釋:最長數(shù)字連續(xù)序列是 [1, 2, 3, 4]。它的長度為 4锚烦。
示例 2:
輸入:nums = [0,3,7,2,5,8,4,6,0,1]
輸出:9
提示:
0 <= nums.length <= 104
-109 <= nums[i] <= 109
鏈接:https://leetcode-cn.com/problems/longest-consecutive-sequence
Python代碼:
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
size = len(nums)
for i in range(size-1):
for j in range(size-i-1):
if nums[j]>nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
ret = 1
ans = 1
for i in range(size-1):
if (nums[i+1] == nums[i]+1):
ans += 1
elif (nums[i+1] == nums[i]):
continue
else:
ans = 1
ret = max(ret, ans)
return ret
Python代碼2:
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
ret = 0
dt = {}
for num in nums:
if num in dt:
continue
left = dt.get(num-1, 0)
right = dt.get(num+1, 0)
curr = 1+left+right
dt[num] = curr
dt[num-left] = curr
dt[num+right] = curr
ret = max(ret, curr)
return ret
Java代碼:
class Solution {
public int longestConsecutive(int[] nums) {
Map<Integer, Integer> dt = new HashMap<>();
if(nums.length==0){
return 0;
}
int ret = 0;
for(int num:nums){
if(dt.containsKey(num)){
continue;
}
int left = dt.getOrDefault(num-1, 0);
int right = dt.getOrDefault(num+1, 0);
int curr = 1 + left + right;
dt.put(num, curr);
dt.put(num-left, curr);
dt.put(num+right, curr);
ret = Math.max(ret, curr);
}
return ret;
}
}