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处重新遍历;若不是给定的数,则直接跳过即可。代码如下:

 class Solution {
public:
int removeElement(int A[], int n, int elem)
{
int count=;
if(n<) return ;
int l=,r=n-;
while(l<=r)
{
if(A[l]==elem)
{
swap(A[l],A[r])
r--;
count++;
}
else
l++;
}
return n-count;
}
};

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

 class Solution
{
public:
int removeElement(int A[],int n,int elem)
{
int count=;
for(int i=;i<n;++i)
{
if(A[i]==elem)
count++;
else if(count>) //避免多个连续
A[i-count]=A[i];
}
return n-count;
}
}

最新文章

  1. Power of Four(Difficulty: Easy)
  2. java 求 两个数的百分比% (转)
  3. jsp页面中的java代码
  4. 使用 Entity Framework
  5. xilinx cpld XC95144XL 最小系统板
  6. COJ 3012 LZJ的问题 (有向图判环)
  7. js关闭 window.open 打开的页面
  8. HTML系列(五):超链接
  9. 第4章 同步控制 Synchronization ----事件(Event Objects)
  10. 前端基于Canvas生成等值面的方案
  11. Java——static关键字
  12. Node url模块
  13. pycharm2016.2.3注册码到期, 激活, 破解版
  14. Linux下的反调试技术
  15. Is there a way to detect if call is in progress? Phone Event
  16. 第二十四章 springboot注入servlet
  17. 使用HVTableView动态展开tableView中的cell
  18. SpringBoot实战(六)之使用LDAP验证用户
  19. 最大流算法-ISAP
  20. 集合的addAll方法--list.addAll(null)会报错--java.lang.NullPointerException

热门文章

  1. pywinauto 使用
  2. Centos7安装FastDFS
  3. 微信小程序关于tabbar点击切换数据不刷新问题
  4. mysql日志管理#二进制日志详解
  5. 爬虫之requests模块基础
  6. Windows和Linux系统下,虚拟环境安装的全面说明和详细步骤
  7. PHP中的面向对象魔术方法大全
  8. 学习CSS
  9. 动态规划----FatMouse’s Speed(HDU 1160)
  10. 最小生成树算法 1.Prim算法