Move Zeroes (E)

题目

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:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
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.

题意

将数组中所有0放到最后,其余数按照原有顺序放到前面。

思路

见代码。

代码实现

Java

class Solution {
    public void moveZeroes(int[] nums) {
        int p = 0, q = 0;
        while (q != nums.length) {
            if (nums[q] != 0) {
                int tmp = nums[p];
                nums[p++] = nums[q];
                nums[q] = tmp;
            }
            q++;
        }
    }
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄