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)