当前位置:网站首页>力扣每日一题-第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];
}
};边栏推荐
- RedHat红帽RHEL7安装与使用,VMware Workstation16 Pro虚拟机的安装与使用
- 你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
- UI遍历的初步尝试
- 走出迷宫的最少步数2
- C language structure, function and pointer exercise (simple address book)
- CMake 编译运行dpdk项目程序
- 鲜花线上销售管理系统的设计与实现
- Penetration Testing and Offensive and Defense Confrontation - Vulnerability Scanning & Logic Vulnerability (Part1)
- DALL·E-2是如何工作的以及部署自己的DALL·E模型
- hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
猜你喜欢

Shader Graph learns various special effects cases

2022金九银十工作潮,怎么样才能成功跳槽面试拿到高薪呢?

Unity image使用长图后 图片很糊

商业模式及其 SubDAO 深入研究

PEG 衍生物Biotin-PEG1-OH(cas:95611-10-2,2-生物素氨基乙醇)优势说明

【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price

生物素叠氮化物中的(CAS:1527486-16-3TAMRA-azide-PEG3-Biotin)反应的特点!

芯片资讯|半导体收入增长预计将放缓至 7%,蓝牙芯片需求依然稳步增长

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

高校就业管理系统设计与实现
随机推荐
-Vector Dot Product-
oracle的数据导入导出
商业模式及其 SubDAO 深入研究
即时通讯开发如何撸一个WebSocket服务器
鲜花线上销售管理系统的设计与实现
生物素叠氮化物中的(CAS:1527486-16-3TAMRA-azide-PEG3-Biotin)反应的特点!
unity编辑器扩展界面使用 List
【LeetCode】求根节点到叶节点数字之和
防勒索病毒现状分析
-Chess game-
Win7怎么把控制面板添加到右键菜单
-骑士巡游-
递归 二分查找 冒泡排序 快速排序
Are the numbers entered symmetrical?
小程序实现搜索功能续
宽带由20M换为100M
Minimum number of steps to get out of the maze 2
Shader Graph learns various special effects cases
Web性能测试模型小结
Xi'an biotin-tetrapolyethylene glycol-amide-4phenol light yellow semi-solid