pic

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.

分析

  题目的意思是,给定一个数组和一个值,删除数组中所有等于那个值的元素,返回数组的新长度。


     * 一道很简单的程序设计题目。
     *设置一个游标,游标左边的元素都不等于elem

Code

class Solution {
public:
    /*  设置一个游标,游标左边的元素都不等于elem */
    int removeElement(int A[], int n, int elem) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int index = 0;
        for(int i = 0; i < n; ++i)
            if(A[i] != elem)
                A[index] = A[i], index++;
        return index;
    }
};

pic