15:三数之和

This commit is contained in:
huangge1199@hotmail.com 2021-05-03 20:19:42 +08:00
parent 262c1663c0
commit 1f180f5c57
2 changed files with 131 additions and 0 deletions

View File

@ -0,0 +1,95 @@
//给你一个包含 n 个整数的数组 nums判断 nums 中是否存在三个元素 abc 使得 a + b + c = 0 请你找出所有和为 0 且不重
//复的三元组
//
// 注意答案中不可以包含重复的三元组
//
//
//
// 示例 1
//
//
//输入nums = [-1,0,1,2,-1,-4]
//输出[[-1,-1,2],[-1,0,1]]
//
//
// 示例 2
//
//
//输入nums = []
//输出[]
//
//
// 示例 3
//
//
//输入nums = [0]
//输出[]
//
//
//
//
// 提示
//
//
// 0 <= nums.length <= 3000
// -105 <= nums[i] <= 105
//
// Related Topics 数组 双指针
// 👍 3303 👎 0
package leetcode.editor.cn;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
//15:三数之和
public class ThreeSum {
public static void main(String[] args) {
//测试代码
Solution solution = new ThreeSum().new Solution();
// solution.threeSum(new int[]{-1, 0, 1, 2, -1, -4});
// solution.threeSum(new int[]{-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6});
solution.threeSum(new int[]{-4, -2, -1});
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
for (int first = 0; first < n; ++first) {
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int third = n - 1;
int target = -nums[first];
for (int second = first + 1; second < n; ++second) {
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
while (second < third && nums[second] + nums[third] > target) {
--third;
}
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
ans.add(list);
}
}
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,36 @@
<p>给你一个包含 <code>n</code> 个整数的数组 <code>nums</code>,判断 <code>nums</code> 中是否存在三个元素 <em>abc </em>使得 <em>a + b + c = </em>0 ?请你找出所有和为 <code>0</code> 且不重复的三元组。</p>
<p><strong>注意:</strong>答案中不可以包含重复的三元组。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>nums = [-1,0,1,2,-1,-4]
<strong>输出:</strong>[[-1,-1,2],[-1,0,1]]
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>nums = []
<strong>输出:</strong>[]
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>nums = [0]
<strong>输出:</strong>[]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= nums.length <= 3000</code></li>
<li><code>-10<sup>5</sup> <= nums[i] <= 10<sup>5</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>双指针</li></div></div>\n<div><li>👍 3303</li><li>👎 0</li></div>