Remove Element

来源:互联网 发布:discuza5源码 编辑:程序博客网 时间:2024/06/01 23:27
问题:

Given an array and a value, remove all instances of that value in place and return the new length.

解析:

#include<iostream> 
using namespace std;
class Solution {
public:
int removeElement(int a[], int val){
int n;
n = sizeof(a);
for (int i = 0, int b = 0; i < n; i++){
if (a[i] == val)
n--;
else
a[b++] = a[i];

}
return n;
}
};

解析:

首先是确定数组的长度,然后遍历数组,如果数组中的数等于val的话,长度减一,否则,将这个数组写入另一个新的数组中。