跳至主要內容

374. 猜数字大小

T4mako算法二分查找交互小于 1 分钟

374. 猜数字大小

简单

题目描述open in new window

解法思路:二分查找

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        long left = 1;
        long right = n;
        while(guess((int)((left + right)/2)) != 0){
            if(guess((int)((left + right)/2)) < 0) {
                right = (left + right)/2 - 1;
            }
            if(guess((int)((left + right)/2)) > 0) {
                left = (left + right)/2 + 1;
            }
        }
        return (int) ((left + right)/2);
    }
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5