This is the 26th day of my participation in Gwen Challenge

Topic describes

Mobile zero

Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements. Leetcode-cn.com/problems/re…

Input:0.1.0.3.12] output: [1.3.12.0.0]
Copy the code

Description:

Must operate on the original array, cannot copy additional arrays. Minimize the number of operations.

The label

Double pointer

Analysis of the problem solving

1. Double pointer

Let’s get right to it.

Define two Pointers, fast and slow. The fast pointer is used to iterate over whether the element is0. If it is not0, gives its value to the element to which the slow pointer points, and the slow pointer moves right. if0No operation is performed. After fast pointer traversal is complete, all is not0Is assigned to the front of the array, starting at the slow pointer position, and all numbers after the array are set to0Can. Very simple, we create the fast and slow pointer first. The fast pointer is used to iterate over groups of numbers and the slow pointer is used to save not0As it iterates through each element, it determines whether it is0, if not for0Drop the element to the slow pointer and move the slow pointer. For example: [1.2.0.4.6]

1Don't for0So put it in the first one.1] slow pointer ++2Don't for0Then put it in the second [1.2] slow pointer ++00, then leave him alone [1.2]
4Don't for0Then put it in the third [1.2.4]
6Don't for0Then put it in the fourth [1.2.4.6The fast pointer traversal is complete. Get the new array [1.2.4.6] and use a slow pointer to add to the array0And then you get the result. [1.2.4.6.0]
Copy the code

Go to !!!!!

/** Do not return anything, modify nums in-place instead. */
function moveZeroes(nums: number[]) :void {
    // Create a fast pointer to record
    let index = 0;
    for (let i = 0; i < nums.length; i++) {
        // If the current element is not 0, point the element to the slow index
        if(nums[i] ! = =0) { nums[index] = nums[i]; index++; }}// Change all values after the slow pointer to 0
    for (let i = index; i < nums.length; i++) {
        nums[i] = 0; }};Copy the code

And let’s write it like a cool guy.

/** Do not return anything, modify nums in-place instead. */
function moveZeroes(nums: number[]) :void {
    nums.sort((a,b) = > b? 0: -1)};Copy the code

The last

From today not pigeon, every day an algorithm problem and published articles, first want to solve the problem group for Top100, the 14th topic finished work!!