LertCode- 27. Remove Element

2017-07-26  本文已影响23人  去留无意hmy

Description
Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

分析
题目要求对一数组删除指定的元素后形成的新数组。
注意:本题要求只能在原数组的基础上修改,不准定义其他数组。因此修改完原数组后,还应当返回新数组的元素的个数。

C语言代码

//思路一
int removeElement(int A[], int n, int elem)
{
    int i=0,j=0;
    for(i=0;i<n;i++)
    {
        if(A[i]!=elem)
        A[j++]=A[i];
    }
    return j;       
}
//思路二
int removeElement(int A[], int n, int elem)
{
    int i=0,j=n-1,k=0;
    while(i<=j)
    {
        if(A[i]==elem&&A[j]!=elem)
        {
            A[i]=A[j];
            A[j]=elem;
        }
        if(A[i]!=elem)
            i++;
        if(A[j]==elem)
            j--;
    }
    return j+1;     
//结束循环的条件时i>j,由于j每次只移动一位,因此跳出循环时j即满足j+1=i。而i只有在A[i]!=elem的时候增加,即i时数组中与elem相异的数的个数。
}
int main()
{
    int arr[]={3,2,2,3};
    int elem=2;
    removeElement(arr, 4,  3);
     return 0;
}

参考文献
[1] https://leetcode.com/problems/remove-element/#/description
[2] https://hk029.gitbooks.io/leetbook/

上一篇 下一篇

猜你喜欢

热点阅读