-4

I'm very new to this java language and practicing to build my basics. So here is the code and also the error please tell me how to resolve this

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

Line 10: error: '.class' expected
                    return int[]{i, j};
                                ^
Line 10: error: not a statement
                    return int[]{i, j};
                                 ^
Line 10: error: ';' expected
                    return int[]{i, j};
                                  ^
Line 10: error: not a statement
                    return int[]{i, j};
                                    ^
Line 10: error: ';' expected
                    return int[]{i, j};
                                     ^
5 errors
nassim
  • 1,547
  • 1
  • 14
  • 26
Saumya
  • 3
  • 1

1 Answers1

0

It is not clear what you want to return if nums[i] + nums[j] never match target, but I'll asume is OK to return an empty array for that case:

class Solution { 
    public int[] twoSum(int[] nums, int target) {

    for(int i = 0; i < nums.length; i++){
        
        for(int j = 0; j < nums.length; j++){
            
            if(nums[i]  + nums[j] == target){
                // you need to add "new"
                return new int[]{i, j};
            }
        }
    }
    // you can also "return null;", or anything else
    return new int[]{};
}

}
  • why we are adding 'new' ? – Saumya May 11 '21 at 13:45
  • We add `new` since all arrays are objects, so `new` will create an Array. There are ways to deal with arrays without `new`, you can check [this answer](https://stackoverflow.com/questions/39032577/declaring-arrays-without-using-the-new-keyword-in-java) for more detail. – Victor Polo De Gyves Montero May 11 '21 at 16:59