0

I'm trying to solve LeetCode "Two Sum" problem in Java. I solved it in Python and tried rewriting it in Java.

This is my solution in Python.

def twoSum(self, lst, target):
       for i in range(len(lst)):
          first_num = lst[i]
          rem = target-first_num
           
          if rem in lst[i+1:]:
             out = [i, lst[i+1:].index(rem)+i+1]
          return(out)

This is what I tried so far with converting it to Java. (I'm new to Java)

import java.util.Arrays;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int size_of_lst = nums.length;
        int[] out = new int[2];      
        
        for(int i = 0; i < size_of_lst; i++){
            int first = nums[i];
            int rem = target - first;  
                        
            // getting lst[i+1:]
            int[] newArray = Arrays.copyOfRange(nums, i+1, size_of_lst);
            
            if(Arrays.asList(newArray).contains(rem)){ 
                out[0] = i;

                // because we sliced the array from [i+1: end]
                int ind = Arrays.asList(newArray).indexOf(rem) + i + 1;
                
                out[1] = ind;  
            }
        }
        return out;
    }
}

I tried putting print statements and from what I noted, it seems like the code does not go inside the "if" statement.

Sample input 1 - 
lst - [2,7,11,15]
target - 9

Output from my code [0, 0] (for every input, this is the result I get)
Expected output [0, 1]

Please help me to find the problem and points that can be improved in my code.

  • Provide a sample input, the expected result and the actual result. "doesn't work" is not enough information. – Michael May 09 '22 at 12:00
  • `Arrays.asList(newArray)` will result in a `List`, while you seem to think it results in a `List` (which is not possible in Java) or a `List`. – Mark Rotteveel May 09 '22 at 12:08

0 Answers0