オットセイの経営日誌

データサイエンス系ベンチャーを経営してます。経営のこと、趣味のことつぶやきます。

LeetCode / Guess Number Higher or Lower

今年も残すところ後1週間程度ですね。

ここ数ヶ月は怒涛のように過ぎ去り、ちょっと自分の人としての器を超えた容量が押し寄せている感じで、リハビリの必要性を感じてます。

ということで、リハビリがてらプレーンな二分探索問題を解きます。

https://leetcode.com/problems/guess-number-higher-or-lower/

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example :

Input: n = 10, pick = 6
Output: 6

解答・解説

解法1

過去記事でも取り扱った二分探索で解きます。

# The guess API is already defined for you.
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        low = 1
        high = n
        while low <= high:
            mid = (low+high)//2
            if guess(mid) == 0:
                return mid
            elif guess(mid) == 1:
                low = mid+1
            else:
                high = mid-1