[英]need help figuring out what is wrong with this
给定一个整数数组 nums 和一个 integer 目标,返回两个数字的索引,使它们加起来等于目标。
您可能会假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。
您可以按任何顺序返回答案。
它适用于一些测试用例但不是全部,并且给出了一个超出范围的索引,还有我怎样才能让它变得更好
这是我的代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] answer = new int[nums.length -1];
for(int i =0; i < nums.length; i++){
if((nums[i] + nums[i+1]) == target) {
answer[0] = i;
answer[1] = i + 1;
return answer;
}
}
return answer;
}
}
因此,算法中存在相当多的问题。 其中一些在下面提到
让我们考虑以下输入
[3,3,7,4,6,0,3,5]。
所以总数组长度为 8,数组从 0 到 7
a) 在这里,根据您的逻辑,您正在检查加起来达到给定目标的 2 个连续数字,但事实并非如此。 我们必须找到 2 个可能不连续的数字,就像这里假设给定的目标是 13,所以我们必须返回 [2,4]。
b) 使用您当前的逻辑,当您为目标 13 运行循环时,您的逻辑肯定会执行到最后。 所以当 i=7 时,如果你的条件被检查
if((nums[7] + nums[8]) == target) {
answer[0] = 7;
answer[1] = 8;
return answer;
}
但是我们知道我们的数组从索引 0 到 7,所以这将给出 indexArrayOutOfBound 异常,因为第 8 个索引不存在。
此外,即使您修复了此解决方案,也可能无法以优化的方式使用 timeComplexity O(n)
您可以参考以下解决方案https://github.com/DivyaJaggya/DSAPractice/blob/main/src/arrays/Find2SumForUnsortedArray.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.