现在的位置: 首页 > 综合 > 正文

Leetcode:Remove Element

2013年04月23日 ⁄ 综合 ⁄ 共 463字 ⁄ 字号 评论关闭

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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sumElem=0;
int num=n-1;

for( int i= 0; i <= num ; i ++ )
{
if(A[i]==elem)
{
sumElem++;

while( i < num && A[num] == elem)
{
sumElem++;
num--;
}

if(i==num)
{
return n-sumElem;
}

A[i] = A[num];
num--;
}
}

return n-sumElem;

}
};

抱歉!评论已关闭.