leetcode 374 猜数字游戏
思路:二分查找。
1 public class Solution extends GuessGame { 2 public int guessNumber(int n) { 3 int low = 1, high = n; 4 while (low <= high) { 5 //int mid = (low + high) / 2; 6 int mid = low + (high - low) / 2; 7 switch (guess(mid)) { 8 case 1: low = mid + 1; break; 9 case -1: high = mid - 1; break; 10 case 0: return mid; 11 } 12 } 13 return -1; 14 } 15 }
需要注意的一个地方:
1. mid的写法。如果按照旧的写法,low + high有可能溢出(虽然可以用long解决)。这里学习到了mid的新写法:
mid = low + (high - low) / 2; 两种写法效果一样。以后就按新的来写了。