您的位置:首页 > 其它

LeetCode之Remove Element

2014-01-19 11:18 274 查看

【题目】

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.

【题意】

把数组中与给定值相同的元素删除,在原数组上修改,返回值是最终元素个数。

【分析】



【代码】

/*********************************
*   日期:2014-01-19
*   作者:SJF0115
*   题号: Remove Element
*   来源:http://oj.leetcode.com/problems/remove-element/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int index = 0;
        for(int i = 0;i < n;i++){
            if(A[i] != elem){
                A[index++] = A[i];
            }
        }
        return index;
    }
};
int main() {
    Solution solution;
    int result;
    int A[] = {3,2,5,4,2,6,3,2};
    result = solution.removeElement(A,8,2);
    for(int i = 0;i < result;i++){
        printf("%d ",A[i]);
    }
    printf("\nLength:%d\n",result);
    return 0;
}


【代码2】

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