LeetCode, leetcodeoj
Link: Remove Element
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
The requirement for this question is to delete the specified element in an array and return the length of the new array. The element sequence of the new array can be changed.
The idea of this question is to use two pointers, l and r. l records the next position (that is, the current length of the new array) that does not contain the specified element. r traverses the array from the beginning, if the number at the r position is equal to the specified number, it is not processed. If the number at the r position is not equal to the specified number, you need to place the number at the r position in the l position and Add 1 to the l position.
Time Complexity: O (n)
Space complexity: O (1)
1 class Solution 2 {3 public: 4 int removeElement (int A [], int n, int elem) 5 {6 if (n = 0) 7 return 0; 8 9 int l = 0; 10 for (int r = 0; r <n; ++ r) 11 if (A [r]! = Elem) 12 A [l ++] = A [r]; 13 return l; 14} 15 };
Reprinted please note the Source: LeetCode --- 27. Remove Element