0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 374. Guess Number Higher or Lower

Posted at

374. Guess Number Higher or Lower

アプローチ

二分探索

O(log n)

/** 
 * 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);
 */

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int start = 1;
        int end = n;

        while(start <= end){
            int mid = start + (end- start) / 2;
            int check = guess(mid);
            if(check == 0){
                return mid;
            }else if(check == 1) {
                 start = mid + 1;
            }else{   
                 end = mid -1;
            }
        }
        return 0;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?