Skip to content

Commit c815de3

Browse files
committed
Pairs of Songs With Total Durations Divisible by 60 풀이
문제: https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/description/
1 parent 0f41b0d commit c815de3

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

20230107/pairs-of-songs/README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Pairs of Songs With Total Durations Divisible by 60
2+
## 문제 분석
3+
### 구하는 것
4+
- pairs of songs
5+
### 주어진 것
6+
- list of songs
7+
- songs[i] => duration of the song
8+
### 조건
9+
- pair 로 묶인 songs 의 길이 합이 60으로 나누어떨어져야함.
10+
## 풀이 계획
11+
### 예시 분석
12+
[30, 20, 150, 100, 40]
13+
14+
=>
15+
[30, 150]
16+
[20, 100]
17+
[20, 40]
18+
19+
=> 이렇게 탐색하는 경우 n^2의 시간복잡도를 가지게 됨.
20+
21+
60으로 먼저 나눠보면 어떨까?
22+
그 후에 나머지 배열을 순회하며 해시에 카운트를 저장하자.
23+
처음에는 0, 짝이 되는 숫자가 등장하면 1 씩 증가.
24+
마지막에는 총 합을 구하면 된다.
25+
26+
[30, 20, 30, 40, 40]
27+
{
28+
30: 2,
29+
20: 1,
30+
40: 2,
31+
}
32+
33+
[60, 60, 60] => [0, 0, 0]
34+
{
35+
0: 3
36+
}
37+
38+
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
def numPairsDivisibleBy60(songs):
2+
return count_pairs(counts=count_remainder(songs))
3+
4+
5+
def count_remainder(songs):
6+
remainders = [song % 60 for song in songs]
7+
counts = dict()
8+
for remainder in remainders:
9+
counts.setdefault(remainder, 0)
10+
counts[remainder] += 1
11+
return counts
12+
13+
14+
def test_count_remainder():
15+
assert count_remainder([0, 10, 20, 10]) == {0: 1, 10: 2, 20: 1}
16+
17+
18+
def count_pairs(counts):
19+
remainders = [0, 10, 20, 30]
20+
21+
count = 0
22+
for remainder in remainders:
23+
count_a = counts.get(remainder, 0)
24+
count_b = counts.get(60 - remainder, 0)
25+
26+
match remainder:
27+
case 0 | 30:
28+
count += count_a * (count_a - 1) // 2
29+
case _:
30+
count += count_a * count_b
31+
32+
return count
33+
34+
35+
def test_count_pairs():
36+
assert count_pairs({0: 2, 10: 2, 20: 3, 40: 5, 50: 3}) == 22
37+
assert count_pairs({0: 3}) == 3
38+
39+
40+
def test_numPairsDivisibleBy60():
41+
assert numPairsDivisibleBy60([30, 20, 150, 100, 40]) == 3
42+
assert numPairsDivisibleBy60([60, 60, 60]) == 3

0 commit comments

Comments
 (0)