博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
27 Remove Element
阅读量:6228 次
发布时间:2019-06-21

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

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.

Example 1:

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

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

nums being 2.

It doesn't matter what you leave beyond the returned length. Example

2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements

of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

思路

用快慢指针的方法遍历数组, 快指针从0-i遍历, 慢指针记录快指针所有不等于val的数值

复杂度

时间O(n) 空间O(1)

代码

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

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

你可能感兴趣的文章
Linux守护进程
查看>>
遇到没“人性”的管理:你真可怜!
查看>>
http://www.bootcss.com/p/font-awesome/
查看>>
新浪微博UWP UI意见征求
查看>>
使用ServiceStack构建Web服务
查看>>
Linqer工具
查看>>
table中超过长度的列,显示省略号
查看>>
Qtcreator中经常使用快捷键总结
查看>>
可扩展Web架构与分布式系统(转)
查看>>
KVM虚拟机的安装
查看>>
【转】PHP中require和include路径问题总结
查看>>
Android 监听apk安装替换卸载广播
查看>>
指针之——一级二级多级指针
查看>>
AndroidStudio遇到过的问题
查看>>
MySQL整体架构与内存结构
查看>>
线上centos6出现软死锁 kernel:BUG: soft lockup
查看>>
pl/sql developer 自动输入替换 光标自动定位
查看>>
HTML5学习笔记(二十三):DOM应用之动态加载脚本
查看>>
Java 中的悲观锁和乐观锁的实现
查看>>
XAMPP permissions on Mac OS X
查看>>