博客
关于我
27.移除元素
阅读量:646 次
发布时间:2019-03-15

本文共 799 字,大约阅读时间需要 2 分钟。

为了解决这个问题,我们需要在原地移除数组中所有等于给定值的元素,并返回移除后数组的新长度。我们不能使用额外的数组空间,因此必须在原数组上进行操作。

方法思路

我们可以使用双指针法来解决这个问题。快指针遍历数组,遇到不等于目标值的元素时,将其复制到慢指针当前的位置,并前进慢指针。这种方法确保我们在原地修改数组,同时不使用额外的空间,时间复杂度为 O(n),空间复杂度为 O(1)。

解决代码

public class Test {    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;    }    public static void main(String[] args) {        int[] nums = {0,1,2,2,3,0,4,2};        System.out.println(new Test().removeElement(nums, 2));    }}

代码解释

  • 初始化指针:慢指针 i 初始化为 0,用于记录新数组的起始位置。
  • 遍历数组:快指针 j 从 0 开始遍历数组。
  • 检查元素:如果当前元素 nums[j] 不等于目标值 val,则将其复制到 nums[i],然后前进慢指针 i
  • 返回结果:遍历结束后,慢指针 i 的值即为新数组的长度。
  • 这种方法确保我们在原地修改数组,符合题目要求,同时保证了时间和空间上的效率。

    转载地址:http://fxelz.baihongyu.com/

    你可能感兴趣的文章
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named 'pandads'
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>