LeetCode 35 - Search Insert Position
2016-03-01 15:51
441 查看
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.
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 { public: int searchInsert(vector<int>& nums, int target) { int size = nums.size(); int left_idx = 0; int right_idx = size - 1; int mid_idx, idx = -1; while (left_idx <= right_idx) { mid_idx = (left_idx + right_idx) / 2; if (nums[mid_idx] == target) return mid_idx; else if (nums[mid_idx] < target) { if (mid_idx == size - 1 || nums[mid_idx+1] > target) return mid_idx + 1; else left_idx = mid_idx + 1; } else { if (mid_idx == 0 || nums[mid_idx-1] < target) return mid_idx; else right_idx = mid_idx - 1; } } } };Runtime: 8 ms
相关文章推荐
- Atitit.linq java的原理与实现 解释器模式
- 若有以下定义,且0<=i<4,则不正确的赋值语句是 int b[4][6],*p,*q[4]; A q[i]=b[i]; B p=b; C p=b[i]; D q[i]=&b[0][0];
- 图片压缩时 某个 jpeg图片 报错 Unsupported Image Type
- HDOJ 1715 大菲波数
- unity 切圆角矩形 --shader编程
- jsonp使用,spring4.x对jsonp的支持
- Atitit.linq java的原理与实现 解释器模式
- Atitit.linq java的原理与实现 解释器模式
- HDOJ 1715 大菲波数
- LAMP中php配置
- 【最大流/费用流】BZOJ1834-[ZJOI2010]network 网络扩容
- SPRING IN ACTION 第4版笔记-第二章-002-@ComponentScan、@Autowired的用法
- 说下查询动作 Pivot
- iOS 新手指引在App中的添加,第一次启动应用程序出现,后面都不出现
- Android Paint和Color类学习
- Nginx简单配置
- Atitit.wrmi web rmi框架新特性
- js判断是移动端还是pc端
- C#中字符串前面加@的作用
- python引用非当前作用于变量时需使用关键字声明一下