283.Move-Zeroes
283. Move Zeroes
题目地址
https://leetcode.com/problems/move-zeroes
题目描述
代码
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