일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- Substring with Concatenation of All Words
- Class
- iterator
- 밴픽
- 715. Range Module
- shiba
- Python Code
- 30. Substring with Concatenation of All Words
- 프로그래머스
- 109. Convert Sorted List to Binary Search Tree
- attribute
- Regular Expression
- Python Implementation
- 파이썬
- data science
- 시바견
- concurrency
- Generator
- kaggle
- 315. Count of Smaller Numbers After Self
- 컴퓨터의 구조
- Python
- 운영체제
- 43. Multiply Strings
- t1
- LeetCode
- DWG
- Decorator
- Protocol
- Convert Sorted List to Binary Search Tree
Archives
- Today
- Total
Scribbling
LeetCode: 454. 4Sum II 본문
First thing to try is iterating nums1, nums2, nums3 and looking for the corresponding element in nums4. This will result in O(N**3) time complexity, which raises TLE.
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
from collections import Counter
c = Counter(nums4)
ret = 0
for n1 in nums1:
for n2 in nums2:
for n3 in nums3:
ret += c[-(n1 + n2 + n3)]
return ret
How can we reduce the time complexity?
Making use of the fact that all arrays have same length of N would be great.
The idea is to pair (nums1, nums2) and (nums3, nums4) each, and to store all sum results generated by both pairs in the seperate counters. --> O(N**2)
Then, iterate through all sum results in one counter. --> O(N**2)
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
from collections import Counter
c1 = Counter()
c2 = Counter()
for n1 in nums1:
for n2 in nums2:
c1[n1+n2] += 1
for n3 in nums3:
for n4 in nums4:
c2[n3+n4] += 1
ret = 0
for k, v in c1.items():
ret += c2[-k] * v
return ret
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 30. Substring with Concatenation of All Words (0) | 2022.01.17 |
---|---|
LeetCode: 27. Remove Element (0) | 2022.01.17 |
LeetCode: 395. Longest Substring with At Least K Repeating Characters (0) | 2022.01.16 |
LeetCode: 384. Shuffle an Array (0) | 2022.01.15 |
LeetCode: 378. Kth Smallest Element in a Sorted Matrix (0) | 2022.01.14 |