Search Insert Position
2015-07-24 10:38
162 查看
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.
Analyse: Binary search. Whenever meeting a number, compare the pre/next number with the target.
Runtime: 8ms.
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
Analyse: Binary search. Whenever meeting a number, compare the pre/next number with the target.
Runtime: 8ms.
class Solution { public: int searchInsert(vector<int>& nums, int target) { int left = 0, right = nums.size() - 1; while(left <= right){ int mid = (left + right) / 2; if(nums[mid] < target){ if(mid == nums.size() - 1) return mid + 1; else{ if(nums[mid + 1] >= target) return mid + 1; } left = mid + 1; } else if(nums[mid] > target){ if(mid == 0) return mid; else{ if(nums[mid - 1] < target) return mid; } right = mid - 1; } else return mid; } } };
相关文章推荐
- mysql快速翻倍插入数据
- Fragment生命周期
- POJ 2993:Emag eht htiw Em Pleh
- Android Studio之gradle的配置与介绍
- oracle 数据库设计的一些原则
- RHEL5下编译2.6.26.5内核
- 类型引发的bug
- Android Studio之gradle的配置与介绍
- POJ 2993:Emag eht htiw Em Pleh
- IOS下横屏竖屏控制
- RAD Studio XE2 v16.0 ISO镜像文件下载 Update4 Hotfix 1(附破解) 百度云盘
- Java应用打包后运行需要注意编码问题
- 基于XMPP的即时通讯工具(一)
- Creo二次开发个人二维码上线了。
- C# 程序控制
- maven学习(一)--Hello World
- 天声人語 20150724
- hdu1151 air Raid(最小路径覆盖)
- Winform打包发布
- hdu 1272 小希的迷宫