【Leetcode】Remove Element

来源:互联网 发布:ubuntu终端退出全屏 编辑:程序博客网 时间:2024/05/01 05:20

题目:

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.


解题思路:设置两个指针pa,pb,pa指针从0开始依次向n-1滑动,当pa指向的元素不是待删除的元素时,将pa指向的元素赋给pb指向的元素,同时pb向前滑动。


代码:

class Solution {public:    int removeElement(int A[], int n, int elem) {        int pa,pb=0;        for(pa=0;pa<n;pa++){            if(A[pa]!=elem){                A[pb++]=A[pa];            }        }        return pb;    }};


0 0
原创粉丝点击