首页 > 学院 > 开发设计 > 正文

LeetCode 2 Remove Element

2019-11-06 08:06:39
字体:
来源:转载
供稿:网友

1、题目描述 Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example: Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

2、解题思路

定义两个指针,一个从数组的第一个元素开始向后遍历,另一个从数组的末端向前遍历;

当第一个指针指向的元素是删除的元素时,利用第二个指针将数组后面的非删除元素与之替换;

知道两个指针相等或者后者比前者小时,结束遍历;

此过程中记录遍历元素的个数;

3、代码

#include <iostream> using namespace std;int main(){ cout<<"please input the length of the original arry: "; int n1; cin>>n1; int a[n1]; int del; cout<<"please input the original arry "<<endl; int i=0; for (i=0;i<n1;i++) cin>>a[i]; cout<<"please input the element deleted"; cin>>del; auto *p=&a[0],*q=&a[n1-1]; int j=0; while(p<q){ if (*p==del){ while(*q==del){ q--; } auto b=*p; *p=*q; *q=b; p++; q--; j++; } else{ j++; p++; } } if(p==q){ if(*p!=del) j++; } cout<<"the length of new arry is "<<j<<endl; cout<<"the new arry: "<<endl; for(i=0;i<j;i++) cout<<a[i]<<" "; cout<<endl;}

4、实验结果 这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表