Skip to content

Commit a560bdd

Browse files
committed
Solve: Longest Consecutive Sequence
1 parent dc6b6ad commit a560bdd

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
๏ปฟ# --- ํ•ด์„ ---
2+
#๋งค๊ฐœ๋ณ€์ˆ˜ nums ๋ฅผ set์œผ๋กœ ๋ฐ”๊ฟ”์„œ ์ค‘๋ณต์ œ๊ฑฐ
3+
#set์„ list๋กœ ์ „ํ™˜ํ•˜์—ฌ sortํ•˜์—ฌ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ณ€ํ™˜
4+
#for loop ๋กœ nums[1]๋ถ€ํ„ฐ nums[len(nums)-1] ์— ์ ‘๊ทผ
5+
#nums[i]-nums[i-1] =1 ์ด๋ฉด ๋ณ€์ˆ˜ current๋ฅผ ์ฆ๊ฐ€, longest๋Š” current์˜ ์ตœ๋Œ“๊ฐ’์„ ์—…๋ฐ์ดํŠธ
6+
#๋งŒ์•ฝ ํ•ด๋‹น ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด current๋ฅผ 1๋กœ ์ดˆ๊ธฐํ™”, ์ดํ›„ longest ๊ฐ’ return
7+
8+
# --- Big O
9+
#N: ๋งค๊ฐœ๋ณ€์ˆ˜ nums์˜ ๊ธธ์ด๊ฐ€ N์ด๋‹ค.
10+
11+
# Time Complexity: O(N)
12+
#- set(nums)๋Š” nums์˜๋ชจ๋“  ์š”์†Œ๋ฅผ ํ•˜๋‚˜์”ฉ ์ˆœํšŒํ•˜๋ฉฐ ์ค‘๋ณต ์ œ๊ฑฐ : O(N)
13+
#- list(set(nums)) ๋Š” data type์„ ๋ณ€ํ™˜ํ•˜๋ฉด์„œ nums์˜ ๊ฐฏ์ˆ˜๋งŒํผ data๋ฅผ ์ถ”๊ฐ€ ์ƒ์„ฑ: O(N)
14+
#- for loop ๋Š” nums[1] ๋ถ€ํ„ฐ nums[len(nums)-1]๋งŒํผ ์ˆœํšŒ: O(N)
15+
16+
# Space Complexity: O(N)
17+
#-nums = list(set(nums)): list(),set(),dict() ์ด๋Ÿฐ data type์„ ๋ณ€ํ™˜ํ• ๋•Œ๋งˆ๋‹ค N๋งŒํผ ๊ณต๊ฐ„ ์ถ”๊ฐ€ํ• ๋‹น: O(N)
18+
#-longest,current ๋ณ€์ˆ˜๋Š” ์ƒ์ˆ˜ : O(1)
19+
20+
class Solution(object):
21+
def longestConsecutive(self, nums):
22+
"""
23+
:type nums: List[int]
24+
:rtype: int
25+
"""
26+
#If the nums doesn't have elements, return 0
27+
if len(nums) ==0:
28+
return 0
29+
#์ค‘๋ณต์ œ๊ฑฐ set
30+
nums = list(set(nums))
31+
#sort
32+
nums.sort()
33+
print(nums)
34+
35+
#Variables
36+
longest = 1
37+
current = 1
38+
39+
#Approah all element of nums for checking the sequnece number or not
40+
for i in range(1,len(nums)):
41+
if nums[i] == nums[i-1] + 1:
42+
current +=1 #current๋Š” nums[i]์™€ nums[i-1]์˜ ์ฐจ์ด๊ฐ€ 1์ด๋ฉด +1ํ•ด์คŒ.
43+
longest = max(longest, current) #return๊ฐ’์„ ์œ„ํ•ด currrent๊ฐ€ ๊ฐ€์žฅ ํฌ๋„๋ก ์—…๋ฐ์ดํŠธ
44+
else:#์—ฐ์† ๋˜์ง€ ์•Š์„ ์‹œ current 1๋กœ ์ดˆ๊ธฐํ™”
45+
current =1
46+
print(longest)
47+
return longest
48+
49+

0 commit comments

Comments
ย (0)