Remove Element

来源:互联网 发布:运气一直很差知乎 编辑:程序博客网 时间:2024/05/16 18:36

题目:
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 && *A==NULL)        {            return 0;        }        else        {            int count=0;            for(int i=0;i<n;i++)            {                if(A[i]==elem)                {                    count++;                }                else if(count>0)                {                    A[i-count]=A[i];                }            }            return n-count;        }    }};
0 0
原创粉丝点击