博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
删除数组中特定的值 Remove Element
阅读量:7218 次
发布时间:2019-06-29

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

  hot3.png

问题:

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 in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:

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

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

解决:

①定义一个变量记录新数组的长度,将不等于val的值一次复制到数组的前面,而不必管后面是什么。耗时11ms.

public class Solution {

    public int removeElement(int[] nums, int val) {
       int len = 0;    
       for(int i = 0; i < nums.length; i++){
           if(nums[i] != val){
               nums[len++] = nums[i];
           }
       }
       return len;
    }
}

②使用count记录数组中值为val的个数,将非val的数向前移动count个位数即可。耗时9ms.

public class Solution {

    public int removeElement(int[] nums, int val) {
        int count = 0;//记录val值的个数
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == val){
                count ++;
            }else{
                nums[i - count] = nums[i];
            }
        }
        return nums.length - count;
    }
}

转载于:https://my.oschina.net/liyurong/blog/907421

你可能感兴趣的文章
你必须掌握的 21 个 Java 核心技术!
查看>>
告诉你WHT中文站是什么?
查看>>
4、Juniper SSG520 PPTP映射到ROS后MAC无法连接解决方法
查看>>
利用批处理文件来建立一个记录3389登陆者信息
查看>>
Linux 系统下双机HA的实现
查看>>
02_swarm mode key concepts
查看>>
Eclipse打包插件Fat Jar 解压打包
查看>>
Apache Shiro 使用手册
查看>>
CentOS mini 6.5 安装DB2 Express-C 问题处理记录
查看>>
DirectByteBuffer
查看>>
Docker Compose文件详解 V2
查看>>
Memcached的原理与应用(未完)
查看>>
基于 Confluence 6 数据中心的 SAML 单点登录设置你的身份提供者
查看>>
mysql总结
查看>>
Navicat for MySQL版本更新至v11.2.12,修复多项问题|附下载
查看>>
整理 JAVA中的IO流 (字符流和字节流两个大类)
查看>>
uefi与win8 (根据网络资料整理)
查看>>
Eclipse优化
查看>>
Log4j tutorial with Tomcat examples
查看>>
Kong 网关
查看>>