简体   繁体   English

需要帮助找出问题所在

[英]need help figuring out what is wrong with this

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.给定一个整数数组 nums 和一个 integer 目标,返回两个数字的索引,使它们加起来等于目标。

You may assume that each input would have exactly one solution, and you may not use the same element twice.您可能会假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。

You can return the answer in any order.您可以按任何顺序返回答案。

it works for some test cases but not all and gives an index out of bounds, also how can I make it better它适用于一些测试用例但不是全部,并且给出了一个超出范围的索引,还有我怎样才能让它变得更好

this is my code这是我的代码

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;
    }
}

So, there are quite the few issues in the algo.因此,算法中存在相当多的问题。 some of them to mention below其中一些在下面提到

Let us consider below input让我们考虑以下输入
[3,3,7,4,6,0,3,5]. [3,3,7,4,6,0,3,5]。
So total array length is 8 and array starts from 0 to 7所以总数组长度为 8,数组从 0 到 7

a) here with your logic you are checking the 2 consecutive numbers that add upto a given target which is not the case. a) 在这里,根据您的逻辑,您正在检查加起来达到给定目标的 2 个连续数字,但事实并非如此。 We have to find 2 numbers that may be Non consecutive as well like here lets assume the target given is 13 so we have to return [2,4].我们必须找到 2 个可能不连续的数字,就像这里假设给定的目标是 13,所以我们必须返回 [2,4]。

b) with your current logic, when you run the loop for target 13, definitely your logic will execute till the end. b) 使用您当前的逻辑,当您为目标 13 运行循环时,您的逻辑肯定会执行到最后。 so when i=7, if you condition is checked所以当 i=7 时,如果你的条件被检查

if((nums[7] + nums[8]) == target) {   
               answer[0] = 7;   
               answer[1] = 8;  
            return answer;   
   }  

But we know that our array runs from index 0 to 7 so this will give indexArrayOutOfBound exception as 8th index doesn't exists.但是我们知道我们的数组从索引 0 到 7,所以这将给出 indexArrayOutOfBound 异常,因为第 8 个索引不存在。

Also even if you fix this solution this might not work in optimized way with timeComplexity O(n)此外,即使您修复了此解决方案,也可能无法以优化的方式使用 timeComplexity O(n)

You can refer below solution https://github.com/DivyaJaggya/DSAPractice/blob/main/src/arrays/Find2SumForUnsortedArray.java您可以参考以下解决方案https://github.com/DivyaJaggya/DSAPractice/blob/main/src/arrays/Find2SumForUnsortedArray.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM