首页 > 其他 > 详细

[Leetcode] 283. Move Zeroes

时间:2018-11-16 16:48:09      阅读:131      评论:0      收藏:0      [点我收藏+]

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.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
class Solution {
    // 把0移动到最后 <==> 把非0的移动到前面
	public void moveZeroes(int[] nums) {
		// 记录移动了一个非零元素到前面
		// 当移动了move个非零元素到前面时,说明前move个都是移动过的,此时再往前移动时应放在 move位置,才不会破坏顺序
		int move = 0;
		// 记录遍历到第几个
		int index = 0;
		while (index < nums.length) {
			// 如果nums[index]!=0,说明它需要移动到move位置上,并且move+1
            // 除了第一次循环以外,move位置的元素一定是0,因为循环到index时,遇到了move个非0,全移动到最前面了,所以move位置肯定是0
			if (nums[index] != 0) {
				int temp = nums[move];
				nums[move] = nums[index];
				nums[index] = temp;
				move++;
			}
			index++;
		}
	}  
}

  

  

[Leetcode] 283. Move Zeroes

原文:https://www.cnblogs.com/zebinlin/p/9969872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!