This is the 17th day of my participation in the August Text Challenge.More challenges in August

Title description:

283. Move Zero – Force Buckle (LeetCode) (leetcode-cn.com)

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.

Example:

Input: [0,1,0,3,12] output: [1,3,12,0,0]Copy the code

Description:

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

Thought analysis

Double pointer method

We create two Pointers I and lastNoneZeroIndex, and on the first pass, lastNoneZeroIndex keeps track of how many non-zero elements there are. Each nonzero element is moved to the left of the array. After the first iteration, the index of lastNoneZeroIndex points to the last nonzero element.

The second time, I’m going to start at lastNoneZeroIndex and end at lastNoneZeroIndex, and I’m going to set everything in the remaining region to zero.

AC code

class Solution {
    fun moveZeroes(nums: IntArray): Unit {
        var lastNoneZeroIndex = 0;

        for ( i in 0..nums.lastIndex) {
            if(nums[i] ! =0) { nums[lastNoneZeroIndex++] = nums[i]; }}for ( m in lastNoneZeroIndex.. nums.lastIndex) {
            nums[m] = 0; }}}Copy the code

The code above uses a two-layer loop. The problem asks us to minimize the number of operations, so we are now optimized for a one-layer loop.

class Solution {
    fun moveZeroes(nums: IntArray): Unit {
        var lastNoneZeroIndex = 0;

        for (i in 0..nums.lastIndex) {
            if(nums[i] ! =0) {
                var temp = nums[i]
                nums[i] = nums[lastNoneZeroIndex]
                nums[lastNoneZeroIndex++] = temp
            }
        }
    }
}
Copy the code

Using Kotlin’s syntactic features, we can also write more elegant code

class Solution {
    fun moveZeroes(nums: IntArray): Unit {
        var index = 0
        for ((i, value) in nums.withIndex()) {
            if(value ! =0) {
                nums[i] = nums[index]
                nums[index++] = value
            }
        }
    }
}
Copy the code

conclusion

Simple questions don’t deserve a summary. – –

reference

Two ways to easily block out – Move Zero – Force buckle (LeetCode) (leetcode-cn.com)

Move Zero – Move Zero – Force Buckle (LeetCode) (leetcode-cn.com)

Three solutions – Moving Zero – Force buckle (LeetCode) (leetcode-cn.com)

283. Moving Zero – Moving Zero – Force Buckle (LeetCode) (leetcode-cn.com)