LeetCode 16 3Sum Closest (C, C ++, Java, Python), leetcode3sum

Source: Internet
Author: User

LeetCode 16 3Sum Closest (C, C ++, Java, Python), leetcode3sum
Problem:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. return the sum of the three integers. you may assume that each input wowould have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Solution: This question is basically the same as that of Question 15. It is even simpler. You only need to compare and compare the results. If the match is equal to the target, you can directly return the result !!!
Give an integer array and find the sum of the three numbers that are the shortest distance from the value of the given target.
Solution: Read the Code directly. If you do not understand it, check my 15 questions.
Java source code (in 342 ms ):
public class Solution {    public int threeSumClosest(int[] nums, int target) {        int length=nums.length,Min=Integer.MAX_VALUE;        Arrays.sort(nums);        for(int i=0;i<length-2;i++){            if(i>0 && nums[i]==nums[i-1])continue;            int begin=i+1,end=length-1;            while(begin<end){                int sum=nums[i]+nums[begin]+nums[end];                if(Math.abs(sum-target)<Math.abs(Min))Min=sum-target;                if(sum==target)return target;                else if(sum>target)end--;                else begin++;            }        }        return Min+target;    }}

C language source code (in 9 ms ):
int abs(int tar){    return tar>0?tar:-tar;}void quickSort(int* nums,int first,int end){    int l=first,r=end;    if(first>=end)return;    int temp=nums[l];    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 threeSumClosest(int* nums, int numsSize, int target) {    int begin,end,i,sum,Min=INT_MAX;    quickSort(nums,0,numsSize-1);    for(i=0;i<numsSize-2;i++){        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(abs(sum-target)<abs(Min))Min=sum-target;            if(sum==target)return target;            else if(sum>target)end--;            else begin++;        }    }    return Min+target;}

C ++ source code (in 12 ms ):
class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int length=nums.size(),Min=2147483647;        quickSort(nums,0,length-1);        for(int i=0;i<length-2;i++){            if(i>0 && nums[i]==nums[i-1])continue;            int begin=i+1,end=length-1;            while(begin<end){                int sum=nums[i]+nums[begin]+nums[end];                if(abs(sum-target)<abs(Min))Min=sum-target;                if(sum==target)return target;                else if(sum>target)end--;                else begin++;            }        }        return Min+target;    }private:    int abs(int t){        return t>0?t:-t;    }    void quickSort(vector<int>& nums,int first,int end){        int l=first,r=end,tmp;        if(first>=end)return;        tmp=nums[l];        while(l<r){            while(l<r && nums[r]>=tmp)r--;            if(l<r)nums[l]=nums[r];            while(l<r && nums[l]<=tmp)l++;            if(l<r)nums[r]=nums[l];        }        nums[l]=tmp;        quickSort(nums,first,l-1);        quickSort(nums,l+1,end);    }};

Python source code (in 127 ms ):
class Solution:    # @param {integer[]} nums    # @param {integer} target    # @return {integer}    def threeSumClosest(self, nums, target):        length=len(nums);Min=2147483647        nums.sort()        for i in range(length-2):            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 abs(sum-target)<abs(Min):Min=sum-target                if sum==target:return target                elif sum>target:end-=1                else:begin+=1        return Min+target


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.