1.删除有序数组中的重复项
思路:采用快慢指针法,快指针用来搜索符合要求的元素,慢指针来指示新数组中的位置。这道题关键在于重复元素肯定是连续排列的。用快指针来找出单一元素,慢指针用来在新数组中存放的没有重复出现的元素,且慢指针当前位置就是上一次发现的没有重复出现的元素,因此检验元素是否是重复出现的元素的方法就是将快指针指向的元素与慢指针指向的元素进行比较,且快慢指针初始化时,快指针初始化为1,因为0号元素肯定没有重复出现,不用检验,而慢指针设置为0,存放着0号元素,当快指针找到下一个没有重复出现的元素时,慢指针后移一位(注意代码中要用++lowfastpointer),因为要先后移再赋值,然后为新数组赋值。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int lowpointer=0,fastpointer;
for(fastpointer=1;fastpointer<nums.size();fastpointer++){
if(nums[fastpointer]!=nums[lowpointer])
nums[++lowpointer]=nums[fastpointer];
}
return (lowpointer+1);
}
};
2.比较含退格的字符串
给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。
注意:如果对空文本输入退格字符,文本继续为空。
思路:先将两个字符串转换成没有退格字符的形式。“删除排序数组中的重复项”有异曲同工之妙,采用快慢指针,重构两个字符串,再比较重构后的两个字符串是否相等即可。
注:唯一需要注意的地方在于字符串第一位为符号#时慢指针不回退,不然会造成数组访问越界的问题。
第一次写超出了时间限制
class Solution {
public:
bool backspaceCompare(string s, string t) {
return (str_convert(s)==str_convert(t));
}
private:
string str_convert(string s){
int lowpointer=0,fastpointer=0;
while(fastpointer<s.size()){
if(s[fastpointer]!='#') s[lowpointer++]=s[fastpointer++];
else if(lowpointer>0) {
lowpointer--;
fastpointer++;
};
else fastpointer++; //第一次写时忘记讨论这一情况,在for循环时,这一句可以不写,而while循环时必须加上。
}
return s.substr(0,lowpointer);
}
};
发现如果将while循环改成,for循环则不会超过时间限制,后面发现上面代码问题出在当时在elseif后没有else fastpointer++;这一句,导致当’#'出现在字符串第一个位置时,程序陷入了死循环。而for循环每次fastpointer都会自增,避免了这种情况。
class Solution {
public:
bool backspaceCompare(string s, string t) {
return (str_convert(s)==str_convert(t));
}
private:
string str_convert(string s){
int lowpointer=0,fastpointer=0;
for(;fastpointer<s.size();fastpointer++){
if(s[fastpointer]!='#') s[lowpointer++]=s[fastpointer];
else if(lowpointer>0) {
lowpointer--;
}
}
return s.substr(0,lowpointer);
}
};
3.有序数组的平方
思路:数组原本是有序的, 只是在平方之后就变得无序了, 根本原因就是负数平方之后可能成为最大数了, 那么数组平方的最大值就在数组的两端, 不是最左边就是最右边, 不可能是中间.
这样我们就能确定了平方后最大值的位置, 所以用双指针指向数组的两端, 必定能找到平方后的最大值, 将其放到新数组末尾, 之后不断向中间移动, 通过比较两个指针平方后的大小, 就能不断地将当前的最大值放入数组的尾部, 直到两个指针相遇为止.
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int length=nums.size();
int index;
int lowpointer=0,fastpointer;
vector<int> new_nums(length,-1); //创建新数组
for(index=0;index<length;index++){ //将原数组中所有元素计算平方
nums[index]=nums[index]*nums[index];
}
index=fastpointer=length-1; //双指针找是住在的最大值,并将其放在新数组最后
while(fastpointer>=lowpointer){
if(nums[fastpointer]>=nums[lowpointer]) new_nums[index--]=nums[fastpointer--];
else new_nums[index--]=nums[lowpointer++];
}
return new_nums;
}
};