[LeetCode] Remove Element 分析

来源:互联网 发布:xampp mysql 配置文件 编辑:程序博客网 时间:2024/05/18 19:21
Remove Element算是LeetCode的一道水题,不过这题也有多种做法,现就我所知的几种做一点讨论。

题目链接:https://leetcode.com/problems/remove-element/

题目描述: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. 
要注意的是“It doesn't matter what you leave beyond the new length.”

思路分析:思路很简单,直接上代码。

Solution 1:暴力移动

 1 class Solution { 2 public: 3     int removeElement(vector<int>& nums, int val){ 4         int len = nums.size(); 5         int ptr = 0; 6         int newLen = 0; 7         for(int i = 0;i<len;i++) 8         { 9             if(nums[i]!=val)10             {11                 nums[ptr++]=nums[i];12             }13         }14         newLen = ptr;15         return newLen;16     }17 };

Solution 2:使用STL

1 class Solution {2 public:3     int removeElement(vector<int>& nums, int val) {4         auto end = remove(nums.begin(),nums.end(),val);//这里用到了自动指针5         return distance(nums.begin(),end);6     }7 };

 关于Solution 2中STL的使用:

1,remove算法描述:查找的得到第一个元素的位置,然后从此位置开始遍历容器,将后面的元素依次前移,跳过和value相同值的元素,也就是说,所有和value相同值的元素都会被覆盖,而其他的元素都会依次前移。最后remove返回"指向最后一个'有用'元素的iterator",但是在remove算法过程中,并没有修改原容器的size,以及end()

2,distance()用于求出迭代器之间的距离,即两个参数之间的元素个数。

0 0