Given an array of integers, return indices of the two numbers such that they add up to a specific target.java
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].
複製代碼
暴力法很簡單,遍歷每一個元素 xx,並查找是否存在一個值與 target−x 相等的目標元素。bash
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0 ; i < nums.length; i ++){
for(int j = 0 ; j < nums.length ; j ++){
if(nums[i] + nums[j] == target){
int[] res = {i, j};
return res;
}
}
}
throw new IllegalStateException("the input has no solution");
}
}
複製代碼
使用HashMap,基本思路是:用數組的值做爲key,index做爲value。對數組進行迭代的時候,將元素插入到hashMap中的,這時咱們回過頭來檢查表中是否已經存在當前元素所對應的目標元素。若是它存在,那咱們已經找到了對應解,並當即將其返回。ui
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp =target-nums[i];
if(map.containsKey(temp)){ // 返回布爾
return new int []{map.get(temp),i};
}
map.put(nums[i],i); // key value
}
throw new IllegalStateException("the input has no solution");
}
}
複製代碼