0

I tried return answer[] outside of the loop, but it only works when it was initialized before the loop. I am confused now, is that because it has to be declared before the loop to avoid it become the local variable? this is my code(if int[] inside of if-condition, it would not return)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] answer = 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){
                    //int[] answer = new int[2];
                    answer[0] = i;
                    answer[1] = j;
                }
            }
        }
        return answer;
    }
}
1
  • 1
    First decide on answers to these two questions: 1) What should be returned if the if statement is never true? 2) What should be returned if the if statement is true more than once? Commented Mar 30, 2020 at 1:05

2 Answers 2

0

The local may never get executed within the loop. Even without the if, the loops may execute zero times.

Furthermore, the rules for definite assignment are quite long - check the JLS. Any further complications would not be welcome.

If answer was a field, then it would be implicitly initialised to null and may, therefore, cause NullPointerExceptions unless you are careful.

Sign up to request clarification or add additional context in comments.

2 Comments

throw new IllegalArgumentException("ERROR"); If I add this in the end. Will it help?
You need to definitely exit as there is a return value. So yeah, if you put the return inside (to return on first match instead of last) then throwing an exception at the end should work.
0

You really need to define what the answers to these two questions are:

  1. What should be returned if the if statement is never true?
  2. What should be returned if the if statement is true more than once?

Assuming the answer to the first is "null", and the answer to the second is "first match", then you'd write the code like this:

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length - 1; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                return new int[] { i, j }; // returning first match immediately
            }
        }
    }
    return null; // answer to first question here
}

1 Comment

@xyz666999 Welcome to StackOverflow. You should click the up-arrow of any/all answers you find useful. If your question has been answered to your satisfaction, click the check mark next to the best answer to accept it, so other than see that the question has been resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.