1089. Duplicate Zeros

LeetCode easy original: C# #array #csharp #easy #leetcode #two-pointers
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

Дан arreglo целых чисел фиксированной длины arr, дублируйте каждое вхождение нуля, сдвигая оставшиеся elementы вправо.

Учтите, что elementы за пределами длины исходного arregloа не записываются. Внесите указанные изменения в arreglo на месте и ничего не возвращайте.

Ejemplo:

Input: arr = [1,0,2,3,0,4,5,0]

Output: [1,0,0,2,3,0,0,4]

Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

C# solución

coincidente/original
public class Solution {
    public void DuplicateZeros(int[] arr) {
        int possibleDups = 0;
        int length_ = arr.Length - 1;
        for (int left = 0; left <= length_ - possibleDups; left++) {
            if (arr[left] == 0) {
                if (left == length_ - possibleDups) {
                    arr[length_] = 0;
                    length_ -= 1;
                    break;
                }
                possibleDups++;
            }
        }
        int last = length_ - possibleDups;
        for (int i = last; i >= 0; i--) {
            if (arr[i] == 0) {
                arr[i + possibleDups] = 0;
                possibleDups--;
                arr[i + possibleDups] = 0;
            } else {
                arr[i + possibleDups] = arr[i];
            }
        }
    }
}

C++ solución

borrador automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public void DuplicateZeros(vector<int>& arr) {
        int possibleDups = 0;
        int length_ = arr.size() - 1;
        for (int left = 0; left <= length_ - possibleDups; left++) {
            if (arr[left] == 0) {
                if (left == length_ - possibleDups) {
                    arr[length_] = 0;
                    length_ -= 1;
                    break;
                }
                possibleDups++;
            }
        }
        int last = length_ - possibleDups;
        for (int i = last; i >= 0; i--) {
            if (arr[i] == 0) {
                arr[i + possibleDups] = 0;
                possibleDups--;
                arr[i + possibleDups] = 0;
            } else {
                arr[i + possibleDups] = arr[i];
            }
        }
    }
}

Java solución

borrador automático, revisar antes de enviar
import java.util.*;
import java.math.*;

// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
    public void DuplicateZeros(int[] arr) {
        int possibleDups = 0;
        int length_ = arr.length - 1;
        for (int left = 0; left <= length_ - possibleDups; left++) {
            if (arr[left] == 0) {
                if (left == length_ - possibleDups) {
                    arr[length_] = 0;
                    length_ -= 1;
                    break;
                }
                possibleDups++;
            }
        }
        int last = length_ - possibleDups;
        for (int i = last; i >= 0; i--) {
            if (arr[i] == 0) {
                arr[i + possibleDups] = 0;
                possibleDups--;
                arr[i + possibleDups] = 0;
            } else {
                arr[i + possibleDups] = arr[i];
            }
        }
    }
}

Python solución

coincidente/original
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        possibleDups = 0
        length_ = len(arr) - 1

        for left in range(length_ + 1):
            if left > length_ - possibleDups:
                break
            if arr[left] == 0:
                if left == length_ - possibleDups:
                    arr[length_] = 0
                    length_ -= 1
                    break
                possibleDups += 1

        last = length_ - possibleDups

        for i in range(last, -1, -1):
            if arr[i] == 0:
                arr[i + possibleDups] = 0
                possibleDups -= 1
                arr[i + possibleDups] = 0
            else:
                arr[i + possibleDups] = arr[i]

Go solución

coincidente/original
func duplicateZeros(arr []int) {
    possibleDups := 0
    length_ := len(arr) - 1

    for left := 0; left <= length_ - possibleDups; left++ {
        if arr[left] == 0 {
            if left == length_ - possibleDups {
                arr[length_] = 0
                length_--
                break
            }
            possibleDups++
        }
    }

    last := length_ - possibleDups

    for i := last; i >= 0; i-- {
        if arr[i] == 0 {
            arr[i + possibleDups] = 0
            possibleDups--
            arr[i + possibleDups] = 0
        } else {
            arr[i + possibleDups] = arr[i]
        }
    }
}

Algorithm

find количество нулей, которые будут продублированы, назовем это possible_dups. Необходимо убедиться, что мы не считаем нули, которые будут отброшены, так как отброшенные нули не будут частью итогового arregloа. Количество possible_dups даст нам количество elementов, которые будут отброшены из исходного arregloа. В любой момент времени length_ - possible_dups — это количество elementов, которые будут включены в итоговый arreglo.

Обработайте крайний случай для нуля, находящегося на границе оставшихся elementов. Будьте особенно внимательны при дублировании нулей в оставшемся arregloе. Следует учитывать, лежит ли ноль на границе. Этот ноль может быть учтен с возможными дубликатами или может быть просто включен в оставшиеся elementы, когда не осталось места для его дубликата. Если он является частью possible_dups, мы хотим его дублировать, в противном случае — нет.

Итерируйте arreglo с конца и копируйте ненулевой element один раз, а нулевой element дважды. Когда мы говорим об отбрасывании лишних elementов, это означает, что мы начинаем с левой стороны лишних elementов и начинаем перезаписывать их новыми значениями, в конечном итоге сдвигая оставшиеся elementы вправо и создавая пространство для всех дублированных elementов в arregloе.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.