Статья пока доступна только на английском.
Problem Description
You are given an integer array nums.
Move all zeroes to the end of it while preserving the relative order of the non-zero elements.
Note that you must do this in place, without copying the array.
Constraints
- The array length is from 1 to 10000 elements
- Each element is in the range from -231 to 231 - 1
Examples
Input: nums = [0,1,0,3,12]
Answer: [1,3,12,0,0]
Solution
The solution is very simple.
We need two indices.
The first one is a regular index i, incremented on every iteration.
The second one, firstZeroIndex, is the index of the first zero element in the array, initially 0.
We iterate over all elements of the array and, as soon as we meet a non-zero element, swap it with the zero located at firstZeroIndex.
After a swap, we also increment firstZeroIndex.
This way all zeroes "bubble up" to the end of the array in a single pass.
export const moveZeroes = (nums: number[]): void => {
for (let firstZeroIndex = 0, i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
const temp = nums[i];
nums[i] = nums[firstZeroIndex];
nums[firstZeroIndex] = temp;
firstZeroIndex++;
}
}
};Complexity Analysis
Time Complexity
O(n), since we iterate over all elements of the array.
Space Complexity
O(1), since we don't allocate any memory that depends on the array length.