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;
}
}
ifstatement is never true? 2) What should be returned if theifstatement is true more than once?