LeetCode - 374. Guess Number Higher or Lower
2016-07-19 00:15
483 查看
这道题目并没有什么特别可说的地方,看到题目的描述就可以明白这是一个需要使用Binary Search解决的问题,所以直接使用Binary Search即可,代码如下:
思考:
1. 虽然这道题目非常简单,但并不是说没有需要注意的问题,比如这道题目中Binary Search的模版写法一开始竟然有些生疏了,好久写不出来,这个问题要引起重视,对于基础的算法和数据结构应该多加练习
2. 明白Binary Search的一个性质,就是如果while(left < right)使用这种写法,那么如果Binary Search找不到目标的话,最终的结果是left = right
3. 对于搜索,查找类型的问题,一定要有使用Binary Search的敏感度
/* 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 left = 1; int right = n; // Binary search while(left < right){ int mid = left + (right - left) / 2; if(guess(mid) == -1) right = mid - 1; // guess number is higher, move to right else if(guess(mid) == 1) left = mid + 1; // guess number is higher, move to left else return mid; // correct } return left; } }
思考:
1. 虽然这道题目非常简单,但并不是说没有需要注意的问题,比如这道题目中Binary Search的模版写法一开始竟然有些生疏了,好久写不出来,这个问题要引起重视,对于基础的算法和数据结构应该多加练习
2. 明白Binary Search的一个性质,就是如果while(left < right)使用这种写法,那么如果Binary Search找不到目标的话,最终的结果是left = right
3. 对于搜索,查找类型的问题,一定要有使用Binary Search的敏感度
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解