1. 程式人生 > >演算法:刪除陣列元素

演算法:刪除陣列元素

LeetCode OJ Problem: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.

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