题目:
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.
代码:
class Solution { public: int removeElement(int A[], int n, int elem) { if (n==0) return n; int index = 0; for (int i=0; i<n; ++i) { if (A[i]!=elem) { A[index++]=A[i]; } } return index; } };
Tips:
设定一个指针,始终指向要插入的元素的为止。
或者更简洁一些,用STL函数直接一行代码搞定:
class Solution { public: int removeElement(int A[], int n, int elem) { std::distance(A,remove(A,A+n,elem)); } };
时间: 2024-11-13 08:10:08