标签:
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.”
思路分析:思路很简单,直接上代码。
代码一:暴力移动
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 };
代码二:使用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 };
标签:
原文地址:http://www.cnblogs.com/allzy/p/5158810.html