您的位置:首页 > 其它

Leetcode_remove-element

2014-03-17 20:43 281 查看
地址:http://oj.leetcode.com/problems/remove-element/

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.
思路:给定一个数组A及其长度n,求其删掉元素elem后的长度和元素,题目不要求数组元素的相对位置,故考虑排序。排序后遍历,如果存在elem,那么elem必定相邻(如果有多个的话),找到所有的elem后开始移动元素。

参考代码:

class Solution {
public:
int removeElement(int A[], int n, int elem) {
int begin = 0, diff = 0;
std::sort(A, A+n);
for(int i = 0; i < n; ++i)
{
if(A[i]==elem)
{
begin = i;
++diff;
while(++i < n && A[i]==elem)
{
++diff;
}
if(i<n)
{
for(;i<n;++i)
{
A[i-diff]=A[i];
}
}
}
}
return n-diff;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: