일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 알고리즘
- gcp
- stratascratch
- 파이썬기초100제
- SQL
- Microsoft
- slidingwindow
- 구글퀵랩
- nlp
- sql코테
- 니트코드
- Python3
- Python
- two-pointer
- GenAI
- codeup
- medium
- 자연어처리
- 슬라이딩윈도우
- dfs
- 파이썬알고리즘
- heap
- 생성형AI
- LeetCode
- 파이썬
- 투포인터
- 코드업
- 리트코드
- 릿코드
- GenerativeAI
Archives
- Today
- Total
Tech for good
[Leetcode/Sort, Heap] 2974. Minimum Number Game 본문


1. Sort
✅ Approach:
- Sort the array first to make it easy to remove the minimums.
- In every round:
- Alice removes the smallest number (i.e., pop from the front).
- Bob removes the next smallest number.
- Bob appends his number first, then Alice.
class Solution:
def numberGame(self, nums: List[int]) -> List[int]:
nums.sort()
arr = []
while nums:
alice = nums.pop(0) # Alice removes min
bob = nums.pop(0) # Bob removes next min
arr.append(bob) # Bob appends first
arr.append(alice) # Then Alice
return arr
- pop(0) removes and returns the first element (element at index 0).
🧠 Time Complexity
## 1. sort
nums.sort() # O(n log n)
while nums: # loop runs n/2 times (since 2 pops per iteration)
alice = nums.pop(0) # O(n) each time (because pop(0) shifts all elements)
bob = nums.pop(0) # O(n)
Sorting nums | O(n log n) |
Each pop(0) inside loop | O(n) |
Total pops (n times) | O(n²) |
2. heap
class Solution:
def numberGame(self, nums: List[int]) -> List[int]:
heapq.heapify(nums) # Turn nums into a min-heap
arr = []
while nums:
alice = heapq.heappop(nums) # Alice removes min
bob = heapq.heappop(nums) # Bob removes next min
arr.append(bob) # Bob appends first
arr.append(alice) # Then Alice
return arr
🧠 Time Complexity
- heapify(nums) → O(n)
- Each heappop() → O(log n)
- Two heappop() per loop × (n/2) rounds → O(n log n)
'IT > Computer Science' 카테고리의 다른 글
[Leetcode/Heap] 451. Sort Characters By Frequency (0) | 2025.04.07 |
---|---|
[Leetcode/Heap] 3264. Final Array State After K Multiplication Operations I (0) | 2025.04.07 |
[Leetcode/Heap] 2558. Take Gifts From the Richest Pile (0) | 2025.04.04 |
[Leetcode/Heap] 2099. Find Subsequence of Length K With the Largest Sum (0) | 2025.04.04 |
[Leetcode/Heap] 1464. Maximum Product of Two Elements in an Array (0) | 2025.03.31 |