Given an array of nums, write a function that moves all 0s to the end of the array while maintaining the relative order of non-zero elements.
Enter: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1
The code uses j to record the location of 0, the for loop is always exchanged with 0 and non-zero elements.
Example: We enter nums = [1, 0, 5, 7, 2, 0, 9], look at the exchange process for each step, the red arrow represents the position of each iteration, and the red element represents the exchange that occurred during the traversal. Two elements, as shown:


At the end of the traversal, all zeros are also moved to the back of the list, and the relative position of non-zero elements has not changed.
Mobile zero A set of NUMS is given, writing a function to move all 0 to the end of the array while maintaining a relative order of non-zero elements. Example: Enter: [0, 1, 0, 3, 12] Output: [1, 3, 12...
Matrix zero A matrix of M x N is given, if an element is 0, set all the elements of the line and the column to 0. Please use the original algorithm. Example 1 Enter: [[1, 1, 1], [1, 0, 1], [1, 1, 1]] ...
This is the number of Yuele books.233Update, first246Original 01 Reading and preparation Introduced today is the 100th question of the Easy level in the LeetCode algorithm question (the order number i...
The meaning of the topic is a matter of one line of code. Assume that the final array is all a number f, a total of n times, the length of the array is l, the smallest number in the array is m, the ar...
Find the median...
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Exampl...
describe Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. Example: Analyze Accor...
Zero crossing rate (Zero Crossing Rate,ZCR) Refers to the number of times the voice signal passes through the zero point (from positive to negative or from negative to positive) in each frame. This fe...
[Topic Description] A set of NUMS is given, writing a function to move all 0 to the end of the array while maintaining a relative order of non-zero elements. Example: Enter: [0, 1, 0, 3, 12] Output: [...