3

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

98. Random Pick Index

Из целочисленного arregloа nums с возможными дубликатами случайным образом выведите индекс заданного целевого числа. Можно предположить, что заданное целевое number должно существовать в arregloе. Implementación класса Solution: Solution(int[] nums) Инициализирует объект с arregloом nums. int pick(int target) Выбирает случайный индекс i из nums, где nums[i] == target. Если существует несколько допустимых i, то каждый индекс должен иметь равную вероятность возврата.

Ejemplo:

Input

["Solution", "pick", "pick", "pick"]

[[[1, 2, 3, 3, 3]], [3], [1], [3]]

Output

[null, 4, 0, 2]

C# solución

coincidente/original
public class Solution {
    private int[] nums;
    private Random random;
    public Solution(int[] nums) {
        this.nums = nums;
        this.random = new Random();
    }
    public int Pick(int target) {
        int count = 0;
        int result = -1;
        for (int i = 0; i < nums.Length; i++) {
            if (nums[i] == target) {
                count++;
                if (random.Next(count) == count - 1) {
                    result = i;
                }
            }
        }
        return result;
    }
}

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:
    private vector<int>& nums;
    private Random random;
    public Solution(vector<int>& nums) {
        this.nums = nums;
        this.random = new Random();
    }
    public int Pick(int target) {
        int count = 0;
        int result = -1;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == target) {
                count++;
                if (random.Next(count) == count - 1) {
                    result = i;
                }
            }
        }
        return result;
    }
}

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 {
    private int[] nums;
    private Random random;
    public Solution(int[] nums) {
        this.nums = nums;
        this.random = new Random();
    }
    public int Pick(int target) {
        int count = 0;
        int result = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                count++;
                if (random.Next(count) == count - 1) {
                    result = i;
                }
            }
        }
        return result;
    }
}

Algorithm

Инициализируйте объект с arregloом nums. Сохраните этот arreglo для дальнейшего использования.

Реализуйте метод pick(target), который выбирает случайный индекс i из arregloа nums, где nums[i] равен target. Если таких индексов несколько, каждый из них должен иметь равную вероятность быть выбранным.

Для реализации метода pick используйте Algoritmo reservoir sampling для выбора случайного индекса.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.