# Two Sum Java

• I am using the below code. Getting an error at
Line 11: java.lang.ArrayIndexOutOfBoundsException: 3

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

``````    int length= nums.length;
int result[]=new int[2];

for(int i=0;i<=length;i++)
{
for(int j=1;j<=length;j++)
{
if (nums[i]+nums[j]==target)
{
result[0]=i;
result[1]=j;
}

}
}
return result;

}
``````

}'''

• Try change the loop condition to

``````i < length
``````

Array index starts at 0 in Java. So the valid indices of an array of length n are

0, 1, 2, ..., n-1

The index of last element in the array is n-1. In your code, it is length-1. So you should check with

``````i < length
``````

• Another problem with the code is that when you check whether 2 elements sum is target, you should make sure these 2 elements are 2 different elements. Use the logic like this:

``````    if (nums[i]+nums[j]==target && i != j)
{
result[0]=i;
result[1]=j;
}
``````

Try test case [1, 3, 6, 4, 9] and target 8.

• try this

'''for(int i=0;i<length;i++)
{
for(int j=1;j<length;j++)
{
if (nums[i]+nums[j]==target)
{
result[0]=j;
result[1]=i;
}'''

• @zhuqing662k
i think the better way is that i is from 0 to length-2 and j is from i+1 to length-1, so my code is that:

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
result[0]=i;
result[1]=j;
}
}
}
return result;
}
//test
public static void main(String[] args){
Solution sln = new Solution();
int[] nums = {3,2,4};
int target = 6;
int[] result = sln.twoSum(nums,target);
System.out.println("["+result[0]+","+result[1]+"]");

``````}
``````

}

• This post is deleted!

• public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i=0; i< nums.length-1; i++){
for (int j=i+1; j<nums.length; j++){
if(nums[i]+nums[j] == target){
result[0] = i;
result[1] = j;
}
}
}
System.out.println("["+result[0]+","+result[1]+"]");
return result;
}
public static void main(String[] args){
Solution sln = new Solution();
int[] numArray = {3,2,4};
int sum = 6;
sln.twoSum(numArray, sum);
}
}

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