# 3Sum algorithm, 3 sumalgorithm

Source: Internet
Author: User

3Sum algorithm, 3 sumalgorithm

Repeat the original question: (click an image to go to the source link)

The Chinese explanation for this question is,

Enter an array, for example, {-1 0 1 2-1-4}, and find three numbers (a, B, c) from the array to make it and 0, output all (a, B, c) combinations.

Abc must not be repeated, and a <= B <= c.

When getting this question, Every programmer can think of the following algorithm, namely brute-force cracking. the time complexity is o (n ^ 3 ):

`1             for(int i=0;i<nums.length;i++){2                 for(int j=i+1;j<nums.length;j++){3                     for(int k=j+1;k<nums.length;j++){4                         if(nums[i]+nums[j]+nums[k]==0){5                             addResult(nums[i], nums[j], nums[k]); 6                         }7                     }8                 }9             }`

First, sort the input array. In this way, nums [I] <nums [j] <nums [k] can be guaranteed because of the I <j <k] above.

In fact, my algorithm is optimized based on brute-force cracking to minimize time complexity.

The method for sorting Arrays in java is: Arrays. sort (nums );

The third loop is actually unnecessary, because after the I and j values are determined, the nums [k] value to be searched has been determined, -(nums [I] + nums [j]).

Therefore, you only need to judge whether this value exists in the remaining elements of the array.

Based on this idea, I constructed a hashmap as a hash index table to find the location where each value appears: (considering that a value may appear in multiple locations, use arraylist)

Because nums has been sorted, The arraylist in the index table is also sorted.

`HashMap<Integer, ArrayList<Integer>> index = new HashMap<>();`

The code for constructing the index table is as follows:

` 1         for(int i=0;i<nums.length;i++){ 2             int num = nums[i]; 3             if(num==0){ 4                 n++; 5             } 6             if(index.get(num)==null){ 7                  8                  9                 index.put(num, new ArrayList<Integer>());10             }11             12             index.get(num).add(i);13             14             15         }`

N indicates the number of zeros. If n> = 3, a [0 0 0] is output directly.

I have been thinking about the number method required to query the index table for a long time. Finally, I came up with a very good method:

` 1                 int p = -(nums[i]+nums[j]); 2                 if(p<0) continue; 3                 ArrayList<Integer> in = index.get(p); 4                 if(in==null) continue; 5                 if(in.get(in.size()-1)>j){ 6                     if(p>nums[j]){ 7                         addResult(nums[i], nums[j],p);  8                     }else if(p>nums[i]){ 9                         addResult(nums[i], p,nums[j]);10                     }else{11                         addResult(p,nums[i], nums[j]);12                     }13                     14                 }`

Why should p <0 be discarded in Row 3? Because we need to avoid repetition. If p is also a negative number, nums [I] <nums [j] may cause two problems:

① Nums [I] And nums [j] are both positive numbers;

② Nums [I] is a negative number, and nums [j] is a positive number.

In other scanning processes, the following will occur:

① Nums [I] '= p, p' = nums [I], nums [j]' = nums [j] at that time;

② P '= nums [j], nums [I]' = min (nums [I], p), nums [j] '= max (nums [I], p ).

5th rows in. get (in. size ()-1)> what does j mean?

At this time, we need to find a k (k> j) so that nums [k] = p. If yes, nums [k] is output.

ArrayList in indicates that all k values of nums [k] = p are obtained. If the maximum k value is greater than j, then k> j exists, so does nums [k] = p?

K> j is required, because the following situations do not meet the requirements:

Input [-1 0 1 2] cannot output [-1-1 2] Because the index of-1 is , it does not meet k> j

To avoid duplication,

I use the addResult function to avoid repetition. you should understand it at first glance.

`1 HashSet <String> repeat = new HashSet <String> (); // re-query 2 List <Integer> result = new distinct List <Integer> (); 3 4 5 public void addResult (int n1, int n2, int n3) {6 String s = n1 + "&" + n2; 7 8 if (! Repeat. contains (s) {9 List <Integer> p = new ArrayList <> (); 10 p. add (n1); 11 p. add (n2); 12 p. add (n3); 13 result. add (p); 14 repeat. add (s); 15} 16}`

The detailed code is as follows:

Related Keywords:
Related Article

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.