3

LeetCode medium original: C# #array #backtracking #csharp #leetcode #medium
Task text is translated from Russian for the selected interface language. Code is left unchanged.

98. Random Pick Index

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

Example:

Input

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

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

Output

[null, 4, 0, 2]

C# solution

matched/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++ solution

auto-draft, review before submit
#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 solution

auto-draft, review before submit
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

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

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

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

😎

Vacancies for this task

Active vacancies with overlapping task tags are shown.

All vacancies
There are no active vacancies yet.