35. Search Insert Position(python)

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.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4 :

 Input: [1,3,5,6], 0

 Output: 0

看到大神的解法后,真心觉得自己练的太少。这里采用折半查找(二分查找法)。这种查找方法大大减少了时间复杂度,时间复杂度为o(logn)。
仅适用于事先已经排好序的顺序表。其查找的基本思路:首先将给定值K,与表中中间位置元素的关键字比较,若相等,返回该元素的存储位置;
若不等,这所需查找的元素只能在中间数据以外的前半部分或后半部分中。然后在缩小的范围中继续进行同样的查找。如此反复直到找到为止。
二分查找特别适用于那种一经建立就很少改动、
而又经常需要查找的线性表。对那些查找少而又经常需要改动的线性表,可采用链表作存储结
构,进行顺序查找。链表上无法实现二分查找。







本题用的是for循环,时间复杂度为o(n),只要是根据题中输入的条件,然后用if - else 进行判断。












今天是第四天做题,第一次没有任何参考,把一道简单的题做出来。很开心,继续加油。
苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
原文地址:https://www.cnblogs.com/shaer/p/9630502.html