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. Prometheus 配置采集目标

    Prometheus 配置采集目标 1.根据配置的任务(job)以http/s周期性的收刮(scrape/pull)2.指定目标(target)上的指标(metric).目标(target)3.可以以 ...

  2. 开发dubbo应用程序(二)dubbo注册中心相关概述

    1.注册中心概述 ​ 在Dubbo微服务体系中,注册中心是其核心组件之一.Dubbo通过注册中心实现了分布式环境中各微服务之间的注册与发现,是各分布式节点之间的纽带.其主要作用如下: 动态加入.一个服 ...

  3. PHP清除数组中有字符串空格的方法

    清除数组中字符串有空格的方法函数 function TrimArray($arr){ if (!is_array($arr)){ return $arr; } while (list($key, $v ...

  4. c++关于IOCP(完成端口)的服务器开发

    本文转载,以便更好的学习C++的服务器开发 1.对IOCP的理解,转载地址 2.在C++中对IOCP的实现,转载地址 注:其实在.net中 ,Socket的服务器开发中,SocketAsyncEven ...

  5. DataPipeline数据融合重磅功能丨一对多实时分发、批量读取模式

    为能更好地服务用户,DataPipeline最新版本支持: 1. 一个数据源数据同时分发(实时或定时)到多个目的地: 2.  提升Hive的使用场景: 写入Hive目的地时,支持选择任意目标表字段作为 ...

  6. Map去重,去重value相同的元素,保留key最小的那个值

    Map<Integer,String>,Integer代表时间撮,String代表文本信息去重函数:就是删除Map中value相同的元素,只保留key最小的那个元素 public stat ...

  7. XmlDocument.load 读文件报异常:文件正被其它线程使用,解决方法

    string filePath = Form1.getProjectFilePath(); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocu ...

  8. Solr基础理论【倒排索引,模糊查询】

    一.简介 现有的许多不同类型 的技术系统,如关系型数据库.键值存储.操作磁盘文件的map-reduce[映射-规约]引擎.图数据库等,都是为了帮助用户解决颇具挑战性的数据存储与检索问题而设计的.而搜索 ...

  9. RabbitMQ基本概念(一)-RabbitMQ的优劣势及产生背景

    本篇并没有直接讲到技术,例如没有先写个Helloword.我想在选择了解或者学习一门技术之前先要明白为什么要现在这个技术而不是其他的,以免到最后发现自己学错了.同时如果已经确定就是他,最好先要了解下技 ...

  10. Mysql 游标初识

    MySql 游标初识 认识 游标(cursor), 按字面意思可理解为, 游动的标识, 或者叫做"光标", 这样更容易理解. 就好比现有一张表存储了n行记录, 然后我想每次取出一行 ...