Home > Blockchain >  TwoSum return method
TwoSum return method

Time:01-15

So, i was doing an exercice that i found in the internet, and i got confused, so i searched for a solution and ended up with the exercise solution. But still confused of what does the 2 returns mean with the new int[]{i 1,j 1}, what does the {i 1,j 1} do? And then the {-1,-1}.

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        for(int i=0;i<numbers.length;i  ){
            for(int j=i 1;j<numbers.length;j  ){
                if(numbers[i] numbers[j]==target)
                    return new int[]{i 1,j 1};
            }
        }
        return new int[]{-1,-1};
    }
}

I want it to print the indexes of the 2 numbers that will give me the target.

CodePudding user response:

The entire expression new int[]{i 1,j 1} instantiates a new array of two integers, whose values are i 1 and j 1. It seems these are the two indices you're trying to find (if you're indexing from 1). new int[]{-1,-1} similarly creates an array of two integers, both -1, which seems to represent the result that there is no solution in the given array.

CodePudding user response:

From what I can see, the logic of the code is to pass an array in vascular and the objective is not necessarily to find the indexes, imagine the array = {1, 2, 3, 4, 5, 6, 7, 9}, the code goes in each index and from there I followed the subsequent indexes, for example:

starts at 1, goes to 2, 3, 4, 5, 6, 7 and 9, to find the target, the target is based on the value passed in parameter, type, you sent the array I said and sent the value as target 6, then, in the first cycle of the first array (number 1), it will go back to the 4th cycle of the second array until it finds the value 5, adding 1 5 = 6, which 6 is precisely the value sent by parameter as a target, the return will bring you the index {1 1, 4 1}, which will be return new int[]{2, 5}, where {1(this one referring to I) 1, 4(this four referring to j )}

The values ​​returned refer to a new array, I don't see a direct connection with the query of the data later, unless there is another type of logic outside the one presented in another part of the code.

  •  Tags:  
  • Related