题目来源于知识星球—英雄算法联盟,五月算法集训专题
目录
前言
跟随英雄算法联盟博主—英雄哪里出来,每天完成相应的算法练习,一个月后,必定会有所成长!
一、917.仅仅反转字母(简单)
1.题目描述
2.解题思路
用双指针一前一后开始遍历,左侧和右侧扫描到字母后,将两个位置的字母交换位置即可。
3.代码演示(C++)
class Solution
{
public:
string reverseOnlyLetters(string s)
{
int n=s.size();
int i=0;
int j=n-1;//用双指针一前一后开始遍历
while(true)
{
while(i<j&&!isalpha(s[i]))//判断左侧是否扫描到字母
{
i++;
}
while(i<j&&!isalpha(s[j]))//判断右侧是否扫描到字母
{
j--;
}
if(i>=j)
{
break;
}
swap(s[i],s[j]);//将两个位置的字母交换
i++;
j--;
}
return s;
}
};
4.题目链接
二、167.两数之和 II-输入有序数组(中等)
1.题目描述
2.解题思路
双指针l和r分别指向数组的两端,一前一后遍历,如果数组中两个数之和等于目标值target,则返回这两个数
在数组中的位置(下标数+1);如果遍历时,两个数之和小于目标值target,则移动l指针;否则移动r指针。
因为所给数组是升序排列。
3.代码演示(C++)
class Solution
{
public:
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int>a(2);
int l=0;
int r=numbers.size()-1;
while(l<r)
{
if(numbers[l]+numbers[r]==target)
{
a[0]=l+1;
a[1]=r+1;
break;
}
else if(numbers[l]+numbers[r]<target)
{
l++;
}
else
r--;
}
return a;
}
};
4.题目链接
三、165.比较版本号(中等)
1.题目描述
2.解题思路
代码来源于LeetCode官方题解,后续仍需加强理解与学习。
3.代码演示(C++)
class Solution {
public:
int compareVersion(string version1, string version2) {
int n = version1.length(), m = version2.length();
int i = 0, j = 0;
while (i < n || j < m) {
int x = 0;
for (; i < n && version1[i] != '.'; ++i) {
x = x * 10 + version1[i] - '0';
}
++i; // 跳过点号
int y = 0;
for (; j < m && version2[j] != '.'; ++j) {
y = y * 10 + version2[j] - '0';
}
++j; // 跳过点号
if (x != y) {
return x > y ? 1 : -1;
}
}
return 0;
}
};
4.题目链接
四、443.压缩字符串(中等)
1.题目描述
2.解题思路
代码来源于LeetCode官方题解,后续仍需加强理解与学习。
3.代码演示(C++)
class Solution
{
public:
int compress(vector<char>& chars)
{
int n = chars.size();
int write = 0, left = 0;
for (int read = 0; read < n; read++)
{
if (read == n - 1 || chars[read] != chars[read + 1])
{
chars[write++] = chars[read];
int num = read - left + 1;
if (num > 1)
{
int anchor = write;
while (num > 0)
{
chars[write++] = num % 10 + '0';
num /= 10;
}
reverse(&chars[anchor], &chars[write]);
}
left = read + 1;
}
}
return write;
}
};
4.题目链接
总结
每天跟随英雄哥学习相关的算法,一个月会收获很多,如果你想了解更多关于知识星球的内容,欢迎联系我!