C++

【二分查找】35. 搜索插入位置


利用二分查找算法C++短路求值特性

平台AC代码:

 1 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4         int lo = 0, hi = nums.size();
 5         while (lo < hi){
 6             int mi = lo + ((hi - lo) >> 1);
 7             (target < nums[mi]) ? hi = mi : lo = mi + 1;
 8         }
 9         int i = --lo;
10         if (i == -1 || nums[i] != target) i++;
11         return i;
12     }
13 };
View Code

C++自测代码:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int binarySearch(int* A, int e, int lo, int hi)
 6 {
 7     while (lo < hi){
 8         int mi = lo + ((hi - lo) >> 1);  //避免数据溢出
 9         (e < A[mi]) ? hi = mi : lo = mi + 1;
10     }
11     return --lo;
12 }
13 
14 int main()
15 {
16     int a[] = {1,3,5,6};
17     int target;
18     while(cin >> target){
19         int i = binarySearch(a, target, 0, 4);
20         if (i == -1 || a[i] != target) i++;  // 利用C++短路求值特性,避免数组越界情况。
21         cout << i << endl;
22     }
23     return 0;
24 }
View Code

 


作者:Shiningonmin,发布于:2019/05/15
原文:https://www.cnblogs.com/shiningonmin/p/10871114.html