力扣刷题刷到简单二分查找时,一运行代码就提示超时,怎么就超时了?反反复复几次,发现
(right-left)>>1+left这一步需要在移位运算部分加括号,查了一下,基础中的基础是:移位运算优先级低于“+-*/”
我要裂开了……真的好基础!!!
int searchInsert(int* nums, int numsSize, int target) {
int left = 0, right = numsSize - 1, res = numsSize;
while (left <= right) {
int mid = ((right - left) >> 1) + left; // 移位运算的优先级小于“+-*/”
if (target <= nums[mid]) {
right = mid - 1;
res = mid;
} else {
left = mid + 1;
}
}
return res;
}