-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfour_sum_II.py
More file actions
42 lines (30 loc) ยท 1.68 KB
/
four_sum_II.py
File metadata and controls
42 lines (30 loc) ยท 1.68 KB
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
32
33
34
35
36
37
38
39
40
41
42
# 454. 4Sum II
# https://leetcode.com/problems/4sum-ii/
from typing import List
from collections import defaultdict
class Solution:
# ์ฃผ์ด์ง ๋ฐฐ์ด 4๊ฐ์ ์์๋ค์ ์ด์ฉํด์ ํฉ์ฐํ ๊ฐ์ด 0์ด ๋๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๋ฆฌํดํ๋ ๋ฌธ์ ๋ค.
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
t1 = defaultdict(int)
t2 = defaultdict(int)
# ๋ฐฐ์ด ๋๊ฐ์ฉ ์์๋ก ๋ฌถ์ด์ ํฉ์ฐํ ๊ฐ์ ํค๋ก ์ฐ๊ณ , ๊ฐ ํค์ ๋ํ ์นด์ดํ
์ ํด ์ค๋ค.
for i in A:
for j in B:
t1[i + j] += 1
for k in C:
for l in D:
t2[k + l] += 1
result = 0
# ์นด์ดํ
ํ ๋์
๋๋ฆฌ์์ ํค๊ฐ ์๋ก ๋ฐ๋๋๋ ๊ฐ์ด๋ฉด ๊ฐ์ ๊ณฑํด์ค๋ค.
# ์ด ์ด์ ๋ ๋ฌธ์ ์์ ์ํ๋ ๊ฒ์ด ๊ฐ ๋ฐฐ์ด์ ์์์ ๊ฐ๋ค์ ํฉ์ด 0์ด ๋๋ ๊ฒ์ธ๋ฐ, ์ด๋ฏธ ํค์๋ ๋ฐฐ์ด ์์์ ํฉ์ฐ์ด ๋ค์ด๊ฐ ์๋ค.
# ๋ ๋์
๋๋ฆฌ๊ฐ ์๋ก ๋ฐ๋๋๋ ์์๊ฐ ๋ค์ด์๋ค๋ ์๋ฏธ๋ ํฉํ๋ฉด 0์ด ๋๋ค๋ ๊ฒ์ด๋ค.
# ์ฆ (์์๋ก ๋ฌถ์) A, B ์ ์์์ ํฉ๋ค๊ณผ C, D ์ ์์์ ํฉ๋ค ์ค์์ ์๋ก ๋ฐ๋๋๋ ๊ฒ๋ค์ ์ฐพ๋๋ค๋ ์๋ฏธ๋ค.
# ๊ณฑํ๊ธฐ๋ฅผ ํด ์ฃผ๋ ์ด์ ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๊ตฌํด์ผ ํ๋ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ ๊ณฑํ๊ธฐ๋ฅผ ํด ์คฌ๋ค.
for k, v in t1.items():
if -k in t2 and v >= 1 and t2[-k] >= 1:
result += v * t2[-k]
return result
if __name__ == '__main__':
sol = Solution()
assert sol.fourSumCount([1, 2], [-2, -1], [-1, 2], [0, 2]) == 2
assert sol.fourSumCount([1, 1], [-1, -1], [-1, -1], [1, 1]) == 16