[Algorithm] 283. Move Zeroes
Given an array
nums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
var moveZeroes = function(nums) {
let pos = 0;
// keep all the non-zero
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[pos++] = nums[i];
}
} // add all zero numbers
for (let i = pos;i < nums.length; i++) {
nums[pos++] = 0;
}
};
This approach works the same way as above, i.e. , first fulfills one requirement and then another. The catch? It does it in a clever way. The above problem can also be stated in alternate way, " Bring all the non 0 elements to the front of array keeping their relative order same".
This is a 2 pointer approach. The fast pointer which is denoted by variable "cur" does the job of processing new elements. If the newly found element is not a 0, we record it just after the last found non-0 element. The position of last found non-0 element is denoted by the slow pointer "lastNonZeroFoundAt" variable. As we keep finding new non-0 elements, we just overwrite them at the "lastNonZeroFoundAt + 1" 'th index. This overwrite will not result in any loss of data because we already processed what was there(if it were non-0,it already is now written at it's corresponding index,or if it were 0 it will be handled later in time).
After the "cur" index reaches the end of array, we now know that all the non-0 elements have been moved to beginning of array in their original order. Now comes the time to fulfil other requirement, "Move all 0's to the end". We now simply need to fill all the indexes after the "lastNonZeroFoundAt" index with 0.
Complexity Analysis
Space Complexity : O(1)O(1). Only constant space is used.
Time Complexity: O(n). However, the total number of operations are still sub-optimal. The total operations (array writes) that code does is nn (Total number of elements).
var moveZeroes = function(nums) {
// keep all the non-zero
for (let i = 0, pos = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
[nums[pos], nums[i]] = [nums[i], nums[pos]];
pos++
}
}
};
The total number of operations of the previous approach is sub-optimal. For example, the array which has all (except last) leading zeroes: [0, 0, 0, ..., 0, 1].How many write operations to the array? For the previous approach, it writes 0's n-1n−1 times, which is not necessary. We could have instead written just once. How? ..... By only fixing the non-0 element,i.e., 1.
The optimal approach is again a subtle extension of above solution. A simple realization is if the current element is non-0, its' correct position can at best be it's current position or a position earlier. If it's the latter one, the current position will be eventually occupied by a non-0 ,or a 0, which lies at a index greater than 'cur' index. We fill the current position by 0 right away,so that unlike the previous solution, we don't need to come back here in next iteration.
In other words, the code will maintain the following invariant:
All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.
All elements between the current and slow pointer are zeroes.
Therefore, when we encounter a non-zero element, we need to swap elements pointed by current and slow pointer, then advance both pointers. If it's zero element, we just advance current pointer.
With this invariant in-place, it's easy to see that the algorithm will work.
It is a great way to kown how to maintain two pointers, one pointer 'i' which is increase by for loop, another pointer 'pos' is increased by condition, which is if(nums[i] != 0).
[Algorithm] 283. Move Zeroes的更多相关文章
- 283. Move Zeroes【easy】
283. Move Zeroes[easy] Given an array nums, write a function to move all 0's to the end of it while ...
- 283. Move Zeroes(C++)
283. Move Zeroes Given an array nums, write a function to move all 0's to the end of it while mainta ...
- LeetCode Javascript实现 283. Move Zeroes 349. Intersection of Two Arrays 237. Delete Node in a Linked List
283. Move Zeroes var moveZeroes = function(nums) { var num1=0,num2=1; while(num1!=num2){ nums.forEac ...
- 【leetcode】283. Move Zeroes
problem 283. Move Zeroes solution 先把非零元素移到数组前面,其余补零即可. class Solution { public: void moveZeroes(vect ...
- LN : leetcode 283 Move Zeroes
lc 283 Move Zeroes 283 Move Zeroes Given an array nums, write a function to move all 0's to the end ...
- 283. Move Zeroes - LeetCode
Question 283. Move Zeroes Solution 题目大意:将0移到最后 思路: 1. 数组复制 2. 不用数组复制 Java实现: 数组复制 public void moveZe ...
- 283. Move Zeroes@python
Given an array nums, write a function to move all 0's to the end of it while maintaining the relativ ...
- leetcode:283. Move Zeroes(Java)解答
转载请注明出处:z_zhaojun的博客 原文地址:http://blog.csdn.net/u012975705/article/details/50493772 题目地址:https://leet ...
- Java [Leetcode 283]Move Zeroes
题目描述: Given an array nums, write a function to move all 0's to the end of it while maintaining the r ...
随机推荐
- FPGA 软件平台
FPGA软件平台 系统 --> windows 7 xilinx --> vivado 2016.4 xilinx --> ISE 14.7 Altera --> quartu ...
- gevent介绍(转)
原文:https://www.liaoxuefeng.com/wiki/897692888725344/966405998508320 Python通过yield提供了对协程的基本支持,但是不完全.而 ...
- java版的状态机实现
状态机适用场景: C的操作,需要等到A.B的两个操作(A.B顺序操作),那就需要在 A.B之间创建一个状态机(state machine),C的操作需要状态机达到某一个状态才能进行 1. Overvi ...
- .NET Core中如何对Url进行编码和解码
我们在.NET Core项目中,可以用WebUtility类对Url进行编码和解码,首先我们要确保项目中引入了nuget包:System.Runtime.Extensions 当然这个nuget包默认 ...
- php 逻辑题
越长大约发现,高中学的数学,都还给了数学老师,一点都没有留住. 最近遇到了一个 逻辑题,然后想了半天,后来做出来了,我就发现了,我可能是一个假的理科生.很简单的样子. 废话不说,看看这道题吧. /** ...
- ASP.NET MVC实现单用户登录
现在许多网站都要求登录后才能进行进一步的操作,当不允许多用户同时登录一个帐号时,就需要一种机制,当再登录一个相同的帐号时,前面登录的人被挤下线,或者禁止后面的人登录.这里实现的是前一种功能. 网上有许 ...
- Openfire Meetings插件是一个包含各种Jitsi项目(如VideoBridge和Meet)的实现
Openfire Meetings插件是一个包含各种Jitsi项目(如VideoBridge和Meet)的实现.要创建与Openfire Meetings一起使用的本机客户端,建议使用Jitsi项目提 ...
- 把EXECL表格导入到WORD中
一般我们在编写开发文档时需要进行表格导入导出,这里提供几种方法供参考. 法一: 打开EXECL,WORD软件,在需要导入表格的地方选择“插入” ,找到“对象选项: ”在对象对话框中点击“由文件创建”, ...
- sql语句技巧
应用场景:当sql 语句中where后面的条件字段为空的时候,条件不存在 eg:根据传入的参数,从student表中查询数据,参数包含姓名(name 必有),年龄(age 不一定有),性别(gende ...
- vue与webpack开发环境搭建:从无到有
一个vue从无到有的搭建过程. 一.不论是webpack还是vue,最初的第一步就是安装node.js.它是基石. 从官网下载你需要的安装包:官网下载链接:http://nodejs.cn/downl ...