算法系列——Move Zeroes
来源:互联网 发布:少女时代知乎话题 编辑:程序博客网 时间:2024/05/29 09:14
题目描述
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.
解题思路
题目要求将数组中的所有0元素放在数组后面,并保持 非0值的相对顺序不变。
最优的解法应该是时间复杂度O(n)且 空间复杂度为O(1)的解法,核心是,采用双索引 k,i在[0,k]区间的所有元素为非0值,i用来遍历数组,交换0元素和非0元素,直至数组末尾。
算法实现
public class Solution { public void moveZeroes(int[] nums) { int k=0; int temp=0; for(int i=0;i<nums.length;i++) if(nums[i]!=0){ if(i!=k) { temp=nums[k]; nums[k]=nums[i]; nums[i]=temp; } k++; } }}
阅读全文
0 0
- 算法系列——Move Zeroes
- leetcode——Move Zeroes
- Move Zeroes ——LeenCode
- LeetCode——Move Zeroes
- Leetcode—283Move Zeroes
- 【Leetcode算法】- Move Zeroes
- 算法系列——Set Matrix Zeroes
- 15算法课程 283. Move Zeroes
- leetcode——283——Move Zeroes
- LeetCode283——Move Zeroes我的解法
- leetcode刷题日记——Move Zeroes
- LeetCode OJ刷题历程——Move Zeroes
- Leetcode学习(34)—— Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- 自拍仪开发:TypeEror:对象不支持此属性或者方法
- [USACO5.3]量取牛奶Milk Measuring
- LeetCode 7.Reverse Integer
- qt5.8 链接mysql错误:driver not load。
- yum命令提示"Another app is currently holding the yum lock; waiting for it to exit..."
- 算法系列——Move Zeroes
- webview加载https页面空白问题
- C/C++:找零计算器
- shiro +spring + spring mvc+ mybatis整合
- 自定义桌面Widget
- centos安装activeMq
- eclipse下编辑mybatis xml文件没有提示解决办法
- bzoj 1856: [Scoi2010]字符串(卡特兰数)
- SQL Server数据导入报错的问题