码迷,mamicode.com
首页 > 其他好文 > 详细

Search Insert Position(Easy,二分搜索)

时间:2015-09-09 16:21:05      阅读:170      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!