Remove Element

本文介绍了如何在不使用额外空间的情况下从数组中移除特定值,并保持数组的相对顺序不变。提供了两种不同的实现思路和对应的Java代码实现。

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

27Remove Element


描述:


Given an array and a value, 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:

Given nums = [3,2,2,3], val = 3,

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

我的思路:


 这道题目较为简单,我有两种思路:

 1. 设置两个指针i,j,开始均指向数组第一个元素,j用于数组从头到尾按顺序扫描,如果元素nums[j] != val,则将其赋值给nums[i]。

最后返回i值即为新数组的长度。

2. 注意题目中“数组中元素的顺序可以改变”,由此可以想到用数组最后一个非val值来替换数组前面的等于val值的元素。也是设置两个

指针i,j,开始时i指向数组第一个元素,j指向数组最后一个元素。i从前向后扫描,j从后向前扫描:若nums[i] = val,就查看此时j指向

的元素是否等于val值,如果不等于val值则直接用nums[j]替换nums[i],如果等于val值则j继续向前扫描直至遇到nums[j] != val,然后

nums[j]替换nums[i]。直至i值大于j值为止,结束循环,返回的i值即为新数组的长度。


这里提示一下,在审题过程中需要注意认真审题,虽然题目最后只要求返回新数组的长度,但是同时也要求直接在原数组上修改得到新

的数组,所以在考虑算法的时候不能只单纯追求得到正确的返回值,也需要得到正确的返回数组。


我的解决:

思路一:

class Solution {
    public int removeElement(int[] nums, int val) {
        int i=0;
        for (int j = 0; j < nums.length; j ++){
            if(nums[j] != val){
                nums[i] = nums[j];
                i++;
            }
        }
        return i;
    }
}
 思路二:

class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0, j = nums.length-1;
        while(i <= j){
            if(nums[i] == val){
                if(nums[j] == val)
                    j--;
                else{
                    nums[i] = nums[j];
                    j--;
                    i++;
                }
            }
            else
                i++;
        }
        return i;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值