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

來源:互聯網
上載者:User

LeetCode 15 3Sum (C,C++,Java,Python),leetcode3sum
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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.