Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
LeetCode Javascript - Remove Duplicates from a Sorted Array - Return Array issue

LeetCode problem 26 - Remove Duplicates From Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

var removeDuplicates = function (nums) {
    // Iterating the full array
    for (let i = 0; i < nums.length; i++) {
        // Checking for the repeating number
        if (nums[i] === nums[i + 1]) {
            // Removing the element which is repeating
            nums = nums.slice(0, i + 1).concat(nums.slice(i + 2));
            // Resetting the index after removing the element
            i--;
        }
    }
    console.log(nums);
    return nums.length;
};

console.log(removeDuplicates([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4]));

This is the output of the above JS code on Visual Studio Code.

I am not able to submit this code to LeetCode. The expected output is the edited nums array, whereas my output doesn't match. How do I resolve this issue?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your solution is too complicated. To remove duplicates from an array, just do:

const removeDuplicates = (arr) => [...new Set(arr)]

console.log(removeDuplicates([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4]));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda