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 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:
- You must do this in-place without making a copy of the array.
- 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:
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.
- 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】的更多相关文章
- 【leetcode】283. Move Zeroes
problem 283. Move Zeroes solution 先把非零元素移到数组前面,其余补零即可. class Solution { public: void moveZeroes(vect ...
- 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 ...
- 27. Remove Element【easy】
27. Remove Element[easy] Given an array and a value, remove all instances of that value in place and ...
- 657. Judge Route Circle【easy】
657. Judge Route Circle[easy] Initially, there is a Robot at position (0, 0). Given a sequence of it ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- 206. Reverse Linked List【easy】
206. Reverse Linked List[easy] Reverse a singly linked list. Hint: A linked list can be reversed eit ...
随机推荐
- 【AC自动机】【状压dp】hdu2825 Wireless Password
f(i,j,S)表示当前字符串总长度为i,dp到AC自动机第j个结点,单词集合为S时的方案数. 要注意有点卡常数,注意代码里的注释. #include<cstdio> #include&l ...
- 【kruscal】【最小生成树】【搜索】bzoj1016 [JSOI2008]最小生成树计数
不用Matrix-tree定理什么的,一边kruscal一边 对权值相同的边 暴搜即可.将所有方案乘起来. #include<cstdio> #include<algorithm&g ...
- 【函数式权值分块】【分块】bzoj3196 Tyvj 1730 二逼平衡树
#include<cstdio> #include<cmath> #include<algorithm> using namespace std; #define ...
- Target runtime Apache Tomcat 7.1 is not defined 解决方法
在工作台目录下找到 自己操作的项目的文件夹 /.settings/org.eclipse.wst.common.project.facet.core.xml 打开后,显示 <?xml versi ...
- 使用jQuery操作dom(追加和删除样式-鼠标移入移出)练习
1.实现鼠标移入则添加背景色,鼠标移出则删除背景色 <!DOCTYPE html> <html> <head> <title>test1.html< ...
- Java杂谈6——Java安全模型
Java语言安全模型是其有别于传统的编程语言的一个很重要的特点,采用一种沙箱模型隔离了Java的运行环境与具体的操作系统,使得Java在网络环境下能够更为安全的运行.理解Java的安全模型,能够帮助我 ...
- 集群Cluster介绍
来源:http://www.ibm.com/developerworks/cn/linux/cluster/lw-clustering.html简单的说,集群(cluster)就是一组计算机,它们作为 ...
- 集合视图UICollectionView 介绍及其示例程序
UICollectionView是一种新的数据展示方式,简单来说可以把它理解成多列的UITableView.如果你用过iBooks的话,可 能你还对书架布局有一定印象,一个虚拟书架上放着你下载和购买的 ...
- ubuntu16.04给普通用戸提成root权限,会出现造成重启系统,没有登录用户
一.导致问题的原因 直接修改配置文件提权,会造成重启系统后没有原来的登录用户 vim /etc/passwd nulige:x:0:0:nulige,,,:/home/gree:/bin/bash 解 ...
- 60分钟搞定JAVA加解密
从摩尔电码到小伙伴之间老师来了的暗号,加密信息无处不在.从军事到生活,加密信息的必要性也不言而喻. 今天,我们就来看看java怎么对数据进行加解密 分类 a.古典密码 -- 受限制算法:算法的保密性给 ...