您的位置:首页 > 其它

LeetCode 283 Move Zeroes题解

2016-12-05 21:48 302 查看
题目地址:https://leetcode.com/problems/move-zeroes/

题目:

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.

给定一个数组,将元素‘0’都移动到非‘0’元素后面。

For example, given 
nums = [0, 1, 0, 3, 12]
, after calling your function, 
nums
 should
be 
[1, 3, 12, 0, 0]
.

例如,给定nums=【0,1,0,3,12】,经过处理,nums=【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.


算法设计:

用两个int型数值i,j分别记录0元素位置和非0元素位置,j用于向后遍历元素,如果遍历到非0元素,如果i,j不指向同一位置,就j指向的元素复制到i的位置,将j位置置0,如果指向同一位置,将i也向后挪动一个位置一遍于j同步。


Java代码实现:

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) {
nums[i++] = nums[j];
nums[j] = 0;
} else {
++i;
}
}
++j;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: