码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] remove element 删除元素

时间:2017-07-03 17:29:29      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:can   in place   大致   ace   数组   turn   leetcode   hang   避免   

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.

题意:删除给定的数,然后返回新的长度。

思路:这题的思路和sort colors差不多,是其简化版。大致的思路是:使用两个指针,指针l 指前,指针 r 指后,遍历数组,遇到给定的数,则将指针 l 指向的元素和r指向的元素交换,每交换一次r--一次,然后重新从指针l处重新遍历;若不是给定的数,则直接跳过即可。代码如下:

 1 class Solution {
 2 public:
 3     int removeElement(int A[], int n, int elem) 
 4     {
 5         int count=0;
 6         if(n<1) return 0;
 7         int l=0,r=n-1;
 8         while(l<=r)
 9         {
10             if(A[l]==elem)
11             {
12                 swap(A[l],A[r])
13                 r--;
14                 count++;
15             }
16             else
17                 l++;
18         }
19         return n-count;
20     }
21 };

思路二:从前向后遍历数组,遇到给定数,记下其位置,将其和后面第一个不为给定数交换,即可。代码如下:

 1 class Solution
 2 {
 3 public:
 4     int removeElement(int A[],int n,int elem)
 5     {
 6         int count=0;
 7         for(int i=0;i<n;++i)
 8         {
 9             if(A[i]==elem)
10                 count++;
11             else if(count>0)  //避免多个连续
12                 A[i-count]=A[i];
13         }
14         return n-count;
15     }
16 }

 

[Leetcode] remove element 删除元素

标签:can   in place   大致   ace   数组   turn   leetcode   hang   避免   

原文地址:http://www.cnblogs.com/love-yh/p/7111837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!