# A. Count Equal and Divisible Pairs in an Array (opens new window)
Brute Force, check every pair of indexes (i, j)
.
DETAILS
def countPairs(self, A: List[int], k: int) -> int:
ans, n = 0, len(A)
for i in range(n - 1):
for j in range(i + 1, n):
ans += int(A[i] == A[j] and not (i * j) % k):
return ans
# B. Find Three Consecutive Integers That Sum to a Given Number (opens new window)
Check if num
is divisible by 3
.
DETAILS
def sumOfThree(self, num: int) -> List[int]:
return [] if num % 3 else [num // 3 - 1, num //3, num // 3 + 1]
# C. Maximum Split of Positive Even Integers (opens new window)
Greedy.
Start from the smallest even number 2
.
DETAILS
def maximumEvenSplit(self, A: int) -> List[int]:
if A % 2: return []
ans, cur, A = [2], 4, A - 2
while A >= cur:
ans.append(cur)
A -= cur
cur += 2
ans[-1] += A
return ans
# D. Count Good Triplets in an Array (opens new window)
Please refer to This LC Discussion (opens new window) for my solutions in English.
思路是:只看triplet里中间的那个数:
对于A
中每一个数字a
,我们需要找到:以a
为中心的triplet有多少?这样,把所有数的triplets加一起即可。
所以,对于a
我们需要找到:
- 有多少个数在
A, B
里位置均在a
的左边,比如有x
个数。 - 有多少个数在
A, B
里的位置均在a
的右边,比如有y
个数。 - 以
a
为中心的triple共有x*y
种。
遍历过程需要logN时间内的插入/二分查找,数据结构用BST或者BIT都可以。我用的是Python有现成的BST容器SortedList。
DETAILS
from sortedcontainers import SortedList
class Solution:
def goodTriplets(self, A: List[int], B: List[int]) -> int:
# Index of a (from A) in B.
pos = [0] * len(A)
for idx, b in enumerate(B):
pos[b] = idx
# Build pre_a[i]: number of elements on a[i]'s left in both A and B.
# pos_in_b: sorted indexes (in B) of all the visited elements in A.
pos_in_b, pre_a = SortedList([pos[A[0]]]), [0]
for a in A[1:]:
pos_in_b.add(pos[a])
pre_a.append(pos_in_b.bisect_left(pos[a]))
# Build suf_a[i]: number of elements on a[i]'s right in both A and B.
pos_in_b, suf_a = SortedList([pos[A[-1]]]), [0]
for a in reversed(A[:len(A)-1]):
idx = pos_in_b.bisect(pos[a])
suf_a.append(len(pos_in_b) - idx)
pos_in_b.add(pos[a])
suf_a.reverse()
# Sum up all unique triplets centered on A[i].
ans = 0
for x, y in zip(pre_a, suf_a):
ans += x * y
return ans