Remove Element
283. Move Zeros
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
S: read-write pointer 用一对读写指针即可。
void moveZeroes(vector<int>& nums) {
int iw = 0;
for (int ir = 0; ir < nums.size(); ++ir)
if (nums[ir] != 0) nums[iw++] = nums[ir];
for (; iw < nums.size(); ++iw) nums[iw] = 0;
}
27. Remove Element
Given an array and a value, 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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example: Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
S: two pointer
int removeElement(vector<int>& nums, int val) {
int index = 0;
int length;
for(auto num:nums){
if(num != val) nums[index++] = num;
}
return index;
}
26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
S: two pointer
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0) return 0;
int idx = 1;
for(int i = 1; i < nums.size(); ++i){
if(nums[i] != nums[i-1]) nums[idx++] = nums[i];
}
return idx;
}