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