题目
给一个数组和一个和,查找出数组中两个数相加为给定的和
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
two-sum
public class TwoSum {
public static void main(String[] args) {
int[] nums = { 1, 3, 4, 5, 6 };
int[] result = twoSum(nums, 10);
System.out.println("result[0]:" + result[0] + ", result[1]=" + result[1]);
result = twoSum2(nums, 10);
System.out.println("result[0]:" + result[0] + ", result[1]=" + result[1]);
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int length = nums.length;
for (int i = 0; i < length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
public static int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap();
int length = nums.length;
for(int i = 0; i < length; i++){
int complement = target - nums[i];
if(map.containsKey(complement) && map.get(complement) != i){
return new int[]{i, map.get(complement)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}