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.

题目的要求大概是给定一个数组和一个值,删除数组中所有和该值相同的元素并返回一个新的长度

说一下思路:

可以采用双指针,下标i循环数组,每次都让p_last下标与i一起遍历,当A[i]与给定的value相同的时候,p_last停止,数组长度-1,i继续走将下一个值赋给A[p_last],如果是A[i]与value不同的话,就让p_last+1

具体的代码如下:

 class Solution {
public:
int removeElement(int A[], int n, int elem) {
int length = n;
int p_last = ;
for(int i=;i<n;i++){
A[p_last] = A[i];
if(A[i] == elem)
length--;
else
p_last++;
}
return length;
}
};

或者可以有一个更加直观的理解:

如下面的代码:

 class Solution {
public:
int removeElement(int A[], int n, int elem) {
int length = n;
int p_last = ;
for(int i=;i<n;i++){
if(A[i]==elem){
length--;
}else{
A[p_last] = A[i];
p_last++;
}
}
return length;
}
};

p_last代表当前”新“数组的下标,i循环数组当A[i]!=elem时进行赋值,并将p_last加一”新“数组的下一个元素等待被插入个人认为这种方式解释方式比较直观。

最新文章

  1. E-Business Suite 12.2 startCD 50 Install Fails with Fatal Error: TXK Install Service oracle.apps.fnd.txk.config.ProcessStateException: OUI process failed Cannot install Web Tier Utilities
  2. python字符串的编码格式
  3. gb2312
  4. Servlet路径跳转2--在servlet当中,跳转到某网页时的路径写法
  5. 1066 Bash游戏
  6. 关闭用miniUI打开的窗口
  7. C# 想要程序文件移动 而数据保持相对位置
  8. U盘中的闪存白片与黑片
  9. ipc$爆破密码
  10. FLUSH TABLES WITH READ LOCK 锁全局
  11. Plotting trees from Random Forest models with ggraph
  12. 一口一口吃掉Volley(四)
  13. 理解Object.defineProperty函数中的get与set
  14. dll导出函数的两种方式的比较
  15. Hlacon 之Image ,Region,XLD
  16. xgboost原理
  17. Springmvc 使用 AbstractExcelView 导出excel
  18. Linux学习1-Xshell连接阿里云ECS服务器
  19. java 抽象类 接口 区别
  20. php过滤数组空值

热门文章

  1. 高效批量更新 sql 字段的值(从一个表向另一个表更新)
  2. asp生命周期
  3. DOM重绘对focus的影响
  4. Android icons集合
  5. YUV422 YUV420 Planar \ Semi-Planar \ Interleaved
  6. oracle 使用基本问题
  7. PLSQL实例(游标)
  8. xstream对象xml互转
  9. QT中嵌入SDL
  10. STM32F103控制两个步进电机按照一定转速比运动