【发布时间】:2019-03-30 19:29:45
【问题描述】:
我想解决以下问题:
给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。
我将以下数组作为输入 - [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);
}
}
这是解决我的问题的正确方法吗?
【问题讨论】:
-
您需要找到所有个这样的匹配索引对,还是可以在找到第一个时停止?
-
我可以停止寻找第一个。我的程序甚至无法编译大声笑
-
doesn't even compile... 鉴于您的代表水平,您不认为您至少应该发布有效的 Java 代码吗? -
你为什么选择随机索引而不是循环?
-
你的程序有什么问题?