码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-03 20:44:52      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:c++   java   leetcode   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


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

标签:c++   java   leetcode   python   算法   

原文地址:http://blog.csdn.net/hcbbt/article/details/44041671

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!