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:28
     public static void main(String[] args) {
            Integer a[] = {10,0,0,0,6,0,0,0,70,6,7,8,0,4,0};
            int flag = 0;int count =0;
                for(int i=0;i<a.length;i++) {
                if(a[i]==0 ) {
                    flag=1;
                    count++;
                }else if(a[i]!=0) {
                    flag=0;
                }
                if(flag==0 && count>0 && a[i]!=0) {
                    a[i-count] = a[i];
                    a[i]=0;
                }
            }
}
查看更多
劳资没心,怎么记你
3楼-- · 2020-02-26 02:28

For Integer array it can be as simple as

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

For int array :

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

Output of both:

[1, 10, 5, 7, 0]

查看更多
劫难
4楼-- · 2020-02-26 02:29
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++;
    }
}

Since the array of int's is initialized to zero(according to the language spec). this will have the effect you want, and will move everything else up sequentially.

Edit: Based on your edit that you cannot use a new array this answer doesnt cover your requirements. You would instead need to check for a zero(starting at the end of the array and working to the start) and swap with the last element of the array and then decrease the index of your last-nonzero element that you would then swap with next. Ex:

int lastZero = arr.length - 1;
if(arr[i] == 0){
  //perform swap and decrement lastZero by 1 I will leave this part up to you
}
查看更多
SAY GOODBYE
5楼-- · 2020-02-26 02:30

This is One method of Moving the zeroes to the end of the array.

public class SeparateZeroes1  {

    public static void main(String[] args) {

        int[] a = {0,1,0,3,0,0,345,12,0,13};

        movezeroes(a);      
    }

    static void movezeroes(int[] a) {
        int lastNonZeroIndex = 0;
     // If the current element is not 0, then we need to
        // append it just in front of last non 0 element we found.
    for (int i = 0; i < a.length; i++) {
        if (a[i]  != 0 ) {
            a[lastNonZeroIndex++] = a[i];
        }
    }//for


    // We just need to fill remaining array with 0's.
    for (int i = lastNonZeroIndex; i < a.length; i++) {
        a[i] = 0;
    }   
   System.out.println( lastNonZeroIndex         );
 System.out.println(Arrays.toString(a));

    }
}

This is very simple in Python. We will do it with list comprehension

a =[0,1,0,3,0,0,345,12,0,13]
def fix(a):
    return ([x for x in a if x != 0] + [x for x in a if x ==0])

print(fix(a))
查看更多
够拽才男人
6楼-- · 2020-02-26 02:32

Basic solution is to establish an inductive hypothesis that the subarray can be kept solved. Then extend the subarray by one element and maintain the hypothesis. In that case there are two branches - if next element is zero, do nothing. If next element is non-zero, swap it with the first zero in the row.

Anyway, the solution (in C# though) after this idea is optimized looks like this:

void MoveZeros(int[] a)
{

    int i = 0;

    for (int j = 0; j < a.Length; j++)
        if (a[j] != 0)
            a[i++] = a[j];

    while (i < a.Length)
        a[i++] = 0;

}

There is a bit of thinking that leads to this solution, starting from the inductive solution which can be formally proven correct. If you're interested, the whole analysis is here: Moving Zero Values to the End of the Array

查看更多
We Are One
7楼-- · 2020-02-26 02:32

let's say we have an array

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

Let's assume we have array elements between 0-100, now our goal is to move all 0's at the end of the array. now hold 0 from the array and check it with non zero element if any non zero element found swap with that element and so on, at the end of the loop we will find the solution.

here is the code

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]....
}

output:

[5,4,6,7,8,9,0,0,0]
查看更多
登录 后发表回答