Leetcode Remove Element

Source: Internet
Author: User

 Remove Element Total Accepted: 60351 Total Submissions: 187833 My Submissions

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 are you leave beyond the new length.

Show Tags

C + + Solutions:
Class Solution {public:    int removeelement (vector<int>& nums, int val) {        int n = nums.size ();        int i = 0;        while (I < n) {             if (nums[i] = = val) {                swap (nums[i], nums[n-1]);                n--;            } else {                i++;            }        }        return n;    }};

int removeelement (vector<int>& nums, int val) {    vector<int>::iterator  ITR = Nums.begin ();    while (ITR! = Nums.end ())    {        if (*itr = = val)            itr = Nums.erase (ITR);        else            ++itr;    }    return Nums.size ();}

int removeelement (int a[], int n, int elem) {    int begin=0;    for (int i=0;i<n;i++) if (A[i]!=elem) a[begin++]=a[i];    return begin;}


Python solution:
Class solution:# @param    a       list of integers# @param    elem an    integers, value need to being removed# @return an  Integerdef removeelement (self, A, elem):    i = 0 for    j in Range (Len (A)):        if a[j]! = Elem:            a[i] = a[j]            i + = 1    return i

The most concise solution in history:
def removeelement (self, Nums, val):        nums[:] = [x for x in Nums if X!=val]        return len (nums)



Leetcode Remove Element

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.