We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent dbf19a9 commit 7bf67d8Copy full SHA for 7bf67d8
91/binary-search.md
@@ -157,10 +157,24 @@ function binarySearch(nums, target) {
157
158
##### C++
159
160
-暂时空缺,欢迎 [PR](https://github.com/leetcode-pp/leetcode-cheat/pulls)
161
-
162
```cpp
+int binarySearch(vector<int>& nums, int target){
+ if(nums.size() == 0)
163
+ return -1;
164
165
+ int left = 0, right = nums.size() - 1;
166
+ while(left <= right){
167
+ int mid = left + ((right - left) >> 1);
168
+ if(nums[mid] == target){ return mid; }
169
+ // 搜索区间变为 [mid+1, right]
170
+ else if(nums[mid] < target)
171
+ left = mid + 1;
172
+ // 搜索区间变为 [left, mid - 1]
173
+ else
174
+ right = mid - 1;
175
+ }
176
177
+}
178
```
179
180
### 寻找最左边的满足条件的值
0 commit comments