Em Java, como mover todos os 0s para o final do array, preservando a ordem de um array? [2 maneiras]
Publicados: 2020-12-31![Em Java, como mover todos os 0s para o final do array, preservando a ordem de um array? [2 maneiras]](/uploads/article/578/Jg7tpgI3lsELLLkN.png)
Eu tenho jogado com um problema de moving all 0's to end
de Arrays em diferentes entrevistas em várias combinações. Às vezes peço para mover todos os 0 para a frente do array, ordenando um array sem nenhuma estrutura de dados e assim por diante.
Neste tutorial, veremos um exemplo simples de mover todos os 0's para terminar preservando a ordem de um Array. Existem duas abordagens.
Abordagem-1)
Lógica de particionamento QuickSort. O que é Ponto de Pivô?
- O
Pivot point
é um elemento-chave no algoritmo de classificação rápida. Ele executa e particiona a coleção em torno do ponto de pivô. - Ele organiza um Array elementos maiores do que o pivô estão antes dele e os elementos maiores do que o pivô estão depois dele.
- Continue pelo loop para classificar uma matriz
A lógica é muito simples:
- Iterar através de um Array.
- Se array[i] não for igual a 0, troque-o pelo índice atual.
- Se array[i] == 0, simplesmente pule o loop
- No nosso caso
0 is a Pivot point
. - Cada vez que encontramos 0, o contra-pivô será incrementado e o elemento será movido antes do ponto de pivô.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private static void approach1 ( int [ ] crunchifyData ) { // Move 0 to end of array int j = 0 ; for ( int i = 0 ; i < crunchifyData . length ; i ++ ) { if ( crunchifyData [ i ] ! = 0 ) { int temp = crunchifyData [ j ] ; crunchifyData [ j ] = crunchifyData [ i ] ; crunchifyData [ i ] = temp ; j ++ ; } } log ( "\n\nApproach-1 Result: " + Arrays . toString ( crunchifyData ) ) ; } |
Abordagem-2)
- Crie um novo array com o mesmo tamanho
- Iterar através de um Array e pular a adição de 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private static void approach2 ( int [ ] crunchifyData ) { int [ ] num = new int [ crunchifyData . length ] ; int j = 0 ; for ( int i = 0 ; i < crunchifyData . length ; i ++ ) { if ( crunchifyData [ i ] ! = 0 ) { num [ i - j ] = crunchifyData [ i ] ; } else { j ++ ; } } System . out . print ( "\n\nApproach-2 Result: " + Arrays . toString ( num ) ) ; } |
Aqui está um Programa Completo:
CrunchifyMoveAll0ToEnd.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
package crunchify . com . java . tutorials ; import java . util . Arrays ; /** * @author Crunchify.com * Requirement: Move all 0's to end of array preserving order * Input array: 8 8 3 0 4 0 6 0 9 1 * Output array: 8 8 3 4 6 9 1 0 0 0 */ public class CrunchifyMoveAll0ToEnd { public static void main ( String [ ] args ) { int [ ] crunchifyData ; crunchifyData = new int [ ] { 8 , 8 , 3 , 0 , 4 , 0 , 6 , 0 , 9 , 1 } ; log ( "Original array: " + Arrays . toString ( crunchifyData ) ) ; if ( crunchifyData == null | | crunchifyData . length == 0 ) { log ( "Empty Array" ) ; } approach1 ( crunchifyData ) ; approach2 ( crunchifyData ) ; } private static void approach1 ( int [ ] crunchifyData ) { // Move 0 to end of array int j = 0 ; for ( int i = 0 ; i < crunchifyData . length ; i ++ ) { if ( crunchifyData [ i ] ! = 0 ) { int temp = crunchifyData [ j ] ; crunchifyData [ j ] = crunchifyData [ i ] ; crunchifyData [ i ] = temp ; j ++ ; } } log ( "\n\nApproach-1 Result: " + Arrays . toString ( crunchifyData ) ) ; } // Create a new array with same size // Iterate through an Array and skip adding 0 private static void approach2 ( int [ ] crunchifyData ) { int [ ] num = new int [ crunchifyData . length ] ; int j = 0 ; for ( int i = 0 ; i < crunchifyData . length ; i ++ ) { if ( crunchifyData [ i ] ! = 0 ) { num [ i - j ] = crunchifyData [ i ] ; } else { j ++ ; } } System . out . print ( "\n\nApproach-2 Result: " + Arrays . toString ( num ) ) ; } private static void log ( String string ) { System . out . print ( string + " " ) ; } } |
Saída do console do Eclipse:
1 2 3 4 5 6 |
Original array : [ 8 , 8 , 3 , 0 , 4 , 0 , 6 , 0 , 9 , 1 ] Approach - 1 Result : [ 8 , 8 , 3 , 4 , 6 , 9 , 1 , 0 , 0 , 0 ] Approach - 2 Result : [ 8 , 8 , 3 , 4 , 6 , 9 , 1 , 0 , 0 , 0 ] Process finished with exit code 0 |
Deixe-me saber se você conhece melhor maneira de resolver este problema. Eu adoraria ouvir seus pensamentos.
