Lintcode-medium-two Sum

Source: Internet
Author: User
Tags lintcode

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 mus T is less than INDEX2. Please note that your returned answers (both Index1 and Index2) is not zero-based.

Notice

You may assume this each input would has exactly one solution

Example

numbers= [2, 7, 11, 15] , target=9

Return[1, 2]

Challenge

Either of the following solutions is acceptable:

    • O (n) Space, O (nlogn) time
    • O (n) Space, O (n) time

 Public classSolution {/** @param numbers:an array of Integer * @param target:target = numbers[index1] + numbers[index2] * @re Turn: [index1 + 1, Index2 + 1] (Index1 < INDEX2)*/     Public int[] Twosum (int[] numbers,inttarget) {        //Write your code here                int[] res =New int[2]; HashMap<integer, integer> map =NewHashmap<integer, integer>();  for(inti = 0; i < numbers.length; i++){            if(!Map.containskey (Numbers[i])) {Map.put (target-Numbers[i], i); }            Else{                intin1 = Map.get (numbers[i]) + 1; intin2 = i + 1; res[0] =in1; res[1] =in2; returnRes; }        }                returnRes; }}

Lintcode-medium-two Sum

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.