移除元素

这道LeetCode题目要求在O(1)额外空间复杂度下,原地移除数组中所有等于特定值的元素,并返回新长度。通过遍历数组并替换不需要的元素来实现,注意无需真正交换元素,只需覆盖即可。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Clarification:

confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference,which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

//nums is passed in by reference.(i.e. without making a copy)

int len = removeElement(nums, val);

//any modification to nums in your function would be known by the caller.

//using the length returned by your function, it prints the first len elements.

for(int i = 0; i < len; i++) {

​ print(nums[i]);

}

在这里插入图片描述

今天又是一道简单难度的题,题目要求是这样的:输入一个整数数组nums和一个值val,要求在原数组的基础上去除所有和val相等的值。

emmmm又是一道“原地”处理数组的问题,最近力扣出了好多类似的问题啊……

题目还是比较简单的,大体思路如下:

先定义一个len用来保存当前保留的数组的长度,初始值当然是输入数组nums的长度。

再使用一个index索引遍历数组。

如果当前判断的元素和val相等,那么我们就要把它“去除”,具体怎么去除呢?

因为去除了一个元素,所以我们保留的数组的长度就减一,即len–,此时我们在遍历时,数组的最后一个元素就不会被遍历到,也就是说,我们去除了数组的最后一个元素。既然这样,那么我们只需要将要去除的元素与当前数组最后一个元素进行交换即可。

但是,别忘了,题目中说,数组后面的元素是什么样子它根本不关心,只要我们保留的数组符合要求即可,那么我们也就没有必要真的进行交换,只需要用当前数组的最后一个元素覆盖当前位置就可以了。

举个例子,比如nums=[1, 2, 3, 2, 4, 5], val=2

初始状态:

在这里插入图片描述

此时1 != 2,所以index++,继续向后遍历,因为2 == 2,所以将len指向的元素赋值给当前index指向的元素,同时len–

在这里插入图片描述

然后此时5 != 2,index++

在这里插入图片描述

3 != 2,继续向后遍历
在这里插入图片描述

这个时候发现2需要被去除,所以将4赋值给index所指向的位置,len–

在这里插入图片描述

此时index所指的元素不等于val,而且index与len重合,循环结束。

所以最终得到的结果为:[1, 5, 3, 4]

具体的实现代码如下:

/**
 * @author: LittleWang
 * @date: 2021/4/19
 * @description:
 */
public class Solution {
    public int removeElement(int[] nums, int val) {
        int len = nums.length;
        if(len == 0)
            return 0;

        int index = 0;
        while(index < len) {
            if(nums[index] == val) {
                nums[index] = nums[len-1];
                len--;
            }
            else {
                index++;
            }
        }

        return len;
    }
}

问题解决,提交结果如下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值