283.Move-Zeroes

283. Move Zeroes

题目地址

https://leetcode.com/problems/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:

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

代码

Approach 1: Sapce Sub-Optimal

Complexity Analysis Space Complexity : O(n). Since we are creating the "ans" array to store results. Time Complexity: O(n). However, the total number of operations are sub-optimal. We can achieve the same result in less number of operations.

class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0) return;

        int n = nums.length;
        int numZeroes = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] == 0) {
                numZeroes++;
            }
        }

        List<Integer> ans = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            if (nums[i] != 0) {
                ans.add(nums[i]);
            }
        }

        while (numZeroes--) {
            ans.add(0);
        }

        for (int i = 0; i < n; i++) {
            nums[i] = ans[i];
        }

    }
}

Appraoch 2: Space Optimal, Operation Sub-Optimal

Complexity Analysis

Space Complexity : O(1). Only constant space is used.

Time Complexity: O(n). However, the total number of operations are still sub-optimal. The total operations (array writes) that code does is n (Total number of elements).

class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0) return;

        int lastNonZeroFoundAt = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[lastNonZeroFoundAt++] = nums[i];
            }
        }

        for (int i = lastNonZeroFoundAt; i < nums.length; i++) {
            nums[i] = 0;
        }
    }

}

Approach 3: Optimal

  1. All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.

  2. All elements between the current and slow pointer are zeroes.

Complexity Analysis

Space Complexity : O(1). Only constant space is used.

Time Complexity: O(n). However, the total number of operations are optimal. The total operations (array writes) that code does is Number of non-0 elements.This gives us a much better best-case (when most of the elements are 0) complexity than last solution. However, the worst-case (when all elements are non-0) complexity for both the algorithms is same.

class Solution {
    public void moveZeroes(int[] nums) {
    for (int lastNonZeroFoundAt = 0, cur = 0; cur < nums.length; cur++) {
      if (nums[cur] != 0) {
        swap(nums[lastNonZeroFoundAt++], nums[cur]);
      }
    }

  }
}

Last updated