[leetcode] Search Insert Position
2015-07-01 21:51
501 查看
From : https://leetcode.com/problems/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.
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
class Solution { public: int searchInsert(vector<int>& nums, int target) { int len; if(!(len = nums.size()) || target <= nums[0]) return 0; if(target > nums[len-1]) return len; int start=0, mid, end=len-1; while(start <= end) { mid = (start + end) >> 1; if(nums[mid] == target) return mid; else if(mid == start || mid == end) { if(nums[start] == target) return start; return end; } else if(nums[mid] > target){ end = mid; } else { start = mid; } } return mid; } };
相关文章推荐
- 解决ngui挡住粒子的问题
- 在ubuntu下用apt-get安装和管理java
- DragonFlow导读(by quqi99)
- Complete The Pattern #1
- js正则表达式
- iOS UILabel多行时文字向下偏移
- 排序算法之直接选择排序Java版
- C++ Keywords: typedef
- 2015070101 - 霍去病
- [精华]Hadoop,HBase分布式集群和solr环境搭建
- 偶遇mysql外键不好使
- 匿名管道(pipe)
- opencv 拉伸、扭曲、旋转图像-透视变换
- ASM(三) 利用Method组件动态生成方法的字节码
- JVM StackMapTable 属性的作用及理解
- Java 并发包之线程池和原子计数
- Flex&iBatis&Hibernate&Spring—师徒奶茶系统V1总结
- websocket客户端
- hdu4521 小明系列的问题——小明序列(LIS变种 (段树+单点更新解决方案))
- Linux命令-终止进程命令:pkill