移除元素 (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)
发布评论