diff --git a/10 October LeetCode Challenge 2021/12_guessNumHighLow.java b/10 October LeetCode Challenge 2021/12_guessNumHighLow.java new file mode 100644 index 0000000..95e7f28 --- /dev/null +++ b/10 October LeetCode Challenge 2021/12_guessNumHighLow.java @@ -0,0 +1,30 @@ +/* The guess API is defined in the parent class GuessGame. + @param num, your guess + @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 + int guess(int num); */ + +public class Solution extends GuessGame { + public int guessNumber(int n) { + int low = 1; + int high = n; + while (low <= high) { + int mid1 = low + (high - low) / 3; + int mid2 = high - (high - low) / 3; + int res1 = guess(mid1); + int res2 = guess(mid2); + if (res1 == 0) + return mid1; + if (res2 == 0) + return mid2; + else if (res1 < 0) + high = mid1 - 1; + else if (res2 > 0) + low = mid2 + 1; + else { + low = mid1 + 1; + high = mid2 - 1; + } + } + return -1; + } +}