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.
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).
Approach 3: Optimal
All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.
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.
Last updated
Was this helpful?