2024每日刷题(202)
Leetcode—374. 猜数字大小
C++实现代码
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is higher than the picked number
* 1 if num is lower than the picked number
* otherwise return 0
* int guess(int num);
*/
class Solution {
public:
int guessNumber(int n) {
int l = 1;
int r = n;
// [1, n]
while(l <= r) {
int pick = l + (r - l) / 2;
if(guess(pick) < 0) {
r = pick - 1;
} else if(guess(pick) == 0) {
return pick;
} else {
l = pick + 1;
}
}
return l;
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!