[Leetcode] [001] Both Sum (Java)

Source: Internet
Author: User

The title is here: https://leetcode.com/problems/two-sum/

"Label" Array; Hash Table

"Personal Analysis"

This topic, I feel can also be regarded as an example of space change time. If it is O (n^2) that way of thinking, that is, for a number, to sweep all the rest of the numbers, see if there is a combination that can add up and target. But if we add a hash table, the numbers we sweep can be recorded.

I used (Target-number) as the key, with number in the Nums index as value, encountered a new numbers, if it exists in the map (indicating we have encountered before Target-number), then we are to find The result.

1  Public classSolution {2      Public int[] Twosum (int[] Nums,inttarget) {3         int[] result =New int[2];4Map<integer, integer> indexmap =NewHashmap<integer, integer>();5          for(inti = 0; i < nums.length; i++) {6             intNumber =Nums[i];7             if(Indexmap.containskey (number)) {8                 //found the numbers we are looking for!9                 //! Required result is not zero-based indexed, but 1-basedTenResult[0] = 1 +indexmap.get (number); OneRESULT[1] = 1 +i; A                  Break; -}Else { -                 //put The number we are expecting into the map theIndexmap.put (Target-Number , i); -             } -         } -         returnresult; +     } -  +}

[Leetcode] [001] Both Sum (Java)

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.