Given an array nums, write a function to move all 0'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:

  1. You must do this in-place without making a copy of the array.
  2. 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:

  1. All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.

  2. 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的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 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 ...

  4. 【leetcode】283. Move Zeroes

    problem 283. Move Zeroes solution 先把非零元素移到数组前面,其余补零即可. class Solution { public: void moveZeroes(vect ...

  5. 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 ...

  6. 283. Move Zeroes - LeetCode

    Question 283. Move Zeroes Solution 题目大意:将0移到最后 思路: 1. 数组复制 2. 不用数组复制 Java实现: 数组复制 public void moveZe ...

  7. 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 ...

  8. leetcode:283. Move Zeroes(Java)解答

    转载请注明出处:z_zhaojun的博客 原文地址:http://blog.csdn.net/u012975705/article/details/50493772 题目地址:https://leet ...

  9. 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 ...

随机推荐

  1. golang ---rune与byte

    golang内置类型有rune类型和byte类型. rune类型的底层类型是int32类型,而byte类型的底层类型是int8类型,这决定了rune能比byte表达更多的数. 在unicode中,一个 ...

  2. 简洁的 Python Schema

    目录 Python Schema使用说明 1. Schema是什么? 2. 安装 1. 给Schema类传入类型(int.str.float等) 2. 给Schema类传入可调用的对象(函数.带__c ...

  3. React实例------红绿灯

    概述 一个react的demo的实例,适合初学react的新手练习. 效果 用webpack打包后的目录结构 index.html react的封装,复用与Java的类似,面向对象的编程思想.所以in ...

  4. 服务器推送之SSE简单使用

    前端 <!DOCTYPE html> <html> <head> <meta name="viewport" content=" ...

  5. 【C#常用方法】3.将DataTable一次性插入数据库表中(使用SqlBulkCopy)

    将DataTable一次性插入数据库表中(使用SqlBulkCopy) 1.SqlBulkCopy简介 SqlBulkCopy类是ADO.NET中专门用于数据库批量插入数据的类,其批量插入的执行速度是 ...

  6. .NET中的异步编程——动机和单元测试

    背景 自.NET 4.5发布以来已经有很长一段时间了.留在了我们的记忆里,其发布在2012年8月15日.是的,六年前.感觉老了吗?好吧,我不打算让你做出改变,而是提醒你一些.NET发布的亮点.此版本带 ...

  7. Git 理解修改

    参考链接:https://www.liaoxuefeng.com/wiki/896043488029600/897884457270432 Git之所以比其他版本控制系统设计得优秀,就是因为Git跟踪 ...

  8. Django---ORM的常用字段和自定义字段,DjangoORM字段与数据库类型对应,字段参数和Meta的参数,Django的admin操作,13中orm操作方法,单标的双下方法

    Django---ORM的常用字段和自定义字段,DjangoORM字段与数据库类型对应,字段参数和Meta的参数,Django的admin操作,13中orm操作方法,单标的双下方法 一丶ORM常用字段 ...

  9. 使用Nexus3搭建Maven私服+上传第三方jar包到本地maven仓库

    1.搭建Maven私服背景 公司还是按捺不住,要搭建一个自己的Maven本地仓库,可以让开发人员down架包,从内网还是快很多. 这样公司的maven本地仓库就是 开发人员自己电脑上的maven仓库 ...

  10. Python 列表推导式、矩阵、格式化输出

    列表推导式 列表推导式提供了从列表.元组创建列表的简单途径.语法: [表达式 for语句 if语句] 创建并返回一个列表.if语句可选. 示例: list1=[1,2,3,4] #使用元组也行 lis ...