I have this piece of code:
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0;i<nums.length;i++){
int n = target - nums[i];
int temp = nums[i];
nums[i] = Integer.MIN_VALUE;
System.out.println("nums: "+ Arrays.toString(nums));
System.out.println("n: "+n);
int result = Arrays.binarySearch(nums,n);
System.out.println("result: "+result);
if (result >= 0){
int[] out = new int[2];
out[0] = i;
out[1] = result;
return out;
}
nums[i] = temp;
}
return null;
}
}
Where
int[] nums = {0,3,-3,4,-1};
int target = -1;
The code is supposed to give the output [0,4], but is returning null;
The console output is :
nums: [-2147483648, 3, -3, 4, -1]
n: -1
result: -4
nums: [0, -2147483648, -3, 4, -1]
n: -4
result: -1
nums: [0, 3, -2147483648, 4, -1]
n: 2
result: -4
nums: [0, 3, -3, -2147483648, -1]
n: -5
result: -1
nums: [0, 3, -3, 4, -2147483648]
n: 0
result: -4
Why is Arrays.binarySearch() not finding the position of -1?, is it some kind of bug or am I missing something?
>Solution :
From the Javadoc
public static int binarySearch(int[] a, int key)Searches the
specified array of ints for the specified value using the binary
search algorithm. The array must be sorted (as by thesort(int[])
method) prior to making this call. If it is not sorted, the results
are undefined. If the array contains multiple elements with the
specified value, there is no guarantee which one will be found.
It looks to me like your initial array is not already sorted. That means a binary search won’t help you – the best you can do is check every element of the array in turn.