首页 > 其他 > 详细

Leetcode#35 Search Insert Position

时间:2015-01-28 12:57:23      阅读:102      评论:0      收藏:0      [点我收藏+]

原题地址

 

二分搜索变种,注意到当左指针和右指针相交后,应该插入的位置总是在左指针处,所以直接返回左指针即可。

 

代码:

 1 int searchInsert(int A[], int n, int target) {
 2         int l = 0;
 3         int r = n - 1;
 4         
 5         while (l <= r) {
 6             int m = (l + r) / 2;
 7             if (A[m] == target)
 8                 return m;
 9             else if (A[m] < target)
10                 l = m + 1;
11             else
12                 r = m - 1;
13         }
14         
15         return l;
16 }

 

Leetcode#35 Search Insert Position

原文:http://www.cnblogs.com/boring09/p/4255478.html

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