[Leetcode]128. Longest Consecutive Sequence

閱讀時間約 2 分鐘

題目 : 128. Longest Consecutive Sequence Medium

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


1.

numSet : 用set()函數將nums做成集合,去除重複的數字

longest : 紀錄目前最大長度

length : 記錄由num開始算連續數字的長度


line 8 : 先看num是不是連續整數中的最小數,如果是就開始往後找num+1、num+2....

直到找到連續整數的最大長度

line 12 : 跳出迴圈後查看紀錄的length和longest那個最大,用max()回傳最大長度

class Solution:
def longestConsecutive(self, nums: List[int]) -> int:

numSet = set(nums)
longest = 0

for num in nums :
if num-1 not in numSet:
length = 0
while (num+length) in numSet:
length += 1
longest = max(length,longest)

return longest



7會員
47內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
Youna's Devlog 的其他內容
[Leetcode] 1. Two Sum
閱讀時間約 1 分鐘
[Leetcode] 49. Group Anagrams
閱讀時間約 3 分鐘
[Leetcode] 125. Valid Palindrome
閱讀時間約 3 分鐘
[Leetcode] 20. Valid Parentheses
閱讀時間約 3 分鐘
你可能也想看
【LeetCode】19.Remove Nth Node From End of ListInput: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Thumbnail
avatar
2021-10-09
【LeetCode】876. Middle of the Linked ListInput: head = [1,2,3,4,5] Output: [3,4,5] 單看列表只是要找中間值,不過給定的資料結構不是陣列,而是鏈結串列。
Thumbnail
avatar
2021-10-09
【LeetCode】189. Rotate Array之前跳過的題目,回來補完成。 Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]
Thumbnail
avatar
2021-10-08
【LeetCode】557. Reverse Words in a String III今日題目: 把一行字內每個單字都反轉字元。 Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Thumbnail
avatar
2021-10-08
【LeetCode】344. Reverse String今日題目:字串反轉 Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Thumbnail
avatar
2021-10-08
【LeetCode】167. Two Sum II 題目如下: Input: numbers = [2,7,11,15], target = 9 Output: [1,2]
Thumbnail
avatar
2021-10-07
【LeetCode】283. Move Zeroes題目要求如下: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] 把0都搬到後面去,非0的數字移到前面,且不更改原本數字的大小順序。
Thumbnail
avatar
2021-10-07
【LeetCode】977. Squares of a Sorted Array比今天的題目示例如下: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] 簡單來說,要的輸出結果是把陣列內每個數字取平方後,對陣列做排序。
Thumbnail
avatar
2021-10-06
【LeetCode】704. Binary SearchLeetcode上正好有14天的讀書計畫,今天三題都是二分搜索,順手三題都寫一寫,想法上很固定。
Thumbnail
avatar
2021-10-05
【LeetCode】20. Valid Parentheses 前幾天看別人直播刷題,心血來潮打開很久沒動的leetcode試試,挑了一題當初面試沒寫出來的題目。嗯...我那時才剛碰資料結構,知道要用stack寫卻沒實作過任何東西,現在有工作經驗後再來寫,看看會不會有不一樣的想法。
Thumbnail
avatar
2021-10-04