Removing all zeroes to the left of an array GFG
package com.company;
import java.util.Arrays;
public class Array7 {
// Sir's efficient method
public static int[] atEnding(int[] arr){
int n = arr.length;
int count = 0;
for(int i = 0; i < n; i++){
if(arr[i] != 0){
arr[count] = arr[i];
arr[i] = 0;
count++;
}
}
return arr;
}
// Efficient Solution my solution which takes BIG O(n^2)
public static int[] atEnd(int[] arr) {
int n = arr.length;
int res = 0;
for (int j = 0; j < n; j++) {
if (arr[j] == 0) {
res = j;
break;
}
}
for (int i = 0; i < n - 1; i++) {
if (arr[i] == 0 && arr[i + 1] != 0) {
arr[res] = arr[i + 1];
arr[i + 1] = 0;
res = i + 1;
}
}
return arr;
}
// Remove all zero to end MY SOLUTION BIG O(n^2) time
public static int[] removeZeroToEnd(int[] arr, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] == 0 && arr[j] != 0) {
// int a = arr[i];
arr[i] = arr[j];
arr[j] = 0;
}
}
}
return arr;
}
public static void main(String[] args) {
int[] array = {0, 0, 0, 1, 0};
System.out.println(Arrays.toString(atEnding(array)));
}
}
Comments
Post a Comment