1. 程式人生 > >LeetCode 15 3Sum (C,C++,Java,Python)

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

Problem:

Given an array S of n integers, are there elements abc 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