題目描述:
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.
Example 1:
Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length.
代碼:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int flag1 = 0, flag2 = nums.size() - 1;
int length = 0;
while(flag1 <= flag2){
if(nums[flag1] != val){
flag1++;
length++;
}else{
int tmp = nums[flag1];
nums[flag1] = nums[flag2];
nums[flag2--] = tmp;
}
}
return length;
}
};
此題爲easy題,題目要求給定一個數組,和一個val,要求刪除數組中所有值爲val的元素。並且返回刪除後數組的長度l,空間複雜度爲O(1),要求原數組的前l個元素爲刪除值爲val的元素後剩餘的元素。題目思路爲設置兩個flag並且遍歷整個數組,當遍歷到的值爲val時,丟到數組尾(flag2位置處)。這樣最後數組的前l個元素即爲刪除val元素後剩餘的所有元素。
做的過程中想到了另外一種解題思路或許能更簡單一點,即利用vector的erase函數,直接將值爲val的元素消滅,感覺會簡單一點:)