核心思想就是利用sorted array来简单排除需要输出答案的唯一性,以及在2sum map方法在高阶的不适用性
然后可以通过sort来讲高难度问题转化成2sum的小问题
比较当前和目标之间的关系,然后移动指针
2 Sum
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
2 Sum sorted
Given an array of integers numbers
that is already sorted in ascending order, find two numbers such that they add up to a specific target
number.
Return the indices of the two numbers (1-indexed) as an integer array answer
of size 2
, where 1 <= answer[0] < answer[1] <= numbers.length
.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
3 Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Notice that the solution set must not contain duplicate triplets.
3 Sum closest
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
4 Sum
Given an array nums
of n
integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]
such that:
0 <= a, b, c, d < n
a
,b
,c
, andd
are distinct.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Code example
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
# Edge case
if nums == None or len(nums) <= 2:
return -1
# Other case
nums.sort()
diff = float('inf')
ret = 0
# Iterate
# -3 0 1 2
for i in range(0, len(nums) - 2):
t = target - nums[i] # real target is defined as t
j = i + 1
k = len(nums) - 1
while j < k:
if abs(t - nums[j] - nums[k]) < diff:
ret = nums[i] + nums[j] + nums[k]
diff = abs(t - nums[j] - nums[k])
if nums[j] + nums[k] == t:
return target
elif nums[j] + nums[k] < t:
j = j + 1
else:
k = k - 1
return ret