LeetCode---Remove Element

时间:2015-01-11 14:51:20   收藏:0   阅读:258

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 0;
        int len = n-1;
        int i=0;
        while(i<=len)
        {
            if(A[i] == elem)
            {
                swap(A,i,len);
                len--;
            }
            else
                i++;
        }
        return len+1;
    }
    void swap(int* a, int i, int j)
    {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}; 


原文:http://blog.csdn.net/shaya118/article/details/42610917

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!