java返回两个数字的索引,这样它们加起来就是一个特定的目标
我想解决以下问题:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
我将下面的数组作为输入-[2,7,11,15],目标=9
因为nums[0]+nums[1]=2+7=9, 返回[0,1]
这是我的密码-
import java.util.Random;
public class TwoSum {
static int[] numbers = new int[] {2, 7, 11, 15};
int[] indices = new int[numbers.length];
public static int[] returnIndices(int target, int[] inputArr) {
int[] indices = new int[2];
int randomOne = new Random().nextInt(inputArr.length);
int randomTwo = new Random().nextInt(inputArr.length);
while(true) {
if(target == inputArr[randomOne] + inputArr[randomTwo]) {
indices[0] = randomOne;
indices[1] = randomTwo;
break;
}
}
System.out.println("done");
return indices;
}
public static void main(String[] args) {
int[] output = returnIndices(9, numbers);
}
}
这是解决我问题的正确方法吗
# 1 楼答案
# 2 楼答案
C版本
# 3 楼答案
可以使用hashmap以以下方式存储第一个数组:
接下来获取目标元素9,并从索引0开始遍历给定数组
索引0处的元素为2-->;计算(9-2)=7-->;检查7是否是hashmap中的键
附加说明:您需要注意以下情况:
arr=[3,2,1,1]target=6(本例中不存在答案,但通过上述方法,当计算6-3=3时,得到的答案是索引0。)
但这可以通过检查(target arr[i]==arr[i])是否返回true来轻松解决。如果返回true,并且hashmap在键arr[i]处存储了两个索引,则将其作为答案返回,否则继续下一个元素
# 4 楼答案
}