Leetcode Note: Go - Guess Number Higher or Lower
Guess Number Higher or Lower - LeetCode
https://leetcode.com/problems/guess-number-higher-or-lower/
- Go 言語で取り組んだメモ
所感
- 与えられた数値と、数値を推測する guess 関数を使って Higher or Lower 情報をベースとして具体的な数値を求めて return する
- 愚直にループする方法もあるがバイナリサーチが無難そう
回答
Guess Number Higher or Lower - LeetCode
https://leetcode.com/problems/guess-number-higher-or-lower/solution/
/**
* 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
* func guess(num int) int;
*/
func guessNumber(n int) int {
low := 0
high := n
for low <= high {
mid := low + (high - low) / 2
res := guess(mid)
if res == 0 {
return mid
} else if res < 0 {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
ぶなん