arrays - Move Zeroes in Scala -


i'm working on "move zeroes" of leetcode scala. https://leetcode.com/problems/move-zeroes/description/ given array nums, write function move 0's end of while maintaining relative order of non-zero elements. must in-place without making copy of array.

i have solution works in intellij same array input while executing in leetcode, i'm not sure whether done in-place... wrong code ?

thanks

def movezeroes(nums: array[int]): array[int] = {     val lengthorig = nums.length     val lengthfilfter = nums.filter(_ != 0).length     var numswithoutzero = nums.filter(_ != 0)     var numzero = lengthorig - lengthfilfter      while (numzero > 0){        numswithoutzero = numswithoutzero :+ 0        numzero = numzero - 1     }     numswithoutzero } 

and 1 more thing: template code given leetcode returns unit type mine returns array.

def movezeroes(nums: array[int]): unit = {  } 

while agree @ayush, leetcode explicitly asking use mutable states. need update input array contains changes. also, ask in minimal number of operations.

so, while not idiomatic scala code, suggest solution allong these lines:

def movezeroes(nums: array[int]): unit = {     var = 0     var lastnonzerofoundat = 0     while (i < nums.size) {         if(nums(i) != 0) {           nums(lastnonzerofoundat) = nums(i)           lastnonzerofoundat += 1         }         += 1      = lastnonzerofoundat     while(i < nums.size) {         nums(i) = 0         += 1     } } 

as non-idomatic scala, writing such code not encouraged , thus, little bit difficult read. c++ version shown in solutions may easier read , understand code above:

void movezeroes(vector<int>& nums) {     int lastnonzerofoundat = 0;     // if current element not 0, need     // append in front of last non 0 element found.      (int = 0; < nums.size(); i++) {         if (nums[i] != 0) {             nums[lastnonzerofoundat++] = nums[i];         }     }     // after have finished processing new elements,     // non-zero elements @ beginning of array.     // need fill remaining array 0's.     (int = lastnonzerofoundat; < nums.size(); i++) {         nums[i] = 0;     } } 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -