给定一个只包含小写字母的有序数组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"
注:
letters
长度范围在[2, 10000]
区间内。
letters
仅由小写字母组成,最少包含两个不同的字母。
目标字母target
是一个小写字母。
题目中数组是有序的,当时没有看清楚,所以即使无序算法也通用,代码如下:
C++
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target)
{
int n=letters.size();
int m='z'-'a'; //定义最小值m
int m2='z'-'a';
int countpos=0;
char temp=letters[0];
char temp2=letters[0];
for(int i=0;i<n;i++)
{
int cha=letters[i]-target;
if(cha>0)
{
countpos++;
if(cha<m)
{
m=cha;
temp=letters[i];
}
}
else
{
if(countpos>0)
{
continue;
}
else
{
if(cha<m2)
{
m2=cha;
temp2=letters[i];
}
}
}
}
if(countpos>0)
{
return temp;
}
else
{
return temp2;
}
}
};
python
class Solution:
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
n=len(letters)
m=ord('z')-ord('a')
m1=ord('z')-ord('a')
count=0
temp=letters[0]
temp1=letters[0]
for i in range(0,n):
cha=ord(letters[i])-ord(target)
if cha>0:
count += 1
if cha<m:
m=cha
temp=letters[i]
else:
if count>0:
continue
else:
if cha<m1:
m1=cha
temp1=letters[i]
if count>0:
return temp
else:
return temp1