Four Sum
Given an arraynumsofn_integers and an integertarget, are there elements_a,b,c, andd_innumssuch that_a+b+c+d=target? Find all unique quadruplets in the array which gives the sum oftarget.
Note: The solution set must not contain duplicate quadruplets.
Example
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]Note
主要是小优化问题
每一轮的指针都要注意去重;
每一轮进入内循环之前,可以直接看一眼 index 与
index 后面的连续几个数
nums[] 末尾的最后几个数
是不是会比 target 小或者大,如果 index 与后面连续的几个数加起来都没 target 大,那么检查这个 index 的必要都没有,可以直接跳过;如果 index 与最末尾的几个数相加依然小于 target,那么说明我们应该直接去看下一个更大的数当 index.
Code
Last updated