LeetCode :: Remove Element

来源:互联网 发布:江歌事件 知乎 编辑:程序博客网 时间:2024/06/05 15: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.

很简单的一道题目,是和Remove Duplicates sorted array一个时间发出来的,其实基本思路是完全一个,一种智能删除的思想,关键就是使用一个“有效位指针”,用pos这个“有效位指针”来指示new array的有效位,只有符合条件了pos才会后移动,由于是Remove,array的元素只减不增,所以不用担心pos会失效的问题。

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


0 0
原创粉丝点击