Remove Element

来源:互联网 发布:java api 1.8中文 编辑:程序博客网 时间:2024/05/15 18:26

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) {        // Note: The Solution object is instantiated only once and is reused by each test case.        int cnt = 0;        for(int i = 0; i < n; ++i) {            if(elem == A[i]) {                ++cnt;            } else {                A[i-cnt] = A[i];            }        }        return n - cnt;    }};

1 2 1 1 3 1 1 4

这样的话, 直接遍历一次就可以了, 每个数字只移动一次

a[i]移动的距离, 就是a[i]前面出现elem的次数

0 0