Category | Difficulty | Likes | Dislikes |
---|
algorithms | Medium (36.88%) | 1691 | - |
Tags
array
| hash-table
| two-pointers
Companies
linkedin
给你一个由 n
个整数组成的数组 nums
,和一个目标值 target
。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]]
(若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a
、b
、c
和 d
互不相同nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:
1
2
| 输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
|
示例 2:
1
2
| 输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
|
提示:
1 <= nums.length <= 200
-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>
-10<sup>9</sup> <= target <= 10<sup>9</sup>
Discussion | Solution
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
45
46
47
48
49
50
51
| struct Solution;
// @lc code=start
impl Solution {
/// ## 解题思路
/// - 双指针
/// 1. 先排序;
/// 2. 先定前面两个进行遍历;
/// 3. 剩下两个用双指针从两边向中间遍历;
pub fn four_sum(nums: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
let mut res: Vec<Vec<i32>> = vec![];
let len = nums.len();
if len < 4 {
return res;
}
let mut nums = nums;
nums.sort();
for i in 0..len - 3 {
if i > 0 && nums[i] == nums[i - 1] {
continue;
}
for j in i + 1..len - 2 {
if j > i + 1 && nums[j] == nums[j - 1] {
continue;
}
let (mut l, mut r) = (j + 1, len - 1);
while l < r {
let t = nums[i] + nums[j] + nums[l] + nums[r];
if t == target {
res.push([nums[i], nums[j], nums[l], nums[r]].to_vec());
l += 1;
r -= 1;
while l < r && nums[l] == nums[l - 1] {
l += 1;
}
while l < r && nums[r] == nums[r + 1] {
r -= 1;
}
} else if t < target {
l += 1;
} else {
r -= 1;
}
}
}
}
res
}
}
// @lc code=end
|