首页 > 代码库 > Leetcode_num12_Search Insert Position
Leetcode_num12_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.
比较直观的方法如下:class Solution: # @param A, a list of integers # @param target, an integer to be inserted # @return integer def searchInsert(self, A, target): rs=0 #结果 L=len(A) for i in range(L): if target<A[0]: rs=0 break elif target>A[L-1]: rs=L break elif target==A[i]: rs=i break elif target>A[i] and target<A[i+1]: rs=i+1 break return rs
但是该方法的复杂度为o(n)
复杂度为o(logn)的方法需要利用二分法
代码如下:
class Solution: # @param A, a list of integers # @param target, an integer to be inserted # @return integer def searchInsert(self, A, target): L=len(A) low=0 high=L-1 while(low<=high): mid=low+(high-low)/2 if target<A[mid]: high=mid-1 elif target>A[mid]: low=mid+1 else: return mid return low
Leetcode_num12_Search Insert Position
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。