[leetcode]Remove Element

Remove Element

  Total Accepted: 52603  Total Submissions: 162036 My Submissions

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.


首先将所有要删除的数据的位置保存到vector中。

然后从vector的尾部开始往前扫描,如果删除位置是最后面的几位,则直接删除即可。

如果删除数据的位置不在末尾,即末尾的数据不是删除的,则把末尾的数据填充到前面要删除的地方。

例如,下图中,数字表示位置,红色表示该位置需要删除。


首先从尾部开始查看,9号位置是最后一个直接删除,8号位置不用删除,所以将8往0号位置填充,然后继续往前扫描,7号位置又是最后一个数据,直接删除就行,如此。。。。。。

// test27RemoveElement.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include "vector"


using std::vector;


int removeElement(int a[], int n, int elem);


int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { 1, 2, 1, 3, 1, 4, 1, 5, 1 };
int n = removeElement(a, 9, 1);
return 0;
}
int removeElement(int a[], int n, int elem) 
{
vector<int> temp;
for (int i = 0; i < n; i++)
{
if (a[i] == elem)
{
temp.push_back(i);
}


}
int num = temp.size();
int removeNum = num;
if (num == n)
return 0;
if (num == 0)
return n;
int t = n - 1;
auto j = num - 1;
auto start = 0;
while (num > 0)
{
while (temp[j] == t && num > 0)
{
j--;
t--;
num--;
}
while (t>temp[j] && num > 0)
{
a[temp[start]] = a[t];
start++;
t--;
num--;
}
}
return n - removeNum;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值