[LeetCode]--15. 3Sum

简介: 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: The solution set must not

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: 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]
]

给一组数组,要求得出所有和为0的数字组合,要求数字组合不能重复出现,并且按照升序排列。
先对数组进行排序,时间复杂度O(log(n)),然后定好一个数的位置,查找另外两个数的和等于-nums[i]的组合,由于数组排好序了,所以可以从两边往中间走,当结果大于0的时候后边往后退一步,否则前边进一步,时间复杂度O(n^2),所以时间复杂度为O(n^2)。

public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        int len = nums.length;
        if (len < 3)
            return res;
        Arrays.sort(nums);
        for (int i = 0; i < len; i++) {
            if (nums[i] > 0)
                break;
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            int begin = i + 1, end = len - 1;
            while (begin < end) {
                int sum = nums[i] + nums[begin] + nums[end];
                if (sum == 0) {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums[i]);
                    list.add(nums[begin]);
                    list.add(nums[end]);
                    res.add(list);
                    begin++;
                    end--;
                    while (begin < end && nums[begin] == nums[begin - 1])
                        begin++;
                    while (begin < end && nums[end] == nums[end + 1])
                        end--;
                } else if (sum > 0)
                    end--;
                else
                    begin++;
            }
        }
        return res;
    }
目录
相关文章
|
11月前
|
存储 算法 安全
LeetCode - #1 Two Sum
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #1 Two Sum
|
12月前
|
机器学习/深度学习
leetcode - two-sum
leetcode - two-sum
66 0
|
测试技术
LeetCode 204. Count Primes
统计所有小于非负整数 n 的质数的数量。
31 0
LeetCode 204. Count Primes
|
机器学习/深度学习 Android开发 C++
LeetCode之Two Sum
LeetCode之Two Sum
101 0
|
算法 索引 C++
[LeetCode]--69. Sqrt(x)
Implement int sqrt(int x). Compute and return the square root of x. 我采用的是二分法。每次折中求平方,如果大了就把中值赋给大的,如果小了就把中值赋给小的。 public int mySqrt(int x) { long start = 1, end = x; while
837 0
|
机器学习/深度学习
[LeetCode]--50. Pow(x, n)
Implement pow(x, n). 其实这个题递归和非递归应该都不难实现,就是边界值的问题。 public double myPow(double x, int n) { if (n == 0) return 1.0; double res = 1.0; if (n &lt; 0) {
986 0
|
Java
[LeetCode]--371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. Credits: Special thanks to @fujiaozhu for addin
1130 0