LeetCode刷题Easy篇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:

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

十分钟尝试

没有思路,看了牛人的答案,发现很牛逼。

1 遍历数组,如果num不等于0,nums[i]=num.如果等于0,后面不等于0的元素填充。目的是让不等于0的元素移动到前面。

2. 如果最后填充后,后面有剩余空间,全部填充为0,根本不用比较和移动。

class Solution {
    public void moveZeroes(int[] nums) {
        int index=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                nums[index++]=nums[i];
            }
        }
        while(index<nums.length){
            nums[index++]=0;
        }
        
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85090780