leetcode刷题日记——Move Zeroes
来源:互联网 发布:很臭的东西淘宝有卖吗 编辑:程序博客网 时间:2024/05/20 09:43
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.
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.
分析:拿到这道题,首先我想到的交换元素,但是题目中提到了要保持数组中非零元素的顺序,所以这条思路行不通。然后再分析此题,有点类似冒泡排序的感觉,相当于把数组中的所有零元素给下沉到数组的最后,于是我就按照冒泡排序算法思维写下如下的解法:
class Solution {public: void moveZeroes(vector<int>& nums) { int size=nums.size(); if(size==0) return; for(int i=size-1;i>0;i--){ if(nums[i]==0) continue; for(int j=0;j<i;j++){ if(nums[j]==0){ nums[j]=nums[j+1]; nums[j+1]=0; } } } }};
虽然通过了,但是考虑到题目中的另外一个要求,最小化交换次数,而我们知道的冒泡排序中需要做大量的两两交换,因此不是最优的解法。再细看此题分析,我们可以先把非零元素挑出来按序放到数组前面,然后对于后面剩下的位置,自动补零就可以了,这样既避免了大量的交换,并且运算时间复杂度也从O(n*n)降到了O(n),具体实现如下
class Solution {public: void moveZeroes(vector<int>& nums) { int size=nums.size(); if(size==0) return; int index=0; for(int i=0;i<size;i++){ if(nums[i]!=0) nums[index++]=nums[i]; } for(int i=index;i<size;i++){ nums[i]=0; } }};
0 0
- leetcode刷题日记——Move Zeroes
- LeetCode OJ刷题历程——Move Zeroes
- leetcode——Move Zeroes
- LeetCode——Move Zeroes
- Leetcode—283Move Zeroes
- leetcode——283——Move Zeroes
- Leetcode学习(34)—— Move Zeroes
- leetcode 每日一题 283. Move Zeroes
- leetcode第283题 ,Move Zeroes
- leetcode 283: Move Zeroes
- leetcode - Move Zeroes
- Leetcode: Move Zeroes
- LeetCode - Move Zeroes
- LeetCode-Move Zeroes
- [LeetCode]Move Zeroes
- leetcode-283-Move Zeroes
- [leetcode 283]Move Zeroes
- LeetCode---Move Zeroes
- html#1
- win7系统下文件夹重命名提示"找不到该项目:的解决!
- MVC HtmlHelper guide
- List,Map,Entity,Object数据类型之间的转换
- MySQL-Redo Log
- leetcode刷题日记——Move Zeroes
- 关于cocoaPods pod update 卡住的解决办法
- 使用Mahout搭建推荐系统之入门篇3-Mahout源码初探
- Log4j配置
- 【jQuery】使用append()方法向元素内追加内容
- error1062 ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry ’1′ for
- 判断银行账号是否输入正确
- 关于java中byte
- 企业APP开发应该关注的那些问题