[Leetcode] Three sums && three cloest sums && four sums

Source: Internet
Author: User

Given an array S of n integers, is 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 is in non-descending order. (ie, abc)
    • 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)


Idea: If the direct use of triple traversal brute force crack, the time complexity of O (n^3). It is possible to refer to the sum of two numbers, and for an ordered array, the time complexity of finding two numbers and N is O (n). Sorts the array, and the time complexity is O (NLog (n)). Finally, the problem becomes the number of the first selection, and then the remaining array of query Target-nums[i] Two number, pay attention to the method of checking the weight, then the total time complexity O (n^2) +o (Nlog (n)) =o (n^2).
 Public classSolution { PublicList<list<integer>> Threesum (int[] nums)        {Arrays.sort (nums); intlen=nums.length; List<List<Integer>> list=NewArraylist<>();  for(inti=0;i<len-2;i++)        {            //Go heavy            if(i>0 && nums[i]==nums[i-1])Continue; inttarget2=0-Nums[i]; Twosum (nums, I+1, Target2, list); }        returnlist; }     Public voidTwosum (int[] Nums,intStartintTarget,list<list<integer>>list) {        intHead=start, End=nums.length-1;  while(head<end) {            intsum=nums[head]+Nums[end]; if (sum<target) {head++;            } else if (sum>target) {end--; }            Else{List<Integer> temp=NewArraylist<>(); Temp.add (Nums[start-1]);                Temp.add (Nums[head]);                Temp.add (Nums[end]);                                List.add (temp); //eliminate the possibility of duplication, because it is an ordered array, from small to large, so as long as one one to find duplicates and skip can                intK=head+1;  while(K<end && Nums[k]==nums[head]) k++; Head=K; K=end-1;  while(K>head && nums[k]==nums[end]) k--; End=K; }        }    }}

Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.

    For example, given array S = {-1 2 1-4}, and target = 1.    The sum is closest to the target is 2. (-1 + 2 + 1 = 2).

 Public classSolution { Public intThreesumclosest (int[] Nums,inttarget)        {Arrays.sort (nums); intdis=Integer.max_value; intResult=0;  for(inti=0;i<nums.length-2;i++)        {            inttarget2=target-Nums[i]; intRe=twosumcloest (Nums, i+1, Target2); intD=math.abs (target-re-Nums[i]); if(d<dis) {Dis=D; Result=re+Nums[i]; if(d==0)                    returnTarget; }        }        returnresult; }     Public intTwosumcloest (int[] Nums,intStartinttarget) {        intHead=start,tail=nums.length-1; intRe=0,d=Integer.max_value;  while(head<tail) {            intsum=nums[head]+Nums[tail]; if(sum<target) {                intdis=target-sum; if(dis<d) {d=dis; Re=sum; } head++; }            Else if(target<sum) {                intdis=sum-Target; if(dis<d) {d=dis; Re=sum; } Tail--; }            Else {                returnTarget; }        }        returnre; }}

[Leetcode] Three sums && three cloest sums && four sums

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.