27 題是個 Array 的題型,題目非常簡單:給定一個陣列,把非 remove 目標的元素放在前 n 個位置,最後回傳 n
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
以C++想法來說非常直觀,透過 iterator 找到要 remove 的元素之後刪掉。但這邊要注意的是 erase() 有個坑,他會把後面的元素都往前遞補,所以如果每個都++ 會踩出界,需要在 for 裡面來處理。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
vector<int>::iterator it;
for(it = nums.begin(); it != nums.end();){
if(*it == val)
nums.erase(it);
else it++;
}
return nums.size();
}
};
另外一個是使用 two pointer 寫法,也是非常的直觀簡單。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int res = 0;
for(int i=0; i< nums.size(); i++){
if(nums[i] != val)
nums[res++] = nums[i];
}
return res;
}
};