大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Constraints:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
給一個陣列nums
,找出陣列中最長的連續數字序列,並回傳該長度。
首先將陣列排序,方便找出其中的連續數字序列~
每次都會跟下一個數字比較
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
# []
if len(nums) <= 1:
return len(nums)
# sorted
nums = sorted(nums)
#print(nums)
longest_length = 1
tmp_length = 1
for index in range(len(nums)-1):
#print("longest: ", longest_length, "tmp: ", tmp_length)
if (nums[index+1]-nums[index]) == 1:
tmp_length += 1
# the same number should skip!
elif (nums[index+1]-nums[index]) == 0:
continue
else:
if longest_length <= tmp_length:
longest_length = tmp_length
tmp_length = 1
if longest_length <= tmp_length:
longest_length = tmp_length
#print("longest_length: ", longest_length)
return longest_length
今天就到這邊啦~
大家明天見