Share the joy
This one is from leetcode which I think is very useful. 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.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
A straight-forward solution is similar to insertion sort, which come up O(N^2) time complexity. However, here is a O(N) solution. The solution is that we make the non-zero elements to the left half. Then we put 0 to the rest.
The code is pretty neat, only with several lines.
Check my code on github: link