Move Zeroes - LeetCode

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.



Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
 
 

class Solution {
    public void moveZeroes(int[] nums) {
        int i, tmp=0;
        for(i=0;i<nums.length;i++){
            if(nums[i]!=0){
             nums[tmp++] = nums[i];   
            }
        }
        for(i=tmp;i<nums.length;i++){
                nums[i] = 0;
        }
    }
} 
 
Click this link to try it on Leetcode 
 
 
Here, the solution has to be completed in a in-build function. 
In this we are going to take a temporary variable starts from 0 and 
changing the array by updating the non-zero values to the same array. 
Once the traversal is completed, temporary variable describes the 
count of zeroes. Then starting from temporary variable position 
till end of array has to be updates as 0. 
 
 
For more Leetcode Problems 

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II