Given an array arr, 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: arr[]={0,1,0,3,12} Output: arr[]={1,3,12,0,0}
Approach
Java
import java.util.Arrays;public class MoveZeroes {public static void main(String[] args) {int nums[] = { 0, 1, 0, 3, 12 };moveZeroes(nums);System.out.println(Arrays.toString(nums));}public static void moveZeroes(int[] nums) {int l = 0;// iterate till end of numsfor (int i = 0; i < nums.length; i++) {// if element is not 0, then addif (nums[i] != 0) {nums[l++] = nums[i];}}// add zero in lastwhile (l < nums.length) {nums[l++] = 0;}}}
C++
#include <bits/stdc++.h>using namespace std;//function to move all//zeros to the end of//the arrayvoid moveZeroes(vector<int>& arr){int n=arr.size();int l=0;for(int i=0;i<n;i++){if(arr[i]!=0)arr[l++]=arr[i];}while(l<n)arr[l++]=0;}int main(){vector<int> arr={0,1,0,3,12};moveZeroes(arr);for(int i=0;i<arr.size();i++)cout<<arr[i]<<" ";return 0;}
No comments:
Post a Comment