Leetcode_num12_Search Insert Position
来源:互联网 发布:js css压缩工具推荐 编辑:程序博客网 时间:2024/06/13 06:52
题目:
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
0 0
- Leetcode_num12_Search Insert Position
- LeetCode: Search Insert Position
- Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode34:Search Insert Position
- Search Insert Position
- [35]Search Insert Position
- Search Insert Position
- Search Insert Position
- [LeetCode]Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- Search Insert Position
- CF -- 468B Two Set (2-SAT)
- Robotium 5.0.1 源码解析之控件搜索
- 直接通过ADO操作Access数据库(修改版)
- Pattern正则
- js获取网页高度
- Leetcode_num12_Search Insert Position
- PHP采集 抓取
- Linux系统之工具篇(一)DRBD Centos6.5(64bit)编译安装,双主模式
- MySQL 按指定字段自定义列表排序
- 开源数据库 DBCP与C3P0
- $.ajax 和 jquery.form.js实现表单异步提交
- 数据挖掘模型生命周期管理
- php实现翻版抽奖
- HTML中常用转义字符