题目信息
给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
假设给出的数组中只存在唯一解
例如:给出的数组为 {20, 70, 110, 150},目标值为90,输出 index1=1, index2=2
示例输入:[3,2,4],6
示例输出:[2,3]
题解
这个题不难,但是有一个小陷坑,就是下标是从1开始。
求两数之和,一旦一个数确定了,实际上另一个数也就确定了,这样就可以直接去查找了。
编码
import java.util.Arrays;
public class TwoNumsSum {
public static int[] twoSum (int[] numbers, int target) {
// 定义返回数组
int[] ret = new int[2];
// 遍历数组,查找符合条件的数字组合
for (int i=0; i<numbers.length; i++) {
// 根据目标数字确定待查找的另一个数字
int aim = target - numbers[i];
// 因同一个数字不可用两次,两个数字位置从遍历位置加1
for (int j=i+1; j<numbers.length; j++) {
// 找到目标数字后,立即将下标位置赋给返回数组返回
if (numbers[j] == aim) {
ret[0] = i+1;
ret[1] = j+1;
return ret;
}
}
}
return ret;
}
public static void main(String[] args) {
int[] arr = {3,2,4};
int target = 6;
System.out.println(Arrays.toString(twoSum(arr, target)));
}
}