查找(II)
1. 两数之和
题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
if n < 2:
return []
for i in range(n):
a = nums[i]
nums[i] = ''
if (target-a) in nums:
index1 = i
k = target - a
break
for j in range(len(nums)):
if nums[j] == k:
index2 = j
break
return [index1, index2]
15. 三数之和
题目:给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。注意:答案中不可以包含重复的三元组。
class Solution:
def threeSum(self, nums: [int]) -> [[int]]:
nums.sort()
res, k = [], 0
for k in range(len(nums) - 2):
if nums[k] > 0: break # 1. because of j > i > k.
if k > 0 and nums[k] == nums[k - 1]: continue # 2. skip the same `nums[k]`.
i, j = k + 1, len(nums) - 1
while i < j: # 3. double pointer
s = nums[k] + nums[i] + nums[j]
if s < 0:
i += 1
while i < j and nums[i] == nums[i - 1]: i += 1
elif s > 0:
j -= 1
while i < j and nums[j] == nums[j + 1]: j -= 1
else:
res.append([nums[k], nums[i], nums[j]])
i += 1
j -= 1
while i < j and nums[i] == nums[i - 1]: i += 1
while i < j and nums[j] == nums[j + 1]: j -= 1
return res
16. 最接近的三数之和
题目:给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
redsult = []
nums.sort()
tmp = nums[0] + nums[1] + nums[2]
res = abs(nums[0] + nums[1] + nums[2] - target)
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
currSum = nums[i] + nums[left] + nums[right]
if currSum == target:
return currSum
else:
if abs(currSum - target) < res:
res = abs(currSum - target)
tmp = currSum
if currSum < target:
left += 1
else:
right -= 1
return tmp
18. 四数之和
题目:给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。注意:答案中不可以包含重复的四元组。
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res = []
if len(nums)<4:
return res
n = len(nums)
for first in range(n-3):
if first >0 and nums[first] ==nums[first-1]:
continue #去掉重复的个元素
for second in range(first+1,n-2):
if second >first+1 and nums[second] ==nums[second-1]:
continue
third,fourth = second+1,n-1
while third<fourth:
if nums[first]+ nums[second]+nums[third] + nums[fourth] <target:
third += 1
elif nums[first]+ nums[second]+nums[third] + nums[fourth] >target:
fourth -= 1
else:
res.append([nums[first],nums[second],nums[third],nums[fourth]])
while third < fourth and nums[third]==nums[third+1]:
third+=1
while third < fourth and nums[fourth]==nums[fourth-1]:
fourth -= 1
third +=1
fourth -=1
return res
参考:https://github.com/datawhalechina/team-learning