Leetcode_remove-element

来源:互联网 发布:windows subst 编辑:程序博客网 时间:2024/06/03 22:58

地址:http://oj.leetcode.com/problems/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.

思路:给定一个数组A及其长度n,求其删掉元素elem后的长度和元素,题目不要求数组元素的相对位置,故考虑排序。排序后遍历,如果存在elem,那么elem必定相邻(如果有多个的话),找到所有的elem后开始移动元素。

参考代码:

class Solution {public:    int removeElement(int A[], int n, int elem) {        int begin = 0, diff = 0;        std::sort(A, A+n);        for(int i = 0; i < n; ++i)        {            if(A[i]==elem)            {                begin = i;                ++diff;                while(++i < n && A[i]==elem)                {                    ++diff;                }                if(i<n)                {                    for(;i<n;++i)                    {                        A[i-diff]=A[i];                    }                }            }        }        return n-diff;    }};

0 0