随笔- 509  文章- 0  评论- 151  阅读- 22万 

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\n", sol.searchInsert(A, n, target));
57     }
58 
59     return 0;
60 }
61 #endif
复制代码

 

 posted on   zhuli19901106  阅读(240)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示