744.搜索比目标字母大的最小印花(javascript)744.FindSmallestLetterGreaterThanTarget

原创
小哥 3年前 (2022-11-10) 阅读数 8 #大杂烩

给您排序的字符列表 letters ,列表仅包含小写英文字母。给出另一个目标字母 target,请在此有序列表中查找大于目标字母的最小字母。

相比之下,字母是按顺序循环出现的。例如:

如果目标字母 target = ‘z’ 字符列表是 letters = [‘a’, ‘b’],答案返回。 ‘a’

Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.

Note that the letters wrap around.

For example, if target == ‘z’ and letters == [‘a’, ‘b’], the answer is ‘a’.

示例 1:

输入: letters = ["c", "f", "j"],target = "a"
输出: "c"

示例 2:

输入: letters = ["c","f","j"], target = "c"
输出: "f"

示例 3:

输入: letters = ["c","f","j"], target = "d"
输出: "f"

解决问题的思路:

  1. letters 对于有序数组,可以使用二分法来查找
  2. 如果发生异常。 letters 里面的最后一个元素小于目标值,所以取它letters 中的索引值为0的元素

    var nextGreatestLetter = function (letters, target) { let left = 0, right = letters.length - 1 if (target >= letters[right]) { return letters[0]; } while (left < right) { let mid = Math.floor((left + right) / 2) if (letters[mid] > target) { right = mid } else { left = mid + 1 } } return letters[left] };

leetcode: https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除