Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [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] ]
分析
两层循环,然后按照3Sum的做。O(n3)的复杂度。150ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
对排序后的数组,进行计算的时候,如果满足
1. 最靠前的4个数字之和 > target,则退出计算,因为以后也一定不会满足
2. 前面的数组和 末尾的数字之和 < target,那么说明肯定中间数字之和一定是 < target的,继续
1 2 |
|
同时优化满足条件的判断顺序以及后续处理,可以得到如下代码:16ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|