[LeetCode]Search Insert Position
2015-08-08 22:00
309 查看
题目
Number: 35Difficulty: Medium
Tags: Array, Binary Search
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.
[code][1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0
题解
在有序数组寻找目标值,找到则返回下标,否则返回应当插入的位置。典型的二分搜索题。二分查找关键在于边界的确定。
代码
[code]int searchInsert(vector<int>& nums, int target) { if(nums.empty()) return 0; int l = 0, h = nums.size() - 1; while(l <= h) { int mid = l + ((h - l) >> 1); if(nums[mid] == target) return mid; else if(nums[mid] < target) l = mid + 1; else h = mid - 1; } return l; }
相关文章推荐
- 命运赋-吕蒙正
- 什么是面向对象的程序设计语言?
- Hive0.14在left outer join多级连接中,执行计划生成BUG记录
- Surrounded Regions
- [LeetCode]Search for a Range
- 《机器学习》(Machine Learning)——Andrew Ng 斯坦福大学公开课学习笔记(三)
- Mac OS 安装Wget
- 重复操作放到循环中效率低
- DataNode上执行文件读写时报java.io.IOException: Bad connect ack with firstBadLink as 192.168.X.X错误解决记录
- HTML基础(一)
- 排序算法的C语言实现-希尔排序
- 屡战屡败,屡败屡战
- [LeetCode]Next Permutation
- 通过jacob操作office
- 2015第32周六
- JAVA学习篇--JSTL基金会
- 字符编码详解
- Hdfs本地短路读取文件
- 华为OJ(学英语)
- Hibernate 性能优化及缓存的使用