Remove Element(删除数组某一元素)

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(vector<int>& nums, int val) {
        vector<int>a;
        for(int i=0;iif(nums[i]!=val)
            a.push_back(nums[i]);
        }
        nums=a;
        return a.size();

    }
};



别人的答案:

int rm(vector<int> &arr, int value)  
{  
    int cnt=0;  
    for(int i=0; iif(arr[i]==value) cnt++;  
        else if (cnt>0)  
        {  
            arr[i-cnt] = arr[i];  
        }  
    }  
    return size-cnt;  
}  


class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (n == 0 ) return 0;
        int len = n;
        for (int i = 0, pos = 0; i < n; ++i)
        {
            if (A[i] == elem)
                --len;
            else
                A[pos++] = A[i];
        }
        return len;
    }
};

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (n == 0 ) return 0;
        int len = n;
        for (int i = 0, pos = 0; i < n; ++i)
        {
            if (A[i] == elem)
                --len;
            else
                A[pos++] = A[i];
        }
        return len;
    }
};


你可能感兴趣的:(代码练习)