[LeetCode 283] Move Zeroes
来源:互联网 发布:ps for mac破解版 编辑:程序博客网 时间:2024/06/10 08:28
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.
solution:
two pointers, one point to first zero element, second point to following first non-zero element.
public class Solution { public void moveZeroes(int[] nums) { if(nums.length<=1) return; int first = 0; int sec = 0; while(sec<nums.length) { //find first zero element while(first<nums.length && nums[first] !=0) { first++; } if(first == nums.length) return; sec = first+1; //find following first non-zero element while(sec<nums.length && nums[sec] == 0){ sec++; } if(sec == nums.length) return; swap(nums, first, sec); } } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }}
0 0
- leetcode 283: Move Zeroes
- leetcode-283-Move Zeroes
- [leetcode 283]Move Zeroes
- LeetCode 283----Move Zeroes
- Leetcode #283 Move Zeroes
- leetcode: (283) Move Zeroes
- [LeetCode 283] Move Zeroes
- Leetcode 283 Move Zeroes
- leetcode 283--Move Zeroes
- LeetCode-----283Move Zeroes
- 【LEETCODE】283-Move Zeroes
- 【LeetCode】283Move Zeroes
- Leetcode #283 Move Zeroes
- LeetCode 283:Move Zeroes
- LeetCode 283:Move Zeroes
- 【LeetCode】283 Move Zeroes
- LeetCode 283 Move Zeroes
- [LeetCode-283] Move Zeroes
- COGS 2027 RQNOJ 72 拔河比赛 背包
- USB数据传输形象讲解
- adb 操作手机
- hdoj3400Line belt【三分法】
- 通过adb 命令操作手机应用
- [LeetCode 283] Move Zeroes
- win7配置自己的IIS服务器亲自做的图文很详细
- BZOJ 1854 [Scoi2010]游戏 二分图最大匹配
- hadoop 自学指南九之HBase
- APP Resource——Handling Runtime Change
- Attempting to start Apache service...but apache doesn't work
- shared_ptr Analysis
- 使用 shared_ptr 的一個問題代碼
- 栈的基本操作