27. Remove Element【easy】
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.
解法一:
1 class Solution { 2 public: 3 int removeElement(vector<int>& nums, int val) { 4 if (nums.empty()) { 5 return 0; 6 } 7 8 int i = 0; 9 int j = 0; 10 while (i < nums.size()) { 11 if (nums[i] != val) { 12 nums[j++] = nums[i++]; 13 } 14 else { 15 ++i; 16 } 17 } 18 19 return j; 20 } 21 };
双指针
解法二:
1 public int removeElement(int[] nums, int val) { 2 int i = 0; 3 for (int j = 0; j < nums.length; j++) { 4 if (nums[j] != val) { 5 nums[i] = nums[j]; 6 i++; 7 } 8 } 9 return i; 10 }
Intuition
Since question asked us to remove all elements of the given value in-place, we have to handle it with O(1) extra space.
How to solve it? We can keep two pointers i and j, where i is the slow-runner while j is the fast-runner.
Algorithm
When nums[j] equals to the given value, skip this element by incrementing j. As long as nums[j]≠val, we copy nums[j] to nums[i] and increment both indexes at the same time.
Repeat the process until j reaches the end of the array and the new length is i.
解法三:
1 public int removeElement(int[] nums, int val) { 2 int i = 0; 3 int n = nums.length; 4 while (i < n) { 5 if (nums[i] == val) { 6 nums[i] = nums[n - 1]; 7 // reduce array size by one 8 n--; 9 } else { 10 i++; 11 } 12 } 13 return n; 14 }
Intuition
Now consider cases where the array contains few elements to remove. For example, nums = [1,2,3,5,4], val = 4.
The previous algorithm will do unnecessary copy operation of the first four elements. Another example is nums = [4,1,2,3,5], val = 4.
It seems unnecessary to move elements [1,2,3,5]one step left as the problem description mentions that the order of elements could be changed.
Algorithm
When we encounter nums[i] = val, we can swap the current element out with the last element and dispose the last one. This essentially reduces the array‘s size by 1.
Note that the last element that was swapped in could be the value you want to remove itself. But don‘t worry, in the next iteration we will still check this element.