首页 > 代码库 > LeetCode: Remove Element [026]

LeetCode: Remove Element [026]

【题目】

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.


【题意】

删除数组中指定的值。不关心在新数组的后面即数组尾部留下了什么值。


【思路】

思路同Remove Duplicates from Sorted Array


【代码】

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        if(n==0)return 0;
        int newArrayTail=-1;    //与去重不同,本题中第一个值就可能会被删除
        int pointer=0;
        while(pointer<n){
            if(A[pointer]==elem)pointer++;
            else {A[++newArrayTail]=A[pointer];pointer++;}
        }
        return newArrayTail+1;
    }
};