Binary35SearchInsertPosition

这个很简单的问题我做了很久, 因为想不清楚, 如果找不到target, 合适的位置应该return什么. 显而易见应该return比target小的哪个位置的下一个位置, 所以假设[1,3,5,7], 我们target = 2; 所以最后会比较1; 或者[0,1,3,5,7] 最后会比较3.

If nums[mid] == 1, the low will be mid + 1; if nums[mid] == 3, the high = mid - 1; But the low and high will keep moving until nums[low] = 3;

So, the terminate condition is low > high, not about finding the target or not. So, if nums[mid] > target, the high will keep be smaller, until the low = mid + 1 to make low > high. So we should always return the low, because low is always the higher one between low and high.

阅读更多

没有更多推荐了,返回首页