일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 43. Multiply Strings
- attribute
- Regular Expression
- 715. Range Module
- shiba
- Decorator
- Protocol
- 시바견
- concurrency
- Python
- t1
- Python Code
- Substring with Concatenation of All Words
- 파이썬
- 밴픽
- 109. Convert Sorted List to Binary Search Tree
- Python Implementation
- Convert Sorted List to Binary Search Tree
- DWG
- kaggle
- iterator
- Generator
- 30. Substring with Concatenation of All Words
- data science
- 315. Count of Smaller Numbers After Self
- 운영체제
- 프로그래머스
- Class
- LeetCode
- 컴퓨터의 구조
Archives
- Today
- Total
Scribbling
LeetCode: 1010. Pairs of Songs With Total Durations Divisible by 60 본문
Computer Science/Coding Test
LeetCode: 1010. Pairs of Songs With Total Durations Divisible by 60
focalpoint 2022. 1. 3. 22:01My own code is always messy.
The idea is to sort the list and calculate sums.
Time complexity will be O(NlogN) due to sorting.
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
time = [t % 60 for t in time]
time.sort()
ret = 0
l, r = 0, len(time) - 1
while l < r:
if time[l] + time[r] == 60:
if time[l] == 30:
cnt = 0
while l <= len(time) - 1 and time[l] == 30:
cnt += 1
l += 1
ret += cnt * (cnt - 1) // 2
break
else:
cnt1, cnt2 = 0, 0
l_val, r_val = time[l], time[r]
while time[l] == l_val:
cnt1 += 1
l += 1
while time[r] == r_val:
cnt2 += 1
r -= 1
ret += cnt1 * cnt2
elif time[l] + time[r] < 60:
l += 1
else:
r -= 1
l, cnt = 0, 0
while l <= len(time) - 1 and time[l] == 0:
cnt += 1
l += 1
ret += cnt * (cnt - 1) // 2
return ret
An effetive way to solve this problem is using the 'Two Sum' approach.
This way, time complexity reduces to O(N) while memory complexity increases to O(N).
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
time = [t % 60 for t in time]
from collections import Counter
c = Counter()
ans = 0
for t in time:
ans += c[60-t] if t > 0 else c[0]
c[t] += 1
return ans
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 442. Find All Duplicates in an Array (0) | 2022.01.05 |
---|---|
LeetCode: 268. Missing Number (0) | 2022.01.04 |
LeetCode: 297. Serialize and Deserialize Binary Tree (0) | 2022.01.02 |
LeetCode: 328. Odd Even Linked List (0) | 2021.12.31 |
LeetCode: 289. Game of Life (0) | 2021.12.29 |