Reprint Please specify source: http://blog.csdn.net/crazy1235/article/details/51471280
Subject
Source: https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the both numbers such that they add-to a specific target.
You may assume this each input would has exactly one solution.
Example:
Given nums = [2, 7, one, +], target = 9,
Because Nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Explain
This topic is given an array of int and a target value. The sum of the numbers corresponding to the two subscripts in the array is required to be equal to target.
Returns an array of two subscript elements.
Solutionsolution 1
The stupidest way to do this is to loop the nesting.
Public Static int[]Twosum(int[] Nums,intTarget) {int[] result =New int[2];if(Nums = =NULL|| Nums.length = =0) {returnResult } for(inti =0; i < nums.length; i++) { for(intj = i +1; J < Nums.length; J + +) {if(Nums[i] + nums[j] = = target) {result[0] = i; result[1] = J;returnResult } } }returnResult }
The method has a high time complexity, O (N2).
The spatial complexity is O (1).
Solution 2
Although method one passed the test, but the time complexity is high.
Then see the topic of the prompt tag is "Array" "Hash Table", it is thought to use HashMap to store subscript and value.
/** * Use HashMap storage <br/> * * @param nums * @param target * @return * * Public Static int[]twoSum2(int[] Nums,intTarget) {int[] result =New int[2]; Hashmap<integer, integer> map =NewHashmap<> (); for(inti =0; i < nums.length; i++) {if(Map.containskey (Target-nums[i])) {if(I > Map.get (target-nums[i])) {result[0] = Map.get (Target-nums[i]); result[1] = i; }Else{result[0] = i; result[1] = Map.get (Target-nums[i]); } }Else{Map.put (nums[i], i); } }returnResult }
Note Nums[i] as key, subscript I as value.
Determine if the map contains Target-nums[i] this key.
bingo~~
"Leetcode" 1. The problem solving report of the Sum