Skip to content

744.find-smallest-letter-greater-than-target(date 2019-06-17) #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jul 26, 2019
84 changes: 84 additions & 0 deletions daily/2019-06-17.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# 毎日一题 - 744. find smallest letter greater than target

## 信息卡片
* 时间:2019-06-17
* 题目链接:https://leetcode.com/problems/find-smallest-letter-greater-than-target/
* tag:`Array`

## 题目描述
```
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.

Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.

Examples:
Input:
letters = ["c", "f", "j"]
target = "a"
Output: "c"

Input:
letters = ["c", "f", "j"]
target = "c"
Output: "f"

Input:
letters = ["c", "f", "j"]
target = "d"
Output: "f"

Input:
letters = ["c", "f", "j"]
target = "g"
Output: "j"

Input:
letters = ["c", "f", "j"]
target = "j"
Output: "c"

Input:
letters = ["c", "f", "j"]
target = "k"
Output: "c"
Note:
letters has a length in range [2, 10000].
letters consists of lowercase letters, and contains at least 2 unique letters.
target is a lowercase letter.
```

## 思路
二分查找,提高速度
要求是查找某一个元素,又是在有序的集合中。
所以我们可以用二分查找
1. 排除两种情况;target 小于首元素|| target 大于等于尾元素 => 目标都是首元素
2. 当target>=letters[mid] 时(我们要的值一定在右边),调整左区间 min = mid+1;
3. 当target< letters[mid] 时,调整右区间 max = mid-1;
4. 循环终止条件是 min > max; 最终返回min位置元素

## 建议
在leetcode上找一个数组稍微长一点的测试用例,在纸上画出整个过程;对理解很有帮助

## 参考答案
```js
/**
* @param {character[]} letters
* @param {character} target
* @return {character}
*/
var nextGreatestLetter = function(letters, target) {
const length = letters.length
let min = 0;
let max = length - 1;
if(target >= letters[length-1] || target < letters[0]) return letters[0];
while(min <= max) {
const mid = (max+min) >> 1
if(target >= letters[mid]) {
min = mid + 1;
} else {
max = mid - 1;
}
}
return letters[min]
};
```
7 changes: 6 additions & 1 deletion daily/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ tag: `tree`

时间: 2019-06-14

### [744.find-smallest-letter-greater-than-target](./2019-06-17.md)

tag:`Array` `binary search`

时间:2019-06-17

### [letter-combinations-of-a-phone-number](./2019-06-18.md)

tag: `backtrack`
Expand All @@ -78,7 +84,6 @@ tag:`Array`

时间:2019-06-20


### [nth-highest-salary](./2019-06-21.md)

tag: `sql`
Expand Down