Move Zeroes
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1: Example 2:
Input: nums = [0,1,0,3,12] Input: nums = [0]
Output: [1,3,12,0,0] Output: [0]
First, i used this (Two-Pointer Approach)
But this is not optimised.
T.C-o(n^2) S.C-o(1)
Most optimised (Swap Approach) -
Let’s take the input:[0, 1, 0, 3, 12]
1️⃣ i = 0
, j = 0
→ nums[i] == 0
, so do nothing.
2️⃣ i = 1
, j = 0
→ nums[i] == 1
(non-zero), swap nums[0] ↔ nums[1]
→ [1, 0, 0, 3, 12]
- Move
j
to1
3️⃣i = 2
,j = 1
→nums[i] == 0
, so do nothing.
4️⃣i = 3
,j = 1
→nums[i] == 3
(non-zero), swapnums[1] ↔ nums[3]
→[1, 3, 0, 0, 12]
- Move
j
to2
5️⃣i = 4
,j = 2
→nums[i] == 12
(non-zero), swapnums[2] ↔ nums[4]
→[1, 3, 12, 0, 0]
- Move
j
to3
💡 Final Output: [1, 3, 12, 0, 0]
Comments
Post a Comment