Leetcode744寻找比目标字母大的最小字母
题目
给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。
数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'。
输入: letters = ["c", "f", "j"] target = "a" 输出: "c" 输入: letters = ["c", "f", "j"] target = "c" 输出: "f" 输入: letters = ["c", "f", "j"] target = "d" 输出: "f" 输入: letters = ["c", "f", "j"] target = "g" 输出: "j" 输入: letters = ["c", "f", "j"] target = "j" 输出: "c" 输入: letters = ["c", "f", "j"] target = "k" 输出: "c"
题解
本题采用二分查找来求解,转换为查找左边界的二分查找问题。将目标值加一再在原数组中进行左边界的二分查找,相当于求解大于给定元素的最小元素。
class Solution { public char nextGreatestLetter(char[] letters, char target) { int left = 0; int right = letters.length; while(left < right){ int mid = left + (right - left) / 2; if(letters[mid] < target + 1){ left = mid + 1; } else{ right = mid; } } return right == letters.length ? letters[0] : letters[right]; } }