Move Zeroes

题目地址:
https://leetcode.com/problems/move-zeroes/#/description

题目:
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.

解题思路:这道题是双指针问题,只需要将非零的数移到前面来,后面再补上0就可以了。

代码:

public void moveZeroes(int[] nums) {
    if(nums == null || nums.length == 0){
        return;
    }
    int slow = 0;
    for(int fast = 0; fast <= nums.length - 1; fast++){
        if(nums[fast] != 0){
           nums[slow] = nums[fast];
           slow++;
        }
    }
    while(slow <= nums.length - 1){
        nums[slow] = 0;
        slow++;
    }
}








Comments

Popular Posts