LeetCode283---Move Zeroes

Question:

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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

分析:将数组中的所有零元素移至数组的后面,需要注意的是所有的非零元素必须保持原始顺序,不能随意更改,而且要求最少的元素操作和不能使用复制数组的做法。做法如下:

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         int index = 0;
 4         for (int i = 0; i < nums.length; i++) {
 5             if(nums[i] !=0){
 6             nums[index++] = nums[i]; 
 7             }
 8         }    
 9         while (index<nums.length) {
10             nums[index++] = 0;
11         }   
13     }
14 }

1、定义一个新的数组下标index,

2、循环数组nums,当遇到非零元素时,将其赋值给数组下标为index的元素,循环结束后得到的下标index之前的所有数组元素均为原始数组的非零元素

4、将剩下的数组元素置为0。

原文地址:https://www.cnblogs.com/miaowu1314/p/6225989.html