[Swift]LeetCode374. 猜數字大小 | Guess Number Higher or Lower
阿新 • • 發佈:2018-10-11
fine ESS tel eth def forward efi res @param
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:
n = 10, I pick 6. Return 6.
我們正在玩一個猜數字遊戲。 遊戲規則如下:
我從 1 到 n 選擇一個數字。 你需要猜我選擇了哪個數字。
每次你猜錯了,我會告訴你這個數字是大了還是小了。
你調用一個預先定義好的接口 guess(int num)
,它會返回 3 個可能的結果(-1
,1
或 0
):
-1 : 我的數字比較小 1 : 我的數字比較大 0 : 恭喜!你猜對了!
示例 :
輸入: n = 10, pick = 6 輸出: 6
8ms
1 class Solution { 2 func guessNumber(_ n: Int, _ pick: Int) -> Int { 3 if pick == 0 || pick == n {return n} 4 var left:Int = 1 5 var right:Int = n 6 var mid:Int = 0 7 while(left < right) 8 {9 var mid = left + (right - left)/2 10 if pick == mid 11 { 12 return mid 13 } 14 else if pick < mid 15 { 16 right = mid 17 } 18 else 19 { 20 left = mid 21 } 22 } 23 return mid 24 } 25 }
C++版本:
1 // Forward declaration of guess API. 2 // @param num, your guess 3 // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 int guess(int num); 5 6 class Solution { 7 public: 8 int guessNumber(int n) { 9 int low=1; 10 while(low<=n){ 11 int mid=low+(n-low)/2; 12 int res=guess(mid); 13 if(res==0) return mid; 14 else if(res==-1) n=mid-1; 15 else low=mid+1; 16 } 17 return -1; 18 } 19 };
[Swift]LeetCode374. 猜數字大小 | Guess Number Higher or Lower