1、移除元素
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
int right = nums.size();
if(right == 0) return 0;
else
{
int left = 0;
while(left < right)
{
if(nums[left] == val)
{
nums[left] = nums[right-1];
right--;
}
else
{
left++;
}
}
return left;
}
}
};
- 基于双指针实现
首先判断数组长度,若为0则直接return 0;
然后获取左指针与右指针,当左指针值与 val 相同时,使用右指针值代替左指针,同时将右指针左移一位,若不相同,则左指针右移一位;
当左右指针重合时,即遍历一遍数组,得到最终结果。
2、删除有序数组中的重复项
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n == 0){
return 0;
}
else{
int slow = 1, fast = 1;
while(fast < n){
if(nums[slow - 1] != nums[fast]){
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}
}
};
- 基于双指针实现(数组升序排列)
首先判断数组长度,若为0则直接return 0;
然后赋值快慢指针(slow与fast同时从1取值意在避免出现fast超出n的取值情况),当慢指针-1值与快指针值不同时,使用慢指针值代替快指针值,同时将快慢指针同时右移一位,若不相同,则仅快指针右移一位;
当快指针到达数组终点时,即遍历一遍数组(最多快慢指针各遍历一遍数组),得到最终结果。
3、三数之和
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
if(n<3){
return ans;
}
sort(nums.begin(), nums.end());
for(int first = 0; first < n-2; first++){
if(first > 0 && nums[first-1] == nums[first]){
continue;
}
int third = n-1, target = -nums[first];
for(int second = first+1; second < n-1; second++){
if(second > first+1 && nums[second-1] == nums[second]){
continue;
}
while(second < third && nums[second] + nums[third]>target){
third--;
}
if(second == third){
break;
}
if(nums[second] + nums[third] == target){
ans.push_back({nums[first], nums[second], nums[third]});
}
}
}
return ans;
}
};
- 基于排序+双指针实现
首先判断数组长度,若小于3则直接return 空;
然后基于排序+双层循环+双指针寻找符合条件的三个数;
第一步,对数组进行排序;
第二步,对first进行循环,若下一次循环first的值与此前相同,则跳过本次循环;
第三步,构建双指针,third指针从数组末尾向左移;second指针从first右一位向右移,若下一次循环second的值与此前相同,则跳过本次循环;
第四步,此时处于第二层循环,已确定first,若first+second+third=0,则second+third=-first,因此,当second<third且second+third>-first,则左移third,直至不满足条件,然后判断second与third的大小,若second=third,说明最小的second+third的值仍大于-first,因此可结束循环;反之,若second+third的值等于-first,则保存结果;
当双指针依次到达数组终点时,即各遍历一遍数组,得到最终结果。