Find Smallest Letter Greater Than Target问题及解法

来源:互联网 发布:mac aegisub 乱码 编辑:程序博客网 时间:2024/05/22 05:25

问题描述:

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'.

示例:

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"

问题分析:

典型的二分查找算法。


过程详见代码:

class Solution {public:    char nextGreatestLetter(vector<char>& letters, char target) {        int l = 0, r = letters.size() - 1;int res = letters[0];while (l < r){int mid = l + (r - l) / 2;if (letters[mid] <= target) l = mid + 1;else r = mid;}if (letters[l] > target) res = letters[l];return res;    }};


阅读全文
0 0
原创粉丝点击