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.
nums? It will change indices on values.