35. Search Insert Position **
2016-08-11 18:22
429 查看
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.
My code:
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums)-1
if nums[left]>=target:
return left
if nums[right]<target:
return right+1
mid = (left + right)/2
while left <right-1:
mid = (left+right)/2
if target==nums[mid]:
return mid
elif target<nums[mid]:
right =mid
else:
left = mid
return right
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
My code:
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums)-1
if nums[left]>=target:
return left
if nums[right]<target:
return right+1
mid = (left + right)/2
while left <right-1:
mid = (left+right)/2
if target==nums[mid]:
return mid
elif target<nums[mid]:
right =mid
else:
left = mid
return right
相关文章推荐
- MATLAB数学建模(6)-蒙特卡洛算法
- android中包的导入方法总结
- HDU 5512 Pagodas
- CENTOS 7.2 使用 RDO 安装 OPENSTACK
- JetBrains WebStorm 安装破解问题
- my97DatePicker日期控件——日期输入框联动,使用focus使第二个输入框没展示出日期控件
- 【python】lxml
- JZOJ.4678【NOIP2016提高A组8.11】 钱仓
- 重写、隐藏123
- 关于用Getline读取文件只能读取首行的问题
- 老司机教你怎么泡妹子(软件篇上)
- 注解用法详解——@SuppressWarnings
- 查找企业网中非法接入的WIFI设备(原创) 推荐
- 1005.Spell It Right (20)
- linux 基本操作:
- Spring Boot学习记录(二)--thymeleaf模板
- ng-class用法
- C++基础学习笔记 - 函数模板
- 打地鼠游戏
- 在iOS开发中使用正则表达式分解字符串