LeetCode

Search Insert Position

2013.12.15 00:03

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

Solution:

  See the STL reference for functions lower_bound() and upper_bound() in <algorithm>.

  Obviously it's binary search.

  Time complexity is O(log(n)), space complexity is O(1).

Accepted code:

 1 //#define __MAIN__
 2 #define _CRT_SECURE_NO_WARNINGS
 3 #include <cstdio>
 4 #include <cstdlib>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     int searchInsert(int A[], int n, int target) {
10         // Note: The Solution object is instantiated only once and is reused by each test case.
11         if(n <= 0){
12             return 0;
13         }
14 
15         if(target < A[0]){
16             return 0;
17         }
18 
19         if(target > A[n - 1]){
20             return n;
21         }
22 
23         int ll, mm, rr;
24         ll = 0;
25         rr = n - 1;
26         while(true){
27             if(rr - ll <= 1){
28                 if(target == A[ll]){
29                     return ll;
30                 }else{
31                     return rr;
32                 }
33             }
34             mm = (ll + rr) / 2;
35             if(target < A[mm]){
36                 rr = mm;
37             }else if(target > A[mm]){
38                 ll = mm;
39             }else{
40                 return mm;
41             }
42         }
43         return rr;
44     }
45 };
46 
47 #ifdef __MAIN__
48 int main()
49 {
50     Solution sol;
51     int A[] = {1, 3, 5, 6};
52     const int n = sizeof(A) / sizeof(int);
53     int target;
54 
55     while(scanf("%d", &target) == 1){
56         printf("%d
", sol.searchInsert(A, n, target));
57     }
58 
59     return 0;
60 }
61 #endif
原文地址:https://www.cnblogs.com/zhuli19901106/p/3474919.html