18_leetcode_remove Element

来源:互联网 发布:mac版qq怎么远程 编辑:程序博客网 时间:2024/06/16 12: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.


1:特殊情况:数组为NULL或者n为0 的时候;2:设置两个指针,一个指向当前满足条件的数组的最后一位,一个从头到后遍历指针, 当后一个指针指向的数值为要删除的元素时,指针向后移动, 当指向的数值不为删除的元素时,前一个指针进行操作。3:返回前一个指针


    int removeElement(int A[], int n, int elem)    {                if(A == NULL || n <= 0)            return 0;                int index = -1;                for(int i = 0; i < n; i++)        {            if(A[i] == elem)            {                continue;            }            else            {                A[++index] = A[i];            }        }                return index;    }


0 0