File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ # 시간 복잡도: O(n)
2+ # - while문이 이중으로 쓰였지만, nums에 있는 각 요소를 한 번 씩만 탐색하는 풀이임(이미 확인한 요소는 pop/remove로 없애기 때문)
3+ # 공간 복잡도: O(n)
4+ # - set 하나만 사용했기 때문에 길이인 n개만큼만 공간 차지
5+
6+ class Solution :
7+ def longestConsecutive (self , nums : List [int ]) -> int :
8+ nums = set (nums )
9+ max_length = 1 if nums else 0 # 빈 배열이 들어올 땐 가장 긴 경우는 0밖에 없음
10+
11+ while nums :
12+ num = nums .pop () # 기준이 될 num을 하나 가져옴
13+ length = 1
14+ left , right = 1 , 1
15+ while num - left in nums :
16+ # 기준 num에서 왼쪽으로 확장 가능한 정도를 계산하여 length를 늘림
17+ nums .remove (num - left )
18+ length += 1
19+ left += 1
20+ while num + right in nums :
21+ # 기준 num에서 오른쪽으로 확장 가능한 정도를 계산하여 length를 늘림
22+ nums .remove (num + right )
23+ length += 1
24+ right += 1
25+
26+ max_length = max (max_length , length ) # 기존에 계산해둔 max_length와 비교하여 업데이트
27+
28+ return max_length
29+
30+
31+
32+ # # ** Other trial
33+ # # 시간 복잡도: O(n log n)
34+ # # - sorting을 했기 때문. 문제 통과는 되지만 문제 내 힌트인 O(n)의 시간복잡도를 충족하진 않음
35+ # # 공간 복잡도: O(n)
36+ # # - nums를 set -> list으로 변환하면서 n개의 개수만큼 저장공간 사용
37+ # class Solution:
38+ # def longestConsecutive(self, nums: List[int]) -> int:
39+ # nums = list(set(nums))
40+ # if not nums:
41+ # return 0
42+
43+ # if len(nums) == 1:
44+ # return 1
45+
46+ # nums.sort()
47+ # max_length = 1
48+
49+ # start_i = 0
50+ # length = 1
51+ # while start_i < len(nums) - 1 and start_i + length < len(nums):
52+ # length = 1
53+ # for i in range(start_i, len(nums) - 1):
54+ # if nums[i + 1] == nums[i] + 1:
55+ # length += 1
56+ # else:
57+ # start_i = i + 1
58+ # break
59+ # max_length = max(max_length, length)
60+
61+ # return max_length
You can’t perform that action at this time.
0 commit comments