题目:
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].
方法一:利用了HashMap找key非常快的特性。
/**
* @Author: Wang
* @Date:Created in 23:54 2019/9/15
* @Modify By:
*/
import java.util.HashMap;
import java.util.Map;
/**
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* <p>
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
* <p>
* Example:
* <p>
* Given nums = [2, 7, 11, 15], target = 9,
* <p>
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0, 1].
*/
public class leetCode1 {
public int[] twoSum01(int[] nums, int target) {
Map<Integer,Integer> numsMap = new HashMap<>();
numsMap = swarp(nums);
for(int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if(numsMap.containsKey(complement)) {
return new int[]{i,numsMap.get(complement)};
}
}
throw new IllegalArgumentException("the array dose not contain the numbers wanted");
}
private Map<Integer, Integer> swarp(int[] nums) {
Map<Integer,Integer> numsMap = new HashMap<>();
for(int i = 0;i < nums.length;i++) {
numsMap.put(nums[i],i);
}
return numsMap;
}
}
方法二:暴力解法
/**
* @Author: Wang
* @Date:Created in 23:54 2019/9/15
* @Modify By:
*/
/**
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* <p>
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
* <p>
* Example:
* <p>
* Given nums = [2, 7, 11, 15], target = 9,
* <p>
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0, 1].
*/
public class leetCode1 {
public int[] twoSum02(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length;j++) {
if (nums[i] + nums[j] == target)
return new int[]{i,j};
}
}
throw new IllegalArgumentException("the array dose not contain the numbers wanted");
}
}