題目
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
示例
給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
這是一道簡單題,但是也很考驗思維
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
//key爲數值,value爲下標,也就是真正想要的數據
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
//獲得補數
int dif = target - nums[i];
//如果map的key加上當前的數值剛好等於目標值,則直接拿到了想要的數據,返回即可
if (map.containsKey(dif)) {
result[0] = i;
result[1] = map.get(dif);
return result;
}
//如果map裏的數值補數想要的補數,則存起來供後面循環的時候來查詢
map.put(nums[i], i);
}
return result;
}
}
舉一反三
現在不是兩數想加了,而是兩數相乘、甚至是我們自定義的一種符號@該如何實現?