Skip to content

Commit d60bd3f

Browse files
committed
Merge pull request #73 from wenalan/patch-2
added c++ code
2 parents 2002e35 + f89705c commit d60bd3f

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

zh-cn/binary_search/search_insert_position.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,33 @@ class Solution:
5959
return len(A)
6060
```
6161

62+
### C++
63+
```c++
64+
class Solution {
65+
/**
66+
* param A : an integer sorted array
67+
* param target : an integer to be inserted
68+
* return : an integer
69+
*/
70+
public:
71+
int searchInsert(vector<int> &A, int target) {
72+
// write your code here
73+
if (A.empty()) return 0;
74+
75+
int n = A.size();
76+
int lb = -1, ub = n;
77+
while (lb + 1 < ub) {
78+
int mid = lb + (ub - lb) / 2;
79+
if (A[mid] < target) {
80+
lb = mid;
81+
} else {
82+
ub = mid;
83+
}
84+
}
85+
return ub;
86+
}
87+
};
88+
```
6289
6390
### Java
6491
仍然是 [Binary Search](http://algorithm.yuanbin.me/zh-cn/basics_algorithm/binary_search.html) 中`lower_bound`的变形,两大关键点:`start` 和`end` 的初始化;最终插入位置和`start` 以及`end` 之间的关系,由于`start`对应的索引一定是小于目标值的,那么`start + 1` 就是要求的值了,再检查下两端的边界,DONE

0 commit comments

Comments
 (0)