題目:
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.
來源:http://oj.leetcode.com/problems/remove-element/
思路:
元素的順序是可以改變的。除了新的長度外,留下啥都不要緊。
C++ AC代碼:
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int new_length = 0;
for (int i = 0; i < n; i++ ){
if (A[i] != elem ){
A[new_length] = A[i];
new_length++;
}
}
return new_length;
}
};
運行時間 16ms