LeetCode 27. Remove Element

来源:互联网 发布:indesign mac 编辑:程序博客网 时间:2024/06/03 05:51

27. Remove Element

一、问题描述

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.

二、输入输出

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.

三、解题思路

  • 这道题好像是跟另外一道 26 Remove Duplicates from Sorted Array重复了。当时做的时候,是用了2个指针来保存当前遍历的位置 和 新数组的最后一个位置。每当发现一个新元素的时候,就插到新数组的最后。
  • 现在这个题要简单些,是删除指定元素
  • 可以先排序,相同元素就全都挨到一起了。然后查找指定value元素的开始和停止位置;调用vector.erase把这部分删除就可以了
  • 对于数组长度为0的情况,记得单独处理,养成习惯
  • PS:
    • vector.erase里面的迭代器删除时是前闭后开 所以end是你想删除最后一个元素后面的那一个
    • while(nums[end] == val && end < n)类似这种判断 end < n写在前面,取数组某个元素之前,就应该判断是否越界
class Solution {public:    int removeElement(vector<int>& nums, int val) {        if(nums.size() == 0) return 0;        int n = nums.size(), start = 0, end = 0;        sort(nums.begin(), nums.end());        for (int i = 0; i < n; i++) {            if(nums[i] == val){                start = i;                end = i;                break;            }        }        while(nums[end] == val && end < n){            end++;        }        nums.erase(nums.begin()+start, nums.begin()+end);        return nums.size();    }};
原创粉丝点击