首页 > 其他 > 详细

Search Insert Position(Easy,二分搜索)

时间:2015-09-09 16:19:00      阅读:197      评论: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.

 

样例:

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

时间复杂度:

O(log(n))

Code:

 1     int searchInsert(vector<int> &A, int target) {
 2         // write your code here
 3         long long first = 0;
 4         long long nums = A.size();
 5         long long last = nums - 1;
 6         long long mid;
 7         while(first <= last){
 8             mid = first + ((last - first + 1)>>1);
 9             if(A[mid] == target) return mid;
10             else if((first == last) && (A[mid] > target)) // 如果没有找到,目标较小,插在mid上
11                 return mid;
12             else if((first == last) && (A[mid] < target))
13                 return mid +1;  // 如果没有找到,目标较大,插在mid+1上
14             else if(A[mid] > target) last = mid -1;
15             else first = mid + 1;
16         }
17     }

 

Search Insert Position(Easy,二分搜索)

原文:http://www.cnblogs.com/ljminseu/p/4794856.html

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