0

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.

K.Doe
  • 39
  • 1
  • 9
  • this question is not a good fit for StackOverlow. Maybe the codereview exchange would be a better fit!? – Daij-Djan Oct 20 '19 at 18:30

2 Answers2

0

In above brute force method i==j is not correct solution as two elements of array must be different. i should go from 0 to nums.length and j from i+1 to nums.length.

Abhishek
  • 1
  • 1
  • Yes, I understood that from the solutions and I get why that works. But, wouldn't the first if-statement that I included take care of any repeat elements indices? – K.Doe Oct 20 '19 at 19:03
  • Problem is with j=j++ as explained by Mr. Arvind. Please follow the link in his comment for more explanation. – Abhishek Oct 22 '19 at 07:26
  • @K.Doe - If one of the answers resolved your issue, you can help the community by marking it as accepted. An accepted answer helps future visitors use the solution confidently. – Arvind Kumar Avinash May 29 '20 at 20:31
0

Technically your problem is here j = j++; you need to make it like j = ++j;. See here.

muaz
  • 550
  • 9
  • 15