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)
  • 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)

Solution:

先对数组进行排序,时间复杂度O(log(n)),然后定好一个数的位置,查找另外两个数的和等于-nums[i]的组合,由于数组排好序了,所以可以从两边往中间走,当结果大于0的时候后边往后退一步,否则前边进一步,时间复杂度O(n^2),所以时间复杂度为O(n^2)

题目大意:

给一组数组,要求得出所有和为0的数字组合,要求数字组合不能重复出现,并且按照升序排列

解题思路:

见Solution.

Java源代码(用时437ms):

public class Solution {
    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;
    }
}

C语言源代码(用时48ms):

/**
 * Return an array of arrays of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
void quickSort(int* nums,int first,int end){
    int temp,l,r;
    if(first>=end)return;
    temp=nums[first];
    l=first;r=end;
    while(l<r){
        while(l<r && nums[r]>=temp)r--;
        if(l<r)nums[l]=nums[r];
        while(l<r && nums[l]<=temp)l++;
        if(l<r)nums[r]=nums[l];
    }
    nums[l]=temp;
    quickSort(nums,first,l-1);
    quickSort(nums,l+1,end);
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
    int i,sum,top=-1,begin,end;
    int** res=(int**)malloc(sizeof(int*)*(numsSize*(numsSize-1)*(numsSize-2))/6);
    if(numsSize<3){
        *returnSize=0;
        return res;
    }
    quickSort(nums,0,numsSize-1);
    for(i=0;i<numsSize;i++){
        if(nums[i]>0)break;
        if(i>0 && nums[i]==nums[i-1])continue;
        begin=i+1;end=numsSize-1;
        while(begin<end){
            sum=nums[i]+nums[begin]+nums[end];
            if(sum==0){
                top++;
	            res[top]=(int*)malloc(sizeof(int)*3);
	            res[top][0]=nums[i];res[top][1]=nums[begin];res[top][2]=nums[end];
	            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++;
        }
    }
    *returnSize=top+1;
    return res;
}

C++源代码(66ms):

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        int len=nums.size();
        if(len<3){
            return res;
        }
        sort(nums.begin(),nums.end());
        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){
                    vector<int> t;
                    t.push_back(nums[i]);
                    t.push_back(nums[begin]);
                    t.push_back(nums[end]);
                    res.push_back(t);
                    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;
    }
};

Python源代码(407ms):

class Solution:
    # @param {integer[]} nums
    # @return {integer[][]}
    def threeSum(self, nums):
        res = []
        length=len(nums)
        if length<3:return res
        nums.sort()
        for i in range(length):
            if nums[i]>0:break
            if i>0 and nums[i]==nums[i-1]:continue
            begin=i+1;end=length-1
            while begin < end:
                sum=nums[i]+nums[begin]+nums[end]
                if sum==0:
                    tmp=[nums[i],nums[begin],nums[end]]
                    res.append(tmp)
                    begin+=1;end-=1
                    while begin<end and nums[begin]==nums[begin-1]:begin+=1
                    while begin<end and nums[end] == nums[end+1]:end-=1
                elif sum>0:end-=1
                else:begin+=1
        return res
时间: 2024-10-04 13:40:17

LeetCode 15 3Sum (C,C++,Java,Python)的相关文章

[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).

[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解析与快速排序算法-Java实现

Q: 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 = [-

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

[LeetCode] 15. 3Sum Java

题目: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 = [-

Leetcode 15. 3Sum(python)

先排序,再循环遍历,用双指针. class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ solution=[] nums.sort() for i in range(len(nums)-1): left=i+1 right=len(nums)-1 while left<right: val=

LeetCode 18 4Sum (C,C++,Java,Python)

Problem: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descendi

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 contain duplicate triplets. For example, given array S = [-1,

leetcode刷题记录(JAVA&amp;Python)

---恢复内容开始--- --题目导航见页面左上角的悬浮框#目录导航#-- 相似题型: 1.1 twosum两数之和   2.2 3Sum三数之和 一.简单 1.1 twosum两数之和 原题: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 实例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 暴力解