Java for Leetcode 001 the Sum of

Source: Internet
Author: User

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, target=9
Output: index1=1, index2=2

A solution to the problem

Brute force enumeration, Time complexity O (n^2), and because Target is a two-digit number, it is only possible to use the brute-force enumeration method even if the array is ordered.

Two ways to solve problems

Since the time required to traverse the graph is relatively fixed, you can use HashMap, with the contents of the array as key, and the array subscript as value, so that the time complexity is O (n).

Therefore, the first step: the array elements into the hashmap inside, the second step: for numbers[] Each value, with Target-numbers[i] in the graph to traverse, if found that there is such a value, and such a value is not numbers[i] corresponding to the node itself, then , the traversal ends.

The Java code is as follows:

1 ImportJava.util.HashMap;2  Public classSolution {3     Static  Public int[] Twosum (int[] numbers,inttarget) {4         int[] a={0,0};5Hashmap<integer,integer> map=NewHashmap<integer,integer>();6          for(inti=0;i<numbers.length;i++){7 Map.put (Numbers[i], i);8         }9          for(inti=0;i<numbers.length;i++){Ten             intgap=target-Numbers[i]; One             if(Map.get (GAP)! =NULL) &&map.get (GAP)! =i) { AA[0]=i+1; -A[1]=map.get (GAP) +1; -                  Break; the             } -         }  -         returnA; -     } +}

Java for Leetcode 001 the Sum of

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.