数组类算法
双索引技巧 - 对撞指针
1.两数之和Ⅱ - 输入有序数组
日期:2022/7/8
题目描述:给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列 ,请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.length 。
以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1 和 index2。
你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。
你所设计的解决方案必须只使用常量级的额外空间。
示例:
输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
输入:numbers = [2,3,4], target = 6
输出:[1,3]
输入:numbers = [-1,0], target = -1
输出:[1,2]
思路:
对撞指针,如果相加>target,就移动右指针,如果相加<target,就移动左指针
代码+解析:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i=0,j=numbers.size()-1;
while(i<j){
if(numbers[i]+numbers[j] == target){
return {i+1,j+1};
}
if(numbers[j]+numbers[i] > target) j--;
else i++;
}
return {-1,-1};
}
};
学到的总结:
- return {i+1,j+1}就是return数组
- 也可以用二分查找
2.验证回文串
题目描述:给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
**说明:**本题中,我们将空字符串定义为有效的回文串。
示例:
输入: "A man, a plan, a canal: Panama"
输出: true
输入: "race a car"
输出: false
思路:
如果s[i]不属于字母或数字,i++,同理j--。
代码+解析:
class Solution {
public:
bool isPalindrome(string s) {
if(s.size() == 0) return true;
int i=0, j=s.size()-1;
while(i<=j){
if(!((s[i]>='0'&&s[i]<='9') || (s[i]>='a'&&s[i]<='z') || (s[i]>='A'&&s[i]<='Z'))){
i++;
continue;
}
if(!((s[j]>='0'&&s[j]<='9') || (s[j]>='a'&&s[j]<='z') || (s[j]>='A'&&s[j]<='Z'))){
j--;
continue;
}
if(tolower(s[i])!=tolower(s[j])) return false;
i++;
j--;
}
return true;
}
};
学到的总结:
- tolower()
3.反转字符串中的元音字母
题目描述:给你一个字符串 s
,仅反转字符串中的所有元音字母,并返回结果字符串。
元音字母包括 'a'
、'e'
、'i'
、'o'
、'u'
,且可能以大小写两种形式出现。
示例:
输入:s = "hello"
输出:"holle"
输入:s = "leetcode"
输出:"leotcede"
思路:
如果s[i]和s[j]同时为元音,则交换。否则,如果s[i]或s[j]不是元音,则向中间靠拢
代码+解析:
class Solution {
public:
bool judge(char ch){
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
return true;
else
return false;
}
string reverseVowels(string s) {
int i=0, j=s.size()-1;
while(i<j){
if(judge(s[i]) && judge(s[j])){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}else{
if(!judge(s[i])){
i++;
}
if(!judge(s[j])){
j--;
}
}
}
return s;
}
};
双索引技巧 - 滑动窗口
1.长度最小的子数组
题目描述:
示例:
思路:
代码+解析:
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int i=0, j=1;
int sum = nums[0];
int res = 0;
if(sum>=target){
res = 1;
}
while(j<nums.size()){
sum += nums[j];
while(sum>target && i<j){
if(!res) res = j-i+1;
res = min(res,j-i+1);
sum -= nums[i];
i++;
}
if(sum == target){
if(!res) res = j-i+1;
res = min(res,j-i+1);
}
j++;
}
return res;
}
};