[LeetCode] 015. 3Sum (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)

Github: https://github.com/illuz/leetcode


015.3Sum (Medium)

链接

题目:https://oj.leetcode.com/problems/3sum/

代码(github):https://github.com/illuz/leetcode

题意

在给定数列中找出三个数,使和为 0。

分析

先排序,再左右夹逼,复杂度 O(n*n)。

N-sum 的题目都可以用夹逼做,复杂度可以降一维。

这题数据更新后卡得很紧, C++ 不能全部加完再用 STL 的 erase 和 unique 去重,要一边判断一边加。

代码

C++:

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
		vector<vector<int> > ret;
		int len = num.size();
		int tar = 0;

		if (len <= 2)
			return ret;

		sort(num.begin(), num.end());

		for (int i = 0; i <= len - 3; i++) {
			// first number : num[i]
			int j = i + 1;	// second number
			int k = len - 1;	// third number
			while (j < k) {
				if (num[i] + num[j] + num[k] < tar) {
					++j;
				} else if (num[i] + num[j] + num[k] > tar) {
					--k;
				} else {
					ret.push_back({ num[i], num[j], num[k] });
					++j;
					--k;
					// folowing 3 while can avoid the duplications
					while (j < k && num[j] == num[j - 1])
						++j;
					while (j < k && num[k] == num[k + 1])
						--k;
				}
			}
			while (i <= len - 3 && num[i] == num[i + 1])
				++i;
		}

		// sort and unique will cost a lot of time and course TLE
		// sort(ret.begin(), ret.end());
		// ret.erase(unique(ret.begin(), ret.end()), ret.end());
		return ret;
    }
};

Java:

public class Solution {

    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        int len = num.length, tar = 0;

        if (len <= 2)
            return  ret;

        Arrays.sort(num);

        for (int i = 0; i <= len - 3; i++) {
            // first number : num[i]
            int j = i + 1;	// second number
            int k = len - 1;	// third number
            while (j < k) {
                if (num[i] + num[j] + num[k] < tar) {
                    ++j;
                } else if (num[i] + num[j] + num[k] > tar) {
                    --k;
                } else {
                    ret.add(Arrays.asList(num[i], num[j], num[k]));
                    ++j;
                    --k;
                    // folowing 3 while can avoid the duplications
                    while (j < k && num[j] == num[j - 1])
                        ++j;
                    while (j < k && num[k] == num[k + 1])
                        --k;
                }
            }
            while (i <= len - 3 && num[i] == num[i + 1])
                ++i;
        }
        return ret;

    }
}

Python:

class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):
        if len(num) <= 2:
            return []

        ret = []
        tar = 0
        num.sort()
        i = 0
        while i < len(num) - 2:
            j = i + 1
            k = len(num) - 1
            while j < k:
                if num[i] + num[j] + num[k] < tar:
                    j += 1
                elif num[i] + num[j] + num[k] > tar:
                    k -= 1
                else:
                    ret.append([num[i], num[j], num[k]])
                    j += 1
                    k -= 1
                    # folowing 3 while can avoid the duplications
                    while j < k and num[j] == num[j - 1]:
                        j += 1
                    while j < k and num[k] == num[k + 1]:
                        k -= 1
            while i < len(num) - 2 and num[i] == num[i + 1]:
                i += 1
            i += 1
        return ret
时间: 2024-10-13 23:27:21

[LeetCode] 015. 3Sum (Medium) (C++/Java/Python)的相关文章

[LeetCode] 018. 4Sum (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 018.4Sum (Medium) 链接: 题目:https://oj.leetcode.com/problems/4sum/ 代码(github):https://github.com/illuz/leetcode 题意: 给一个数列 S ,找出四个数 a,b,c,d 使得a + b + c + d = targ

LeetCode 15 3Sum (C,C++,Java,Python)

Problem: 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 ≤ c)

[LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 016.3Sum_Closest (Medium) 链接: 题目:https://oj.leetcode.com/problems/3sum-closest/ 代码(github):https://github.com/illuz/leetcode 题意: 在给定数列中找出三个数,使和最接近 target. 分析:

LeetCode 015 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: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The

[LeetCode] 011. Container With Most Water (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 011.Container_With_Most_Water (Medium) 链接: 题目:https://oj.leetcode.com/problems/container-with-most-water/ 代码(github):https://github.com/illuz/leetcode 题意: 给一些

[LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 012.Integer_to_Roman (Medium) 链接: 题目:https://oj.leetcode.com/problems/integer-to-roman/ 代码(github):https://github.com/illuz/leetcode 题意: 把十进制转为罗马数. 分析: 模拟即可.

[LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 005.Longest_Palindromic_Substring (Medium) 链接: 题目:https://oj.leetcode.com/problems/Longest-Palindromic-Substring/ 代码(github):https://github.com/illuz/leetcode

[LeetCode] 001. Two Sum (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 001.Two_Sum (Medium) 链接: 题目:https://oj.leetcode.com/problems/two-sum/ 代码(github):https://github.com/illuz/leetcode 题意: 一个数组中两个位置上的数的和恰为 target,求这两个位置. 分析: 暴力找

[LeetCode] 002. Add Two Numbers (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 002.Add_Two_Numbers (Medium) 链接: 题目:https://oj.leetcode.com/problems/add-two-numbers/ 代码(github):https://github.com/illuz/leetcode 题意: 求两个 List 相加产生的新的一个 List