数组一
1. 两数之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> a;
for(int i = 0; i < nums.size(); i++){
if(a.find(target - nums[i]) == a.end())
a[nums[i]] = i;
else{
return {a.find(target - nums[i])->second, i};
}
}
return {};
}
};
26. 删除有序数组中的重复项
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0) return 0;
int slow = 0, fast = 1;
while(fast < nums.size()){
if(nums[fast] != nums[slow]){
if(fast - slow > 1){
nums[slow + 1] = nums[fast];
}
slow += 1;
}
fast += 1;
}
return (slow + 1);
}
};
27. 移除元素
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int s = 0, f = 0; //右指针指向当前将要处理的元素,左指针指向下一个将要赋值的位置。
while(f < nums.size()){
if(nums[f] != val){
if(f - s > 0)
nums[s] = nums[f];
s++;
}
f++;
}
return s;
}
};