The sum solution

Source: Internet
Author: User

Question:

Given an array of integers, find the numbers such that they add up to a specific target number.

The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.

You may assume this each input would has exactly one solution.

Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2

Solution:

1. O (n2) runtime, O (1) space–brute Force:

The brute force approach are simple. Loop through each element x and the find if there is another value, the Equals to target–x. As finding another value requires looping through the rest of the array, its runtime complexity is O(n2).

2. O (n) runtime, O (n) space–hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map, maps a value to it in Dex.

1  Public classSolution {2      Public int[] Twosum (int[] Nums,inttarget) {3Map<integer, integer> HM =NewHashmap<integer, integer>();4         int[] result =New int[2];5         intLength =nums.length;6          for(inti = 0; i < length; i++) {7             intleft = target-Nums[i];8             if(Hm.get (left)! =NULL) {9Result[0] = Hm.get (left) + 1;TenRESULT[1] = i + 1; One}Else { A Hm.put (Nums[i], i); -             } -         } the         returnresult; -     } -}
3. O (Nlogn) runtime, O (1) space-binary Search

Similar as solution 1, but with binary search to find INDEX2.

4. O (nlogn) runtime, O (1) space-two pointers

First, sort the array in ascending order Vwhich uses O (NLOGN).

Then, the right pointer starts from biggest number and the left pointer starts from smallest number. If the sum is greater than the target number, move the right pointer. If the sum is smaller than the target number, move the left pointer.

The sum solution

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.