|
| 1 | +# 毎日一题 - 744. find smallest letter greater than target |
| 2 | + |
| 3 | +## 信息卡片 |
| 4 | +* 时间:2019-06-17 |
| 5 | +* 题目链接:https://leetcode.com/problems/find-smallest-letter-greater-than-target/ |
| 6 | +* tag:`Array` |
| 7 | + |
| 8 | +## 题目描述 |
| 9 | +``` |
| 10 | +Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target. |
| 11 | +
|
| 12 | +Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'. |
| 13 | +
|
| 14 | +Examples: |
| 15 | + Input: |
| 16 | + letters = ["c", "f", "j"] |
| 17 | + target = "a" |
| 18 | + Output: "c" |
| 19 | +
|
| 20 | + Input: |
| 21 | + letters = ["c", "f", "j"] |
| 22 | + target = "c" |
| 23 | + Output: "f" |
| 24 | +
|
| 25 | + Input: |
| 26 | + letters = ["c", "f", "j"] |
| 27 | + target = "d" |
| 28 | + Output: "f" |
| 29 | +
|
| 30 | + Input: |
| 31 | + letters = ["c", "f", "j"] |
| 32 | + target = "g" |
| 33 | + Output: "j" |
| 34 | +
|
| 35 | + Input: |
| 36 | + letters = ["c", "f", "j"] |
| 37 | + target = "j" |
| 38 | + Output: "c" |
| 39 | +
|
| 40 | + Input: |
| 41 | + letters = ["c", "f", "j"] |
| 42 | + target = "k" |
| 43 | + Output: "c" |
| 44 | +Note: |
| 45 | + letters has a length in range [2, 10000]. |
| 46 | + letters consists of lowercase letters, and contains at least 2 unique letters. |
| 47 | + target is a lowercase letter. |
| 48 | +``` |
| 49 | + |
| 50 | +## 思路 |
| 51 | +二分查找,提高速度 |
| 52 | +要求是查找某一个元素,又是在有序的集合中。 |
| 53 | +所以我们可以用二分查找 |
| 54 | +1. 排除两种情况;target 小于首元素|| target 大于等于尾元素 => 目标都是首元素 |
| 55 | +2. 当target>=letters[mid] 时(我们要的值一定在右边),调整左区间 min = mid+1; |
| 56 | +3. 当target< letters[mid] 时,调整右区间 max = mid-1; |
| 57 | +4. 循环终止条件是 min > max; 最终返回min位置元素 |
| 58 | + |
| 59 | +## 建议 |
| 60 | +在leetcode上找一个数组稍微长一点的测试用例,在纸上画出整个过程;对理解很有帮助 |
| 61 | + |
| 62 | +## 参考答案 |
| 63 | +```js |
| 64 | +/** |
| 65 | + * @param {character[]} letters |
| 66 | + * @param {character} target |
| 67 | + * @return {character} |
| 68 | + */ |
| 69 | +var nextGreatestLetter = function(letters, target) { |
| 70 | + const length = letters.length |
| 71 | + let min = 0; |
| 72 | + let max = length - 1; |
| 73 | + if(target >= letters[length-1] || target < letters[0]) return letters[0]; |
| 74 | + while(min <= max) { |
| 75 | + const mid = (max+min) >> 1 |
| 76 | + if(target >= letters[mid]) { |
| 77 | + min = mid + 1; |
| 78 | + } else { |
| 79 | + max = mid - 1; |
| 80 | + } |
| 81 | + } |
| 82 | + return letters[min] |
| 83 | +}; |
| 84 | +``` |
0 commit comments