Move 0's to end of array

2020-02-26 01:35发布

I need to move all 0's in an array to the end of the array.

Example: [1, 10, 0, 5, 7] should result in [1, 10, 5, 7, 0].

I am open to doing a reverse loop or a regular loop.

I cannot create a new array.

Here is what I have so far:

for (int i = arr.length; i <= 0; --i) {
    if (arr[i] != 0) {
        arr[i] = arr.length - 1;
    }
}

Thanks!

标签: java arrays
20条回答
2楼-- · 2020-02-26 02:32

This is my code with 2 for loops:

int [] arr = {0, 4, 2, 0, 0, 1, 0, 1, 5, 0, 9,};
int temp;
for (int i = 0; i < arr.length; i++) 
{
  if (arr[i] == 0)
  {
    for (int j = i + 1; j < arr.length; j++) 
    {
      if (arr[j] != 0)
      {
        temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
        break;
      }
    }
  }
}

System.out.println(Arrays.toString(arr));

output: [4, 2, 1, 1, 5, 9, 0, 0, 0, 0, 0]

查看更多
时光不老,我们不散
3楼-- · 2020-02-26 02:33

In case if question adds following condition.

  1. Time complexity must be O(n) - You can iterate only once.
  2. Extra space complexity must be O(1) - You cannot create extra array.

Then following implementation will work fine.

Steps to be followed :

  1. Iterate through array & maintain a count of non-zero elements.
  2. Whenever we encounter a non-zero element put at count location in array & also increase the count.
  3. Once array is iterated completely put the zeros at end of array till the count reach to original length of array.
public static void main(String args[]) {
  int[] array = { 1, 0, 3, 0, 0, 4, 0, 6, 0, 9 };
  // Maintaining count of non zero elements
  int count = -1;
  // Iterating through array and copying non zero elements in front of array.
  for (int i = 0; i < array.length; i++) {
      if (array[i] != 0)
          array[++count] = array[i];
  }
  // Replacing end elements with zero
  while (count < array.length - 1)
      array[++count] = 0;
  for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
  }
}
查看更多
登录 后发表回答