欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[LeetCode]27.Remove Element

程序员文章站 2024-03-22 15:09:04
...

【题目】

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));
    }
};