(1)Two Sum--求数组中相加为指定值的两个数

时间:2023-03-09 03:23:23
(1)Two Sum--求数组中相加为指定值的两个数

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

answer:

 public class TwoSum {
//最low的方法
public int[] twoSum(int[] nums, int target) {
int[] ret = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
ret[0] = i + 1;
ret[1] = j + 1;
}
}
}
return ret; } // 利用map,只需要遍历一次即可
public int[] twoSum1(int[] numbers, int target) {
int[] ret = new int[2]; //初始化一个数组,默认值为0
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
ret[1] = i + 1; //map中放的数字必然是比较早遍历过的
ret[0] = map.get(target - numbers[i]);
return ret;
}
map.put(numbers[i], i + 1);
}
return ret;
} //测试
public static void main(String[] args) {
int[] numbers = { 2, 7, 11, 15 };
int target = 9;
TwoSum test = new TwoSum();
int[] result = test.twoSum1(numbers, target);
System.out.println(Arrays.toString(result));
} }