Remove Elements
题目:
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.
中文:
在一个数组里面移除指定value,并且返回新的数组长度,且不能新建一个数组。
方法很简单,使用两个游标i,j,遍历数组,如果碰到了value,使用j记录位置,同时递增i,直到下一个非value出现,将此时i对应的值复制到j的位置上,增加j,重复上述过程直到遍历结束。这时候j就是新的数组长度。超过新的数组长度的值不影响。
#include <iostream>
using namespace std;
int remove(int arr[],int n,int value);
int main()
{
//声明并初始化数组
int array[]={1,2,2,3,2,4};
//移除的值
int elem=2;
int length=remove(array,6,elem);
cout<<"新的数组长度为:"<<length;
return 0;
}
//输入数组,数组长度,要移除的值
//因为数组名就是地址,相当于址传递
int remove(int arr[],int n,int value)
{
int j=0;
for(int i=0;i<n;i++)
{
if(arr[i]==value)
{
continue;
}
arr[j]=arr[i];
j++;
}
return j;
}
输出:
新的数组长度为:3