<strong><span style="font-size:14px;">题目:</span></strong>
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.
思路:遍历数组,找到目标元素,用数组最后一位替换该目标数组。
Attention: 注意考虑elem出现在最后一位的特殊情况!
AC code:
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Attention: A 的长度是一直在变化的;注意考虑elem出现在最后一位的情况
if(n==0) return 0;
int newlength = n;
for(int index=0; index != newlength; index++)
{
if(A[index] == elem)
{
//if elme is not the last of A
if(index != newlength)
{
A[index] = A[newlength-1];
//Use the last element to cover the current element
//And decrease the newLength by 1
--newlength;
// Decrease the index so that the new current element
// can be checked in next loop
--index;
}
else
--newlength;
}
}
return newlength;
}
};