1,题目要求
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’.
就是给定一个列表,列表中都是字母,再给一个目标字母,找到比其大的字母,而且整个列表是循环的。
2,题目思路
题目很简单,直接按位比较即可。唯一需要添加的就是当找到最后一位也为得到结果是,按照题目要求整个算法是循环的,因此直接返回第一个元素即可。
3,程序源码:
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
for(auto let : letters)
{
if(let>target)
return let;
}
return letters[0];
}
};
int main()
{
Solution sol;
vector<char> letter = {'a','c','e'};
char let = sol.nextGreatestLetter(letter, 'd');
cout<<let<<endl;
return 0;
}