LeetCode 283 Move Zeroes

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/89431219

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.

题目链接:https://leetcode.com/problems/move-zeroes/submissions/

题目分析:非0的往前放,后面不足的补0

0ms,时间击败100%

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

 

没有更多推荐了,返回首页