题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
意思明确,返回数组中两数和为target值得下标
代码如下:
public class TwoSum {
public static void main(String[] args) {
TwoSumImpl t = new TwoSumImpl();
int s[] ={5,2,5, 11};
int tag = 10;
int [] result = t.twoSum(s,tag);
System.out.println(" ======= "+Arrays.toString(result));
}
}
class TwoSumImpl {
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) { // 核心
System.out.println(map);
result[1] = i ; //i的顺序和数组的下标一致
result[0] = map.get(target - numbers[i]);
return result;
}
//最开始我是将数组中所有的值先put进去,在这个for循环外面,发现,数组有重复数字
//行不通,,,智商压制
map.put(numbers[i], i );
}
return result;
}
}