Given an array of integers and a target value, find the two numbers in the array and the target values.
You can assume that each input corresponds to only one answer, and that the same element cannot be reused.
Example:
Given nums = [2, 7, one, a], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 so return [0, 1]
Problem solving: Today found Leetcode original website, do not know is not the wall, had to shift position. This topic is still relatively simple, the method is more, first look at the first, violent solution, double cycle to determine whether the two value and is equal to target. The code is as follows:
1 classSolution {2 Public int[] Twosum (int[] Nums,inttarget) {3 int[] result =New int[2];4 //Arrays.sort (nums);5 for(inti = 0; i < nums.length-1; i++){6 for(intj = i + 1; J < Nums.length; J + + ){7 if(Nums[i] + nums[j] = =target) {8Result[0] =i;9RESULT[1] =J;Ten returnresult; One } A } - } - return NULL; the } -}
can also use a hash table to do, space change time. Put each element and its corresponding position into the HashMap, before the first to determine whether there is already a corresponding number of data in the table, with which can be the target, there is a return result, not continue to put. The code is as follows:
1 classSolution {2 Public int[] Twosum (int[] Nums,inttarget) {3Map<integer, Integer>map =NewHashmap<integer,integer>();4 for(inti = 0; i < nums.length; i++){5 if(Map.containskey (Target-Nums[i]))6 return New int[]{map.get (Target-Nums[i]), i};7 Map.put (Nums[i], i);8 }9 Throw Newillegalargumentexception ();Ten } One}
1. The sum of two "Leetcode China, by Java"