也是binary search的應用題,承前兩篇文章,有lb跟ub和index三個數值可選,我目前覺得應該是回傳lower bound值。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int p = -1, f = 0;
int lb = 0, ub = nums.size() - 1;
while( ub >= lb ) {
int index = lb + (ub - lb) / 2;
if ( nums[index] < target )
lb = index + 1;
else if ( nums[index] > target )
ub = index - 1;
else {
f = 1;
p = index;
break;
}
//cout << "(" << lb << ", " << ub << "," << index << ")";
}
if ( !f )
p = lb;
return p;
}
};
解釋不清楚為什麼是回傳lb...