Acy夕拾算法 Week1_day1
LeetCode 26. 删除有序数组中的重复项
/*整理思路:
·空数组时,返回0;–如果不写会返回1–因为int cur=1
·双指针,cur当前结果,pre去找 不同 的
pre需要到最后,所以pre<size();pre++
pre&cur-1比较,如果不同
把pre赋给cur;cur++
错误点:
·思路错误:判断他们==的时候,pre赋给cur
·遍历时用的i,没有限制pre
·未考虑0时
*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0) return 0;
int cur = 1, pre = 1;
for (; pre < nums.size(); pre++)
{
if (nums[pre] != nums[cur-1])
{
nums[cur] = nums[pre];
cur++;
}
}
return cur;
}
};
LeetCode 27. 移除元素
/*我的思路:
都从0开始遍历,cur是最终答案,pre向后遍历,
遍历到不等于val的数时,放到cur的位置,这样cur以前的都不等于val
*/
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
// if(nums.size()==0) return 0;不需要,因为cur=0一开始
int cur = 0;
for(int pre = 0; pre < nums.size(); pre++)
{
if(nums[pre] != val)//pre遍历到不等时,放到cur的位置
{
nums[cur] = nums[pre];
cur++;
}
}
return cur;
}
};
LeetCode 344. 反转字符串
/*我的思路:
·是以字符数组存储字符串,并且要原地修改
·双指针,直接交换最前后两位置的内容,最前++,最后–
遍历时,保证最前<最后 —不用==,因为两个指针在同一位置,交不交换都是那个字母
·不论数组长度是双数还是单数,都成立。
*/
class Solution {
public:
void reverseString(vector<char>& s) {
// int high = 0, tail = s.size()-1;
// for(int i = 0; i < s.size()/2; i++)
for(int high = 0, tail = s.size()-1;high < tail; high++, tail--)
{
int t = s[high];
s[high] = s[tail];
s[tail] = t;
// high++, tail--;
}
}
};
400

被折叠的 条评论
为什么被折叠?



