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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
題目:
在一個int陣列中,找到哪兩個數相加等於target,並傳回兩個數在陣列中的索引值,每次都只能有一個答案,並且不能使用兩個相同的數
解答:
class TwoSun1 {
private static int[] res;
public static void main(String[] args) {
int nums[] = {2, 7, 11, 15};
int target = 9;
twoSum(nums, target);
System.out.print("[" + res[0] + ", " + res[1] + "]");
}
public static int[] twoSum(int nums[], int target) {
res = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) { // 如果map中有target-nums[i]的元素
res[0] = map.get(target - nums[i])
res[1] = i; //i=1
} else {
map.put(nums[i], i); //使用HashMap存每個數的值和索引
}
}
return res;
}
}