Search code examples
javaarraysalgorithmtestcase

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target


I was working on TwoSum problem of LeetCode Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Test Case:

[2,7,11,15] 9

[3,2,4] 6

[3,3] 6

MY Code:

import java.util.Arrays;
class Solution {
    public int[] twoSum(int[] nums, int target) {
       Arrays.sort(nums);
        int left = 0;
        int right = nums.length-1;
        for(int i : nums){
            int sum = nums[left]+nums[right];
            if(sum == target)
                return new int[]{left+1,right};
            else if(sum > target)
                right--;
            else
                left++;
        }
        return new int[]{0,0};
    }
}

this code is passing for all the test cases except 2nd test case [2,3,4] 6 and no matter what i done it is not resolving so please someone help me with this.


Solution

  • I think you can solve it in a better way.

    My solution states that first pick the 0th element of the list; Then in a nested loop check it with the 1st, 2nd, ..., nth element of the list to see if their sum is equal to the target. If it is then return the result if not repeat the loop.

    For example in [3,2,4] 6 test case:

    1. Pick 3 and go to nested loop.
    2. Pick 2, is 3 + 2 equal to 6? No, then continue.
    3. Pick 4, is 3 + 4 equal to 6? No, then exit from nested loop.
    4. Now pick 2 and go to nested loop.
    5. Pick 4, is 2 + 4 equal to 6? Yes, You find the answer:)
    public class Solution {
        
        public static void main(String[] args) {
            int[] nums = {3, 2, 4};
            int target = 6;
            int[] result = twoSum(nums, target);
            System.out.println(result[0] + ", " + result[1]);
        }
        
        public static int[] twoSum(int[] nums, int target) {
            for(int i = 0; i < nums.length; i++) {
                for(int j = i + 1; j < nums.length; j++) {
                    if(nums[i] + nums[j] == target)
                        return new int[]{i, j};
                }
            }
            return new int[]{-1, -1};
        }
    
    }