Mobile Zero Scala Implementation

Tip: After the article is written, the table of contents can be automatically generated, how to generate it can refer to the help document on the right

 

Article Directory

 


Preface

Implemented using Scala syntax


Tip: The following is the content of this article, the following cases are for reference

1. What is mobile zero

Given an array of nums, write a function to move all zeros to the end of the array while maintaining the relative order of non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Second, use steps

1. Import the library

code show as below:

//Original data: (0,1,0,3,12)
//First processing (1, 3, 12, 3, 12)
//The second processing (1, 3, 12, 0, 0) result

def moveZeroes1(nums: Array[Int]): Unit = {
  var count=0//The current number of non-zero elements
  var len=nums.length
  //The first loop, move all non-zero elements to the front in order
  for ( ind <- 0 until  len)
    if (nums(ind)!=0){
      nums(count)=nums(ind)
      count+=1
    }
  //The second loop, add all zero elements to the back
  for (ind <- count until len)
    nums(ind)=0
}

2. Read in the data

code show as below:

def moveZeroes(nums: Array[Int]): Unit = {
  var indZero = 0 //The index of the current zero element
  var len = nums.length
  for (ind <- 0 until len) {
    if (nums(ind) != 0) {
      val tmp = nums(ind)
      nums(ind) = nums(indZero)
      nums(indZero) = tmp
      indZero + = 1
    }
  }

 


to sum up

Tip: Here is a summary of the article:
For example, the above is what we will talk about today. This article only briefly introduces the use of pandas, and pandas provides a large number of functions and methods that enable us to process data quickly and conveniently.

Guess you like

Origin blog.csdn.net/qq_42456324/article/details/109215745