[LeetCode-35] Search Insert Position(二分法)
来源:互联网 发布:清代档案文献数据库 编辑:程序博客网 时间:2024/06/03 17:29
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
这个和http://blog.csdn.net/xy010902100449/article/details/48806571差不多类似,采用二分法查找即可。
int searchInsert(int* nums, int numsSize, int target){if(numsSize <= 0)return 0;int low = 0;int high = numsSize-1;int mid;int flag = 0;/*1.判断数组是增序还是降序*/if(nums[0] < nums[numsSize-1]) {flag = 1;}else if(nums[0] == nums[numsSize-1]) {if(target <= nums[0])return 0; elsereturn numsSize;}else {flag = 0;}/*2.二分法查找插入的位置*/if(flag) {while(low <= high) {mid = low+(high-low)/2;if(target < nums[mid]) { high = mid-1;}else if(target == nums[mid]) {return mid;}else {low = mid + 1;}}}else {while(low <= high) {mid = low+(high-low)/2;if(target < nums[mid]) { low = mid + 1;}else if(target == nums[mid]) {return mid;}else {high = mid - 1;}}}return low; }
0 0
- [LeetCode-35] Search Insert Position(二分法)
- LeetCode 35 Search Insert Position 二分法处理
- LeetCode-35-Search Insert Position(二分法)-Medium
- 【二分法】LeetCode-Search Insert Position
- LeetCode(35) Search Insert Position
- LeetCode (35)Search Insert Position
- leetcode 35: Search Insert Position
- Leetcode(35) Search Insert Position
- [leetcode 35] Search Insert Position
- [Leetcode] 35 - Search Insert Position
- LeetCode 35 Search Insert Position
- leetcode-35 Search Insert Position
- LeetCode 35 Search Insert Position
- Leetcode 35 Search Insert Position
- Leetcode[35]-Search Insert Position
- LeetCode 35:Search Insert Position
- leetcode-35-Search Insert Position
- leetcode 35 -- Search Insert Position
- LNMP系列——php编程建议规范
- 图像拼接 SIFT资料合集
- struts.xml配置文件(二)
- 定制自己的SolrRequestHandler
- cf581d
- [LeetCode-35] Search Insert Position(二分法)
- ZOJ2562 More Divisors
- eclipse中导入项目出现小红叉却找不到错误之处的解决办法
- LeetCode题解——Implement Queue using Stacks
- Stack Overflow 最流行的编程语言和标签
- Android读取SD卡.TXT文本内容
- IOS 绘图坐标系颠倒问题
- PHP编程效率的20个要点
- json转xml