DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

1 1

HackerRank #37 | List | 🇧🇷

Este exercício pede para fazermos e manipularmos uma List.

O primeiro input (n) denota a quantidade de elementos dentro de um array. Depois, incluímos um a um desses elementos.

A terceira linha recebe um número (q) que guiará a quantidade de Inserts ou Deletes que faremos dentro da List.

Depois, faremos as modificações para substituir ou remover elementos do array. x denota a posição do elemento que será deletado e y denota o número de substituição que entrará em seu lugar.

De forma ilustrada:

Alt Text

O passo a passo é o seguinte:

  • Escanear o primeiro input
  • Fazer uma nova lista, sempre respeitando a boa prática de fazer mais abstrata possível. Nesse caso ficou: List<Integer> lista = new ArrayList<>();
  • Fazer um for que adiciona, a partir de um scanner, os elementos na lista.
  • Declarar q, x, y e z fora do for, sendo que q também precisa ser escaneado.
  • Fazer um segundo for que recebe uma String que pode ser Insert ou Delete
  • Para a string Insert, recebemos dois ints: x e y. Utilizamos o método .add(), que já faz a substituição.
  • Caso contrário (ou seja, com Delete), recebemos apenas z. Utilizamos o método .remove(), que remove o elemento a partir do número da posição dele.

O código final fica assim, dentro da main:

        Scanner scanner = new Scanner(System.in));
        int n = scanner.nextInt();
        List<Integer> lista = new ArrayList<>();

        for (int i = 0; i < n; i++){
            lista.add(scanner.nextInt());
        }

        int q = scanner.nextInt();
        int x = 0;
        int y = 0;
        int z = 0;

        for (int j = 0; j < q; j++){
            String string = scanner.next();

            if (string.equals("Insert")){
                x = scanner.nextInt();
                y = scanner.nextInt();

                lista.add(x, y);
            } else {
                z = scanner.nextInt();

                lista.remove(z);
            }
        }

        scanner.close();

        for (int h = 0; h < lista.size(); h++){
            System.out.print(lista.get(h) + " ");
        }

Enter fullscreen mode Exit fullscreen mode

=========

Referências

List : Oracle
Java Colletions: Set, list e iterator : DevMedia

============

Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa:

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.