283. Move Zeroes【easy】

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解法一:

 class Solution {
public:
void moveZeroes(vector<int>& nums) {
int i = , j = ;
while (i < nums.size()) {
if (nums[i] != ) {
nums[j++] = nums[i++];
}
else
{
++i;
}
} while (j < nums.size()) {
nums[j++] = ;
}
}
};

双指针

解法二:

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.

 void moveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = ;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = ; i < nums.size(); i++) {
if (nums[i] != ) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
// After we have finished processing new elements,
// all the non-zero elements are already at beginning of array.
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
nums[i] = ;
}
}

Complexity Analysis

Space Complexity : O(1)O(1). Only constant space is used.

Time Complexity: O(n)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).

解法三:

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.

 void moveZeroes(vector<int>& nums) {
for (int lastNonZeroFoundAt = , cur = ; cur < nums.size(); cur++) {
if (nums[cur] != ) {
swap(nums[lastNonZeroFoundAt++], nums[cur]);
}
}
}

Complexity Analysis

Space Complexity : O(1)O(1). Only constant space is used.

Time Complexity: O(n)O(n). However, the total number of operations are optimal. The total operations (array writes) that code does is Number of non-0 elements.This gives us a much better best-case (when most of the elements are 0) complexity than last solution. However, the worst-case (when all elements are non-0) complexity for both the algorithms is same.

上面解法仍有优化空间,对于下标不同的时候才交换

 class Solution {
public:
void moveZeroes(vector<int>& nums) {
for (int i = , j = ; i < nums.size(); ++i) {
if (nums[i] != ) {
if (i != j) {
swap(nums[j], nums[i]);
}
++j;
}
}
}
};

解法二、三均参考自solution

283. Move Zeroes【easy】的更多相关文章

  1. 【leetcode】283. Move Zeroes

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

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

  3. 27. Remove Element【easy】

    27. Remove Element[easy] Given an array and a value, remove all instances of that value in place and ...

  4. 657. Judge Route Circle【easy】

    657. Judge Route Circle[easy] Initially, there is a Robot at position (0, 0). Given a sequence of it ...

  5. 557. Reverse Words in a String III【easy】

    557. Reverse Words in a String III[easy] Given a string, you need to reverse the order of characters ...

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

  7. 170. Two Sum III - Data structure design【easy】

    170. Two Sum III - Data structure design[easy] Design and implement a TwoSum class. It should suppor ...

  8. 160. Intersection of Two Linked Lists【easy】

    160. Intersection of Two Linked Lists[easy] Write a program to find the node at which the intersecti ...

  9. 206. Reverse Linked List【easy】

    206. Reverse Linked List[easy] Reverse a singly linked list. Hint: A linked list can be reversed eit ...

随机推荐

  1. HDU 1754 I Hate It<区间最值 单点修改>

    I Hate It Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  2. [SPOJ]DIVCNT3

    别人写的讲得挺好的博客 洲阁筛,一种快速求积性函数前缀和的算法 求$\sum\limits_{i=1}^nF(i)$,其中$F(x)$是积性函数,并且$F(p^c)$是关于$p$的低阶多项式 我们把$ ...

  3. 【AC自动机/fail树】BZOJ3172- [Tjoi2013]单词

    [题目大意] http://www.lydsy.com:808/JudgeOnline/problem.php?id=3172 某人读论文,一篇论文是由许多单词组成.但他发现一个单词会在论文中出现很多 ...

  4. ReentrantReadWriteLock (读写锁)源码分析

    关于AbstractQueuedSynchronizer中的独占锁,请参考ReentrantLock(http://www.cnblogs.com/bjorney/p/8040085.html) 1. ...

  5. JS删除数组中某一项或几项的方法汇总

    1.JS中的splice方法 splice(index, len, [item])    //注意:该方法会改变原始数组. splice有3个参数,它也可以用来替换/删除/添加数组内某一个或者几个值. ...

  6. MySQL第三方客户端工具

    如前所述,MySQL是一个基于客户机--服务器的DBMS,因此,为了使用MySQl,你需要有一个客户机软件给MySQL提供要执行的命令.即你需要一个编写和测试MySQL脚本的工具. 1.MySQL命令 ...

  7. [Java基础] 使用JMAP dump及分析dump文件

    转载:http://blog.csdn.net/kevin_luan/article/details/8447896 http://liulinxia02.blog.163.com/blog/stat ...

  8. 【JUnit4.10源码分析】6.1 排序和过滤

    abstract class ParentRunner<T> extends Runner implements Filterable,Sortable 本节介绍排序和过滤. (尽管JUn ...

  9. Windows下搭建基于SSH的Git服务器

    Git客户端安装 客户端要同时安装在远程服务器和自己的电脑上,下载地址:http://msysgit.github.io/ 选择安装组件 :也可以默认选择; 图标组件(Addition icons) ...

  10. C#写的一个视频转换解码器

    C#写的一个视频转换解码器 using System; using System.Collections.Generic; using System.Linq; using System.Text; ...