题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param num int整型一维数组 # @return int整型二维数组 # from typing import List class Solution: def threeSum(self , num: List[int]) -> List[List[int]]: # write code here n = len(num) num.sort() ans = [] for i in range(n - 2): x = num[i] if i > 0 and x == num[i - 1]: continue if x + num[i + 1] + num[i + 2] > 0: break if x + num[-2] + num[-1] < 0: continue j, k = i + 1, n - 1 while j < k: s = x + num[j] + num[k] if s > 0: k -= 1 elif s < 0: j += 1 else: ans.append([x, num[j], num[k]]) j += 1 while j < k and num[j] == num[j - 1]: j += 1 k -= 1 while j < k and num[k] == num[k + 1]: k -= 1 return ans
算法刷题记录 文章被收录于专栏
刷题,记录牛客的101