leetcode 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.

 

Subscribe to see which companies asked this question

 

一道简单到感动的题目,因为不牵扯改变顺序的问题,你排序一下,然后找到删除就好了。

注意点:erase(i)自带i++效果,就是每次删除i的时候会自动将i向后移,所以这个时候如果for循环里有i++就会出错。

 1 class Solution {
 2 public:
 3     int removeElement(vector<int>& nums, int val) {
 4         int s=nums.size(),count=0;
 5         if(s==0) return 0;
 6         sort(nums.begin(),nums.end());
 7         for(auto i=nums.begin();*i<=val&&i!=nums.end();){
 8             if(*i==val){
 9                 count++;
10                 nums.erase(i);
11             }
12             else i++;
13         }
14         return s-count;
15     }
16 };

 

posted @ 2015-11-23 19:20  0giant  阅读(145)  评论(0编辑  收藏  举报