import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Three Sum
*
* Given an array S of n integers, are there elements a, b, c in S
* such that a + b + c = 0 ? Find all unique triplets
* in the array which gives the sum of zero.
* Note:
* •Elements in a triplet (a,b,c) must be in non-descending order.
* (ie, a≤b≤ca \leq b \leq ca≤b≤c)
* •The solution set must not contain duplicate triplets.
* For example, given array S = {-1 0 1 2 -1 -4} .
* A solution set is:
* (-1, 0, 1)
* (-1, -1, 2)
*/
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums.length < 3) return result;
Arrays.sort(nums);
final int target = 0;
for (int i = 0; i < nums.length - 2; ++i) {
if (i > 0 && nums[i] == num
Three Sum(找出数组中,所有三个数字的组合,其和为给定值的情况)
最新推荐文章于 2023-12-11 15:07:59 发布
这篇博客讨论了如何在给定数组中找到所有和为目标值的三个数字的组合。内容涵盖了算法思路,可能的解决方案,以及如何优化搜索过程以提高效率。
摘要由CSDN通过智能技术生成