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.

分析:本题是要去除数组中指定的元素,并更新数组长度。这道题可以借用一个变量nLength(初始化为0)来更新数组的长度,循环查找指定元素,如果没有,则nLength加1,同时进行更新数组。

代码片段如下。

class Solution {

public:

    int removeElement(int A[], int n, int elem) {

        int nLength=0;

        for(int i=0;i<n;++i)

        {

            if(elem!=A[i])

            {

                A[nLength++]=A[i];

            }

        }

        return nLength;

    }

};

 

 

 

你可能感兴趣的:(element)