将数组中的0移动到末尾

8

我需要将数组中所有的0移动到数组的末尾。

例如:[1, 10, 0, 5, 7] 应该变为 [1, 10, 5, 7, 0]。

我可以使用正向循环或反向循环。

不能创建新的数组。

这是我目前的代码:

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

谢谢!


你有任何限制吗? - dcow
1
沿着走,如果你发现一个零后面不跟着另一个零,那就交换它们。重复此过程直到没有更多的交换... - Boris the Spider
冒泡排序?... - dcow
@Gary McSperry,您编辑了这个问题。您的意思是您无法创建一个新的循环吗? - dcow
@DaidCowden 我的意思是我无法创建一个新数组,我的错。 - Nobody
显示剩余2条评论
22个回答

0
假设你有一个数组,像这样:
int a[] = {0,3,0,4,5,6,0};

然后你可以像这样对它进行排序,

   for(int i=0;i<a.length;i++){
    for(int j=i+1;j<a.length;j++){
    if(a[i]==0 && a[j]!=0){
    a[i]==a[j];
    a[j]=0;
    }
    }
    }

0
int arrNew[] = new int[arr.length];
int index = 0;
for(int i=0;i<arr.length;i++){
    if(arr[i]!=0){
       arrNew[index]=arr[i];
       index++;
    }
}

由于int数组被初始化为零(根据语言规范),这将产生您想要的效果,并将所有其他内容顺序向上移动。

编辑:根据您的编辑,您不能使用新数组,因此此答案不符合您的要求。您需要从数组末尾开始检查零,并与数组的最后一个元素交换,然后减少您的最后一个非零元素的索引,然后再进行下一次交换。例如:

int lastZero = arr.length - 1;
if(arr[i] == 0){
  //perform swap and decrement lastZero by 1 I will leave this part up to you
}

@David Cowden,抱歉,我没有考虑清楚就写了那个评论...按下了回车键而不是退格键。决定留下它,看起来像是作业。 - NeilA
我认为将交换移到末尾会改变其他元素的顺序;相反,你需要将所有元素向上移动。 - Boris the Spider
如果他需要维护顺序,那么他需要将逻辑放在if块中。他没有说明他是否需要,所以我将交换的逻辑留给OP(这就是为什么我在块中只有一个注释)。 - jzworkman

0

假设我们有一个数组

[5,4,0,0,6,7,0,8,9]

假设我们有一个包含0-100之间的数组元素,现在我们的目标是将所有的0移动到数组的末尾。 从数组中取出0,并将其与非零元素进行比较,如果找到任何非零元素,则交换该元素,以此类推,在循环结束时,我们将找到解决方案。
以下是代码:
for (int i = 0; i < outputArr.length; i++) 
  {

      for (int j = i+1; j < outputArr.length; j++) 
  {
        if(outputArr[i]==0 && outputArr[j]!=0){

            int temp = outputArr[i];
            outputArr[i] = outputArr[j];
            outputArr[j] = temp;

        }

     }
        print outputArr[i]....
}

输出:

[5,4,6,7,8,9,0,0,0]

0
public void test1(){

    int [] arr = {0,1,0,4,0,3,2};   
    System.out.println("Lenght of array is " + arr.length);

    for(int i=0; i < arr.length; i++){

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

    for(int x = 0; x < arr.length; x++){
        System.out.println(arr[x]);
    }
}

1
你应该在这里添加你所做的事情的解释。 - bkis

0

如果问题增加以下条件:

  1. 时间复杂度必须为O(n) - 您只能迭代一次。
  2. 额外的空间复杂度必须为O(1) - 您不能创建额外的数组。

那么以下实现将正常工作。

需要遵循以下步骤:

  1. 遍历数组并维护非零元素的计数。
  2. 每当我们遇到一个非零元素时,将其放置在计数位置的数组中,并增加计数。
  3. 一旦完全遍历数组,将零放置在数组末尾,直到计数达到原始数组的长度。
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] + " ");
  }
}

0
/// <summary>
/// From a given array send al zeros to the end (C# solution)
/// </summary>
/// <param name="numbersArray">The array of numbers</param>
/// <returns>Array with zeros at the end</returns>
public static int[] SendZerosToEnd(int[] numbersArray)
{
    // Edge case if the array is null or is not long enough then we do
    // something in this case we return the same array with no changes
    // You can always decide to return an exception as well
    if (numbersArray == null ||
        numbersArray.Length < 2)
    {
        return numbersArray;
    }

    // We keep track of our second pointer and the last element index
    int secondIndex = numbersArray.Length - 2,
        lastIndex = secondIndex;

    for (int i = secondIndex; i >= 0; i--)
    {
        secondIndex = i;

        if (numbersArray[i] == 0)
        {
            // While our pointer reaches the end or the next element
            // is a zero we swap elements
            while (secondIndex != lastIndex ||
                numbersArray[secondIndex + 1] != 0)
            {
                numbersArray[secondIndex] = numbersArray[secondIndex + 1];
                numbersArray[secondIndex + 1] = 0;

                ++secondIndex;
            }
            // This solution is like having two pointers
            // Also if we look at the solution you do not pass more than 
            // 2 times actual array will be resume as O(N) complexity 
        }
    }
    // We return the same array with no new one created
    return numbersArray;
}

0

对于整数数组,它可以非常简单地表示为

Integer[] numbers = { 1, 10, 0, 5, 7 };
Arrays.sort(numbers, Comparator.comparing(n -> n == 0));

对于int数组:

int[] numbers = { 1, 10, 0, 5, 7 };
 numbers = IntStream.of(numbers).boxed()
                    .sorted(Comparator.comparing(n -> n == 0))
                    .mapToInt(i->i).toArray();

两者的输出结果均为:

[1, 10, 5, 7, 0]


0
  import java.io.*;
  import java.util.*;

  class Solution {

  public static int[] moveZerosToEnd(int[] arr) {

  int j = 0;
  for(int i = 0; i < arr.length; i++) {
    if(arr[i] != 0) {
      swap(arr, i, j);
      j++;
    }
   }
    return arr;
  }
 private static void swap(int arr[], int i, int j){
      int temp = arr[j];
      arr[j] = arr[i];
      arr[i] = temp;
   }

public static void main(String[] args) {
   int arr[] =new int[] {1, 10, 0, 2, 8, 3, 0, 0, 6, 4, 0, 5, 7, 0 };
   System.out.println(Arrays.toString(moveZerosToEnd(arr)));
  }
}

0

时间复杂度 = O(n),空间复杂度 = O(1)

import java.util.Scanner;

public class ShiftZeroesToBack {

    int[] array;
    void shiftZeroes(int[] array) {

        int previousK = 0; 
        int firstTime = 0;

        for(int k = 0; k < array.length - 1; k++) {

            if(array[k] == 0 && array[k + 1] != 0 && firstTime != 0) {
                int temp = array[previousK];
                array[previousK] = array[k + 1];
                array[k + 1] = temp;
                previousK = previousK + 1;
                continue;
            }

            if(array[k] == 0 && array[k + 1] != 0) {
               int temp = array[k];
               array[k] = array[k + 1];
               array[k + 1] = temp;
               continue;
            }

            if(array[k] == 0 && array[k + 1] == 0) {
                if(firstTime == 0) {
                    previousK = k; 
                    firstTime = 1;
                }
            }

       }
   }

   int[] input(Scanner scanner, int size) {
       array = new int[size];
       for(int i = 0; i < size; i++) {
           array[i] = scanner.nextInt();
       }
       return array;
   }

   void print() {
       System.out.println();
       for(int i = 0; i < array.length; i++) {
           System.out.print(array[i] + " ");
       }
       System.out.println();
   }

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       ShiftZeroesToBack sztb = new ShiftZeroesToBack();
       System.out.print("Enter Size of Array\t");
       int size = scanner.nextInt();
       int[] input = sztb.input(scanner, size);
       sztb.shiftZeroes(input);
       sztb.print();
   }

}

0

看一下这个函数的代码:

vector<int> Solution::solve(vector<int> &arr) {
    int count = 0;  
    for (int i = 0; i < arr.size(); i++) 
        if (arr[i] != 0) 
            arr[count++] = arr[i]; 
    while (count < arr.size()) 
        arr[count++] = 0; 
    return arr;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接