参考LeetCode 35. Search Insert Position
class Solution { public: /** * 二分查找 * @param n int整型 数组长度 * @param v int整型 查找值 * @param a int整型vector 有序数组 * @return int整型 */ int upper_bound_(int n, int v, vector<int>& a) { // write code here int left = 0, right = n; while (left < right) { int mid = left + (right - left) / 2; if (a[mid] < v) left = mid + 1; else right = mid; } return right + 1; return n + 1; } };