LeetCode 27. Remove Element

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();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值