[leetcode]Remove Element
来源:互联网 发布:编程小白学python pdf 编辑:程序博客网 时间:2024/05/21 02:34
Remove Element
Total Accepted: 52603 Total Submissions: 162036My SubmissionsGiven 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;
}
- LeetCode:Remove Element
- LeetCode: Remove Element
- [Leetcode] Remove Element
- LeetCode: Remove Element
- leetcode 39: Remove Element
- [LeetCode] Remove Element
- Leetcode: Remove Element
- Leetcode:Remove Element
- Leetcode:Remove Element
- Leetcode:Remove Element
- [LeetCode]Remove Element
- LeetCode-Remove Element
- LeetCode - Remove Element
- LeetCode | Remove Element
- leetcode之Remove Element
- LeetCode - Remove Element
- LeetCode: Remove Element
- 【LeetCode】Remove Element
- Android中输出日志
- 二叉树先序遍历非递归方法的两种实现
- 最大二分匹配问题
- 知识分类
- (转载)Android学习之旅- BroadCastReceiver
- [leetcode]Remove Element
- android 用RingtonePreference显示副标题 summary的注意事项
- fastjson
- 马士兵 Servlet_JSP(3) Servlet和JSP的通信(源代码)
- ipbegin10.128.160.168ipend
- [LeetCode]32.Longest Valid Parentheses
- css的选择器.(重点)
- 2015.04.23(Objective _c---NSArray和NSMutableArray)
- ipbegin10.128.160.168ipend