删除序列中的指定元素 Remove Element

来源:互联网 发布:免费x战最新域名 编辑:程序博客网 时间:2024/05/16 12:36

题目源自于Leetcode。

题目: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 left, right;        left=0;        right=0;        while(right<n)        {            if(A[right] != elem)            {                A[left] = A[right];                left++;            }            right++;        }        return left;    }};