[leetcode]744. Find Smallest Letter Greater Than Target大于Target的最小字母

it2025-12-02  9

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.

 

题意

Solution1

code

1 class Solution { 2 public char nextGreatestLetter(char[] letters, char target) { 3 4 if (letters[0] > target) return letters[0]; 5 if (letters[letters.length - 1] <= target) return letters[0]; 6 7 int left = 0; 8 int right = letters.length - 1; 9 while (left <= right) { 10 int mid = left + (right - left) / 2; 11 if (letters[mid] <= target) { 12 left = mid + 1; 13 } 14 else if (letters[mid] > target) { 15 right = mid - 1; 16 } 17 } 18 return letters[left]; 19 } 20 }

 

转载于:https://www.cnblogs.com/liuliu5151/p/10823265.html

相关资源:数据结构—成绩单生成器
最新回复(0)