Commit 9af8a9de authored by yaozc's avatar yaozc
Browse files

27 solved

parent d819cdd6
......@@ -44,3 +44,30 @@ int removeDuplicates(vector<int>& nums) {
}
return ++left;
}
//27 Remove Element
//solution1:使用vector中的erase;需要注意,erase一个iterator后,该指针会成为野指针,不能直接++,所以要让iterator等于erase后返回的新指针(该指针指向vector中后一个element)
int removeElement(vector<int>& nums, int val) {
for(auto i=nums.begin(); i != nums.end();){
if(*i == val){
i = nums.erase(i);
}
else {
i++;
}
}
return nums.size();
}
//solution2:将等于val的element移到vector最后,注意(1)i应该小于nums.size()-counter, (2)swap后应该将i--,这样才不会漏检查swap后的当前element。
int removeElement(vector<int>& nums, int val) {
int counter = 0;
for(int i=0; i<nums.size()-counter; i++){
if(nums[i] == val){
swap(nums[i], nums[nums.size()-counter-1]);
counter++;
i--;
}
}
return nums.size()-counter;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment