744. Find Smallest Letter Greater Than Target

Posted real1587

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了744. Find Smallest Letter Greater Than Target相关的知识,希望对你有一定的参考价值。

Given a list of sorted characters letterscontaining 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:

  1. letters has a length in range [2, 10000].
  2. letters consists of lowercase letters, and contains at least 2 unique letters.
  3. target is a lowercase letter.

 

题目是变种版的二分查找,返回值字符数组的索引用取余搞定目标比所有字符大这个问题。
 1 char nextGreatestLetter(char* letters, int lettersSize, char target) {
 2         int low=0, high=lettersSize;
 3         while(low<high){
 4             int mid=low+(high-low)/2;
 5             if(letters[mid]>target)    high=mid;//如果比目标大,就往左边找
 6             else    low=mid+1;               //如果比目标小,就往右边推
 7         }
 8         /*l
 9         因为etters数组索引范围是0-lettersSize-1,当low大于lettersSize-1的情况下,
10         说明字符数组里面不存在比目标大的字符,此时low==lettersSize,对lettersSize进行取余,
11         返回字符数组第一个元素。
12         */
13         return letters[low%lettersSize];
14 }

 

以上是关于744. Find Smallest Letter Greater Than Target的主要内容,如果未能解决你的问题,请参考以下文章

744. Find Smallest Letter Greater Than Target 找到大于目标的最小的字母

744. Find Smallest Letter Greater Than Target(大于给定元素的最小元素)(leetcode)

744. Find Smallest Letter Greater Than Target 查找比目标字母大的最小字母

LeetCode 744. Find Smallest Letter Greater Than Target (时间复杂度O(n))

leetcode 744. 寻找比目标字母大的最小字母(Find Smallest Letter Greater Than Target)

[LeetCode] Find Smallest Letter Greater Than Target