0374. 猜数字大小 Guess Number Higher or Lower

问题描述

这个问题就是二分查找法的一个基本应用:

#![allow(unused)]
fn main() {
// Binary Search
unsafe fn guess_number(n: i32) -> i32 {
    assert!(n > 0);
    let mut left = 0;
    let mut right = n;
    while left <= right {
        let mid = left + (right - left) / 2;
        let pick = unsafe { guess(mid) };
        if pick == -1 {
            right = mid.saturating_sub(1);
        } else if pick == 1 {
            left = mid + 1;
        } else {
            return mid;
        }
    }
    0
}
}