27. Remove Element

来源:互联网 发布:idea新建普通java项目 编辑:程序博客网 时间:2024/06/06 16:52

题目

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.

Hint:

  1. Try two pointers.
  2. Did you use the property of "the order of elements can be changed"?
  3. What happens when the elements to remove are rare?
分析

详见注释,均使用STL算法。

class Solution {public:    int removeElement(vector<int>& nums, int val) {        sort(nums.begin(),nums.end());//先排序,将相同元素集中在一起        vector<int>::iterator it_begin=find(nums.begin(),nums.end(),val);//查找val第一次出现的位置        if(it_begin==nums.end())//不存在val则返回原集合            return nums.size();        vector<int>::iterator it_end=upper_bound(nums.begin(),nums.end(),val);//查找第一个比val大的元素位置        nums.erase(it_begin,it_end);//删除区间[it_begin,it_end),即删除所有val        return nums.size();    }};


0 0
原创粉丝点击