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.

思路:

可以使用后面的元素和被删除的元素进行交换,,从前面查找被删除的元素,从后面查找用来替换的元素,不过需要考虑的就是全部符合和全部不符合的情况,从前往后遍历的元素位置就是最后一个不被删除的元素。

#include <iostream>#include <vector>using namespace std;/*题目: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.思路: 由于删除一个元素可以使得原来元素的顺序更改 就可以使用后面的元素来代替前面的元素 */ int Remove_elem(vector<int>& vec,int elem){int j = vec.size()-1;int i;for(i=0;i<j;){if(vec[i] == elem){for(;j>=-1;j–)if(vec[j] != elem)break;if(j<i)break;swap(vec[i],vec[j]);}i++;}return j+1;} int main(){vector<int> vec(10,1);vec[3] = vec[6]=vec[2]=vec[9]=2;cout<<Remove_elem(vec,2);return 0;}

世上没有绝望的处境,只有对处境绝望的人。

Remove elements 删除指定元素

相关文章:

你感兴趣的文章:

标签云: