題目:
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].
意思明確,返回?cái)?shù)組中兩數(shù)和為target值得下標(biāo)
代碼如下:
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的順序和數(shù)組的下標(biāo)一致
result[0] = map.get(target - numbers[i]);
return result;
}
//最開始我是將數(shù)組中所有的值先put進(jìn)去,在這個(gè)for循環(huán)外面,發(fā)現(xiàn),數(shù)組有重復(fù)數(shù)字
//行不通,,,智商壓制
map.put(numbers[i], i );
}
return result;
}
}