首页 > 其他 > 详细

[Leetcode] search insert position 寻找插入位置

时间:2017-07-11 15:25:42      阅读:272      评论:0      收藏:0      [点我收藏+]

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

题意:在已排序的数组中查找给定数字,若有,返回下标,没有,则返回插入位置

思路:题意的要求应该理解成,应该返回的是第一个不小于目标值的下标。所以用二分查找即可。详情可见我之前的博客关于二分查找的总结。代码如下:

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) 
 4     {
 5         int lo=0,hi=n;
 6         while(lo<hi)
 7         {
 8             int mid=lo+((hi-lo)>>1);
 9             if(A[mid]<target)
10                 lo=mid+1;
11             else
12                 hi=mid;
13         }   
14         return hi;
15     }
16 };

 

[Leetcode] search insert position 寻找插入位置

原文:http://www.cnblogs.com/love-yh/p/7150593.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!