前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【每日一题】27. Remove Element

【每日一题】27. Remove Element

作者头像
公众号-不为谁写的歌
发布2020-07-29 15:50:55
2880
发布2020-07-29 15:50:55
举报
文章被收录于专栏:桃花源记

题目描述

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

代码语言:javascript
复制
Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

代码语言:javascript
复制
Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。

不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

题解

这道题类似于上一题26. Remove Duplicates from Sorted Array;不过这里给定的数组没有表明是有序的,但做法大同小异:

  • 声明两个指针,一个指针指向不包含val的数组;另一个指向原数组的第一个元素;
  • 依次遍历,如果当前值等于val,跳过;如果不等于,将这个元素划分到子数组中,
  • 最后不包含val的子数组的下标idx表明数组的右边界,因此返回idx+1即可。

Code

代码语言:javascript
复制
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int idx = -1;
        
        for (int i=0; i< nums.size(); i++){
            if (nums[i] != val)
                nums[++idx] = nums[i];
        }
        
        return idx + 1;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 题解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档