首页 > 其他 > 详细

【Remove Elements】cpp

时间:2015-04-23 15:14:30      阅读:202      评论:0      收藏:0      [点我收藏+]

题目

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 index = 0;
        for (int i=0; i<n; ++i)
        {
            if (A[i]!=elem)
            {
                A[index++]=A[i];
            }
        }
        return index;
    }
};

Tips:

设定一个指针,始终指向要插入的元素的为止。

 

或者更简洁一些,用STL函数直接一行代码搞定:

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        std::distance(A,remove(A,A+n,elem));
    }
};

 

【Remove Elements】cpp

原文:http://www.cnblogs.com/xbf9xbf/p/4450451.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!