Leetcode: Remove Element

来源:互联网 发布:pokemon go 辅助软件 编辑:程序博客网 时间:2024/06/06 07:03

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.

比较简单,可以直接遍历往前拷贝, O(n)。考虑到题目允许元素顺序变动,可以采用填坑的方式减少元素移动次数。

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int j = n-1;
        for (int i = 0; i <= j; ++i) {
            while (A[j] == elem) {
                --j;
            }
            if (A[i] == elem && i < j) {
                A[i] = A[j];
                --j;
            }
        }
        
        return (j+1);
    }
};

==============第二次============

class Solution {public:    int removeElement(int A[], int n, int elem) {        int i = 0;        while (i < n) {            if (A[i] == elem) {                A[i] = A[--n];            }            else {                ++i;            }        }                return n;    }};


0 0