【LeetCode】27 - 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.

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 0; int length=0; for(int i=0;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 0; int newlength=nums.size(); for(int i=0;i<newlength;i++) { if(nums[i]==val) { nums[i]=nums[newlength-1]; i--; newlength--; } } return newlength; }

 

posted @ 2015-08-09 22:30  irun  阅读(139)  评论(0编辑  收藏  举报