Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
I am attempting a brute force approach for this problem--use an integer i to iterate through each element of the array and use another integer j to add non-identical indices to the integer at location i. I'm fairly sure my approach is correct, but I cannot get this java implementation correct.
class Solution {
public int[] twoSum(int[] nums, int target) {
int sum;
int[] Solution = new int[2];
outerloop:
for (int i=0; i<nums.length; i++) {
for (int j=0; j<nums.length; j++) {
if (i == j) {
j = j++;
sum = nums[i] + nums[j];
if (sum == target) {
System.out.println(sum);
Solution[0] = i;
Solution[1] = j;
break outerloop;
}
}
else {
sum = nums[i] + nums[j];
if (sum == target) {
Solution[0] = i;
Solution[1] = j;
break outerloop;
}
}
}
}
return Solution;
}
}
So the above works when I compile and use the array: [2, 7, 11, 15] and target = 9. But when you try: [3, 2, 4] and target = 6, it incorrectly returns Solution = [0, 0].
I can't see what I'm doing wrong and I've looked at the solutions and what others have posted and I get it. But I'm trying to specifically find out what's wrong with the above code.
Any help would be appreciated.