【LeetCode】27 - Remove Element

时间:2021-02-23 02:48:52

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.

Solution 1:

int removeElement(vector<int>& nums, int val)
{
   /*set a new indexto to record new length, if it is val then jump to next element and do nothing,
    else, keep it. But there are some redundant assignment*/
if(nums.empty())return ;
int length=;
for(int i=;i<nums.size();i++)
{
if(nums[i]!=val)
nums[length++]=val;
}
return length;
}

Solution 2:

int removeElement(vector<int>& nums, int val)
{
   /*the most beautiful solution, when it meets val, assignment this position with the last element, it cost less than once tranversal
    Tips: the element from the last may be val, so i-- is necessary*/
if(nums.empty())return ;
int newlength=nums.size();
for(int i=;i<newlength;i++)
{
if(nums[i]==val)
{
nums[i]=nums[newlength-];
i--;
newlength--;
}
}
return newlength;
}