Given an array of integers, return indices ofthe two numbers such that they add up to a specific target.
You may assume that each input wouldhave exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2+ 7 = 9,
return [0, 1].
解法一:
public class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length - 1; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
解法二:
public class Solution{
//该过程先判断数组的值是否在HashMap的键中,如果不在HashMap中,则将target和nums的差以键存入HashMap中,同时将nums在数组中的下标存入HashMap的值中。如果HashMap的键中包含数组中的值,则将HashMap的值和数组的下标输出。
public int[] twoSum(int[] nums, int target){
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
int j = map.get(nums[i]);
result[0] = j;
result[1] = i;
break;
}else{
map.put(target - nums[i], i);
}
}
return result;
}
}