27. 移除元素 (Remove Element)

编程入门 行业动态 更新时间:2024-10-18 03:31:23

27. <a href=https://www.elefans.com/category/jswz/34/1767470.html style=移除元素 (Remove Element)"/>

27. 移除元素 (Remove Element)

原题链接

27. 移除元素 (Remove Element)

题目大意

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.

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

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

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

解题思路:
利用双指针思想

  • 定义前置指针index,用于放置符合条件的(不等于val)的元素。
  • 遍历数组,i 指向当前遍历的元素,当前元素如果符合条件,直接赋值给nums[index],且index++;
  • 如果 i 指向的元素不符合条件,i 继续向后遍历,index 不变。

代码:

class Solution {
public:int removeElement(vector<int>& nums, int val) {int index = 0;for (int i = 0; i < nums.size(); i++) {if (nums[i] != val) {nums[index++] = nums[i];}}return index;}
};

更多推荐

27. 移除元素 (Remove Element)

本文发布于:2023-12-07 11:47:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1671136.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:移除   元素   Remove   Element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!