15. 三数之和
class Solution:
def twoSum(self, nums, start, target):
l = start
r = len(nums) - 1
ans = []
while l < r:
lo = nums[l]
hi = nums[r]
if lo + hi == target:
ans.append([lo, hi])
# 判断条件写成了 !=
while l < r and nums[r] == hi: r -= 1 # 写成了 += 1
while l < r and nums[l] == lo: l += 1
elif lo + hi < target:
while l < r and nums[l] == lo: l += 1
else:
while l < r and nums[r] == hi: r -= 1
return ans
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
ans = []
i = 0
while (i < n - 2): # 错误地使用了for循环
num = nums[i]
cur_ans = self.twoSum(nums, i + 1, 0 - num)
if cur_ans:
ans += [item + [num] for item in cur_ans]
while i < n - 2 and nums[i] == num: i += 1
return ans
2020-3-5 微软笔试 第三题
前两题有点简单,是签到题,就不耽误大家时间了
第三题主要用hashmap存每个分数的次数, 1 / 2 1/2 1/2 取出来做特殊判断,对去重后的分数进行排序,然后用双指针遍历排序后的分数,找到和为1的两个数。
AC代码:
def solution(X, Y):
n = len(X)
div = []
counter = {}
for i in range(n):
x, y = X[i], Y[i]
f = x / y
# 考虑只有1/2的特殊情况
counter[f] = counter.get(f, 0) + 1
if counter[f] == 1 and f != 0.5:
div.append((f, i))
div.sort()
l, r = 0, len(div) - 1
k = counter.get(.5, 0)
ans = k * (k - 1) // 2
while r > l:
# 判断相加为1 todo: 化简(虽然python不会因为大数而报错)
a, b = X[div[l][1]], Y[div[l][1]]
c, d = X[div[r][1]], Y[div[r][1]]
if a * d + b * c == b * d:
ans += counter[div[l][0]] * counter[div[r][0]]
l += 1
r -= 1
elif div[l][0] + div[r][0] > 1:
r -= 1
else:
l += 1
return ans % int(1e9 + 7)
def gcd(a,b):
if a%b == 0:
return b
else :
return gcd(b,a%b)
print(solution([1, 2, 3, 1, 2, 12, 8, 4], [5, 10, 15, 2, 4, 15, 10, 5]))
print(solution([1, 1, 1], [2, 2, 2]))
print(solution([1, 1, 2], [3, 2, 3]))
print(solution([2, 1, 1], [4, 3, 2]))