• 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
  • 相关阅读:
    request库下载
    tomcat启动正常,但是访问项目时,404. Eclipse没有正确部署工程项目
    Tomcat端口被占用
    administrator账户权限如何开启和关闭
    团队作业2 需求分析与原型设计
    矩阵快速幂
    散列函数的应用及其安全性
    递归实例
    芯片测试
    优先队列小知识
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3474919.html
Copyright © 2020-2023  润新知