leetcode第25题--Remove Element

problem:

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.

将一个数组里的和给定元素相同的元素删除,在该数组里操作,返回剩下的个数。注意,数组的前部分要保留答案。我本来直接扫一遍,输出n--,错了。还要改变A的值。如下

class Solution {

public:

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

        int result = n, j = 0; 

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

        {

            if(A[i] == elem)

                result--;

            else

                A[j++] = A[i];

        }

    return result;

    }

};

 

你可能感兴趣的:(LeetCode)