35. Search Insert Position
2016-02-29 09:50
465 查看
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.
solution:
运行速度:快
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
solution:
class Solution { public: int searchInsert(vector<int>& nums, int target) { int left = 0; int right = nums.size()-1; if(nums[right] == target) return right; if(nums[right] < target) return right+1; if(nums[left] >= target) return left; while(left < right){ int mid = left + (right-left)/2; if(nums[mid] == target) return mid; else if(nums[mid]<target){ left = mid + 1; } else right = mid - 1; } if(nums[left] < target) return left+1; else return left; } };心得:二分搜索
运行速度:快
相关文章推荐
- vs中出现 找不到 .manifest 文件的错误解决方法
- 简陋的斗地主,js实现
- PL/SQL产生XML的encoding的值
- Android开发实用网站收藏
- linux下查看显卡信息
- 单链表的逆置-C++实现
- Playframework2.4 学习
- App Store审核被拒的各种原因
- Android学习笔记:关于Handler的详解(二)
- 安装 Apache 出现 <OS 10013> 以一种访问权限不允许的方式做了一个访问套接字的尝试
- Android View 事件分发机制 源码解析 (上)
- 算法代码实现之Union-Find,C++实现,quick-find、quick-union、加权quick-union(附带路径压缩优化)
- Tomcat可以在eclipse里启动,可是不能訪问首页的问题
- 在winform下实现左右布局多窗口界面的方法
- android6.0 权限管理
- Oracle中的自治事务(二)
- android开发游记:百度地图SDK基础地图的使用
- 论文的写作规范
- windows安装Apache HTTP服务器报错:无法启动,因为应用程序的并行配置不正确
- HashMap的简单使用教程