LeetCode35.Search Insert Position
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.
如题,直白的思路是,从头到尾挨着看一遍就好,如果有相等的就返回当前查看的位置,不然的话就看看是不是在合适的位置上,即前面的刚好比target小,后面的刚好比后面的大。
如果需要更快一点,可以考虑二分查找,也就是说从数组的中间开始查看,如果target比中间的数字大呢,就只看左边的部分,否则看中间的部分,无论是左边的还是右边的可以当作一个新的数组继续二分查找,需要注意的是保存只需查看的那部分的上下边界。这样的话时间性能是O(logN),第一种解法的性能是O(N)。
疑惑的是真实运行效果其实没有第一种好,可能是给的测试数据的问题。