前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T6-Remove Element(移除元素)

【leetcode刷题】T6-Remove Element(移除元素)

作者头像
木又AI帮
发布2019-07-17 15:44:59
3050
发布2019-07-17 15:44:59
举报
文章被收录于专栏:木又AI帮木又AI帮

今天分享leetcode第6篇文章,也是leetcode第27题—Remove Element,地址是:https://leetcode.com/problems/remove-element/

【英文题目】

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:

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.

【中文题目】

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

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

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

示例 1:

给定 nums = [3,2,2,3], val = 3,

函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。

你不需要考虑数组中超出新长度后面的元素。

【思路】

本题和上一篇文章Remove Duplicates from Sorted Array类似,用一个变量存储其他元素的个数count,每遇见一个不等于val的元素,将其赋值给数组第count个位置处,并且count加1,最后返回count即可。

【代码】

python版本

class Solution(object):
   def removeElement(self, nums, val):
       """
       :type nums: List[int]
       :type val: int
       :rtype: int
       """
       count = 0
       for i in range(len(nums)):
           if nums[i] != val:
               nums[count] = nums[i]
               count += 1
       return count

C++版本

class Solution {
public:
   int removeElement(vector<int>& nums, int val) {
       int count = 0;
       for(int i = 0; i < nums.size(); i++){
           if(nums[i] != val)
               nums[count++] = nums[i];
       }
       return count;
   }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-02-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

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

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

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