题目:
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].
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 2)
return null;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i],i);
}
int[] res = null;
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i]) && i != map.get(target - nums[i])){
res = new int[2];
res[0] = i;
res[1] = map.get(target - nums[i]);
return res;
}
}
return res;
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
System.out.println(Arrays.toString(new TwoSum().twoSum(nums, target)));
}
}
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 2)
return null;
Map<Integer, Integer> map = new HashMap<>(nums.length, 1.0F);
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
return new int[] { map.get(nums[i]), i };
}
map.put(target-nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
System.out.println(Arrays.toString(new TwoSum().twoSum(nums, target)));
}
}