There are some things I do not understand in the coding world: Making assumptions like it's true. Let's see this solution to binary search.
The question is to find a target number in an array of numbers. If the target is not in the array, return -1. If it is, return the index of the target in the array.
This user's coding solution is brilliant
var search = function(nums, target) {
let lo = 0, hi = nums.length-1;
while (lo < hi) {
let mid = lo + Math.floor((hi-lo+1)/2);
if (target < nums[mid]) {
hi = mid - 1
} else {
lo = mid;
}
}
return nums[lo]==target?lo:-1;
};
The solver goes on further to explain (which I really appreciate by the way rather than simply writing down solution) the logic behind his choice of indexes of midpoint, low, and high.
But! That seemingly sound very mathematical or programmatic is actually not that rigorous because if you change lo+hi/2 to lo+hi+1/2 there won't be an overflow. So, there is nothing wrong with that certain operations.
This, I think is the problem in trying to understand every leetcode problem on the high level. You will not get things correct.
Beware folks! You never know what's true until you see and understand how it works.
Top comments (0)