Two Sum....Java Code


  • 0
    S

    I am getting java.lang.ArrayIndexOutOfBoundsException: 5 on line 18 for my code for the below input . Please help to suggest whats wrong in my code.
    [-1,-2,-3,-4,-5]
    -8
    ...
    public class Solution {

    public static void main(String args[])
    {
    int[] returnArray=new int[2];
    int[] nums={2, 7, 11, 15};
    int target=9;
    returnArray=twoSum(nums,target);
    System.out.println(returnArray[0] + returnArray[1]);

    }
    public static int[] twoSum(int[] nums, int target) {
          int[] returnArray=new int[2];
        outerloop:
        for(int i=0;i<nums.length-1;i++)
        {
            for(int k=1;k<nums.length;k++)
            if(nums[i]+nums[i+k]==target)
            {
                returnArray[0]=i;
                returnArray[1]=i+k;
                break outerloop;
            }
        }
        return returnArray;
    }
    

    }

    ...


  • 0
    P

    Hi Shravan, You are getting the exception because when i will reach towards end, i+k will be out of the size of array, simply replace the condition in inner loop by i+k<nums.length instead of k<nums.length.
    Refer below,

    public int[] twoSum(int[] nums, int target) {
            int[] returnArray=new int[2];
            outerloop:
            for(int i=0;i<nums.length-1;i++)
            {
                for(int k=1;i+k<nums.length;k++)
                if(nums[i]+nums[i+k]==target)
                {
                    returnArray[0]=i;
                    returnArray[1]=i+k;
                    break outerloop;
                }
            }
            return returnArray;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.