[LeetCode] Remove Element
代码:
1 1 class Solution { 2 2 public: 3 3 int removeElement(int A[], int n, int elem) { 4 4 int index = 0; 5 5 for (int i = 0; i < n; i++) { 6 6 if (A[i] != elem) 7 7 A[index++] = A[i]; 8 8 } 9 9 return index; 10 10 } 11 11 };
其他解法
1 class Solution { 2 public: 3 int removeElement(int A[], int n, int elem) { 4 return distance(A, remove(A, A + n, elem)); 5 } 6 };
杂记:
1. remove
Remove value from range
Transforms the range [first,last)
into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range.
2. distance
Return distance between iterators
Calculates the number of elements between first and last.