当前位置:网站首页>力扣每日一题-第51天-744. 寻找比目标字母大的最小字母
力扣每日一题-第51天-744. 寻找比目标字母大的最小字母
2022-08-10 00:48:00 【重邮研究森】
2022.8.9今天你刷题了吗?
题目:
给你一个排序后的字符列表 letters ,列表中只包含小写英文字母。另给出一个目标字母 target,请你寻找在这一有序列表里比目标字母大的最小字母。
在比较时,字母是依序循环出现的。举个例子:
如果目标字母 target = 'z' 并且字符列表为 letters = ['a', 'b'],则答案返回 'a'
分析:
给定一个vector,里面是char类型,以及一个target也是char类型,你需要在vector里面找到一个大于target的字母,且该字母为vector中最小字母。那么就会存在两种情况。
1.找到了存在的字母:直接返回该字母。
2.找不到该字母:直接返回vector第一个字母。
思路:遍历vector数组,每遍历一次判断一次,如果遇到满足条件直接返回,如果不满足最后返回首字母。
解析:
1.暴力法
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
sort(letters.begin(),letters.end());
for(auto &ch:letters)
{
if(ch-'a'<=target-'a')
{
}
else
{
return ch;
}
}
return letters[0];
}
};2.二分法
延续暴力法思路,区别在于不是直接遍历vector,而是利用二分查找从中间开始找,节约时间。
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
int l=0, r=letters.size()-1;
int ret = 0;
while(l <= r){
int m = l + (r-l)/2;
if(letters[m] <= target){
l = m + 1;
}else{
ret = m;
r = m - 1;
}
}
return letters[ret];
}
};边栏推荐
- 无js实现弹出层效果
- 基于SSM实现手机销售商城系统
- FITC标记生物素(FITC-生物素|CAS:134759-22-1)有哪些知识了?
- C language structure, function and pointer exercise (simple address book)
- Teach you how to write performance test cases
- shell指定参数名传参
- Qt的pro文件递归搜寻添加文件
- 【kali-密码攻击】(5.1.2)密码在线破解:Medusa
- 365 days challenge LeetCode1000 questions - Day 052 Step by step summation to get the minimum value of positive numbers Greedy
- Summary of Web Performance Testing Models
猜你喜欢

基于Web的疫情隔离区订餐系统

Not, even the volume of the king to write code in the company are copying and pasting it reasonable?

基于SSM实现手机销售商城系统

assert利用蚁剑登录

宝塔实测-搭建LightPicture开源图床系统

小程序中计算距离信息

什么是一网统管?终于有人讲明白了

Experimental support for decorators may change in future releases.Set the "experimentalDecorators" option in "tsconfig" or "jsconfig" to remove this warning

win10重装系统后没声音怎么办?

【LeetCode】求根节点到叶节点数字之和
随机推荐
win10重装系统后没声音怎么办?
assert利用蚁剑登录
Unity image使用长图后 图片很糊
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
SonarQube升级记录:7.8->7.9->8.9
Summary of basic operations of c language files
Pagoda measurement - building LightPicture open source map bed system
Interdepartmental Communication Skills
信息化和数字化的核心差异
How to add control panel to right click menu in win7
How to activate the payment function on WeChat official account?
Stanford CS143 Speed Pass PA1 Tutorial
宽带由20M换为100M
Mysql database ALTER basic operations
22.括号生成
解决sed替换文本,里面含有“/“、“#”等特殊字符的问题
Teach you how to write performance test cases
2022金九银十工作潮,怎么样才能成功跳槽面试拿到高薪呢?
CAS:851113-28-5 (Biotin-ahx-ahx-tyramine)
【Swoole系列3.5】进程池与进程管理器