[LeetCode] Move Zeroes
2015-11-06 16:11
344 查看
Given an array
For example, given
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Java:
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,
numsshould 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.
解题思路
用两个指针i,j分别指向0和非零,当j指向非零时,交换两个指针所指向的元素,并且i向前走一步;j则每次循环无论是否交换都向前走一步。实现代码
C++:// Runtime: 20 ms class Solution { public: void moveZeroes(vector<int>& nums) { int i = 0; int j = 0; while (j < nums.size()) { if (nums[j] != 0) { swap(nums[i], nums[j]); i++; } j++; } } };
Java:
// Runtime: 1 ms public class Solution { public void moveZeroes(int[] nums) { int i = 0; int j = 0; while (j < nums.length) { if (nums[j] != 0) { if (j != i) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } i++; } j++; } } }
相关文章推荐
- android第一个空白的项目
- file命令
- PrintStream打印流
- Linux学习笔记之学习网站
- 将Emacs打造成阅读源代码的神器
- nginx url转发的一种方式
- 中国2015新互联网公司300强系列
- CRT已经成功连接服务器,但是界面显示空白,无任何显示
- 使用一个map映射出两个对象,再把两者关系对应起来
- servlet(验证码)
- C语言练习作业(一)
- 字符串常量赋值导致的错误
- [Laravel]配置路由小记
- javascript--【DRP】
- cpu时间 / cpu利用率计算
- 【数据一致性】多线程写数据库,如何保持数据一致性?
- 树链剖分
- VBA爬虫小试
- hdu5501The Highest Mark(贪心+背包,好题)
- XCODE,Xcode快捷键