[leetcode]283.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.
Example:
Input: [0,1,0,3,12]
Output: [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元素,保存一次就自增1。最后数组从j开始到结束都赋值为0即可。
代码
class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
for(int i = 0; i < nums.length; i++)
if(nums[i] != 0) nums[j++] = nums[i];
for(int i = j; i < nums.length; i++)
nums[i] = 0;
}
}
解法二
思路
和解法一思路其实一样,但是不进行赋值操作,而是进行交换操作。
代码
class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
for(int i = 0; i < nums.length; i++)
if(nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j++;
}
}
}