Leetcode分类解析:二分查找1.原始二分查找1.1 典型例题35-Search Insert Position (Medium): Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array.Here are few examples.[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7 → 4[1,3,5,6], 0 → 0首先来看一道最经典的二分查找题,考察的就是二分查找的原始实现。因为这道题比较经典,所以下面源码做了大量注释。说是注释,其实是断言,用来在后面说明这段代码的正确性。特别注意一点,就是那个看似奇怪的mid计算方式,为什么不是(low+high)/2呢?做了很久Leetcode我都没注意到,看到有些答案这样写的还以为是多此一举,直到做到某一道题发生溢出,真是井底之蛙!这样写就是因为当low和high特别大时相加会发生Integer溢出,要么都转成long做完运算再转回来,但是下面这种写法更加方便,
...
继续阅读
(120)