LeetCode 398 Random Pick Index(蓄水池抽樣典型例題)
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
就是說 給出一個array, 裡面有Integers,可以帶有重複。現在我們給定一個target,讓隨機輸出array裡面值等於target的元素對應的target.當然,如果只有這一個值等於target的元素的話,就直接返回這個index,但是如果有多個的話 就隨機返回一個。
要注意,我們保證一定存在這個target.
同時也要注意:array的size可能很大 在解題過程中不要用太多的額外空間。
class Solution {
public Solution(int[] nums) {
}
public int pick(int target) {
}
}
idea:
the initial idea will be just get all the value and it’s index, and we are gonna randomly pick one of them.
so we can choose HashMap<Integer, List< Integer >> map: key: value value: list of indexes.
but array.size() maybe huge and the new hashmap will take too much space.
so can we don’t do any preprocess, and each time we pick it, we iterate num and get all the indexes and randomly get one from them.
but there comes another thing: the size of this array is large, and since we gonna use pick() for many times, so that will be bad in time complexity too.
Actually, after saw the solution, I realized that it is a reservoir sampling
class Solution {
int[] nums;
Random rand;
int N;
public Solution(int[] nums) {
this.nums = nums; //同名的一定要用nums不然會出現null pointer的錯誤
N = nums.length;
rand = new Random();
}
public int pick(int target) {
int count = 0;
int res = 0;
for (int i = 0; i < N; i++) {
if (nums[i] != target) {
continue;
} else {
count++;
int random = rand.nextInt() % count;
if (random == 0) {
res = i;
}
}
}
return res;
}
}
相關文章
- [LeetCode] 528. Random Pick with WeightLeetCoderandom
- C# 蓄水池抽樣C#
- 2020.12.21-2020.12.27 leetcode刷題總結(拓撲排序&蓄水池抽樣&二叉搜尋樹&線段樹)LeetCode排序
- 前端面試典型例題前端面試
- 【資料結構與演算法】蓄水池抽樣演算法(Reservoir Sampling)資料結構演算法
- 用Python寫演算法 | 蓄水池演算法實現隨機抽樣Python演算法隨機
- LeetCode398-隨機數索引LeetCode隨機索引
- leetcode 1082典型題 ,開窗函式LeetCode函式
- 12 random案例 年會抽獎案例random
- 利用jstack定位典型效能問題例項JS
- LeetCode 382 Linked List Random NodeLeetCoderandom
- LeetCode 138. Copy List with Random PointerLeetCoderandom
- [LeetCode] 274. H-IndexLeetCodeIndex
- [LeetCode] 724. Find Pivot IndexLeetCodeIndex
- 滑動視窗法——Leetcode例題LeetCode
- **【求助】關於抽樣和標準化的問題**
- [LeetCode] 852. Peak Index in a Mountain ArrayLeetCodeIndexAI
- dfs題目這樣去接題,秒殺leetcode題目LeetCode
- 【mysql】SUBSTRING_INDEX 用法舉例MySqlIndex
- 抽樣之逆轉換方法
- 水庫抽樣演算法演算法
- numpy2.隨機抽樣隨機
- 關於《完全手冊Excel VBA典型例項大全——透過368個例子掌握》隨書樣例的下載Excel
- 阿里媽媽給出了什麼樣的賽題,被頂會NeurIPS 2024 pick了?阿里
- [LeetCode] 2903. Find Indices With Index and Value Difference ILeetCodeIndex
- 50個典型電路例項詳解
- ORACLE統計抽樣預設比例Oracle
- [Hive]Hive實現抽樣查詢Hive
- 小笨的蓄水池
- 蓄水池演算法演算法
- enq: TX - index contention故障修復一例ENQIndex
- 微信小程式pick元件使用問題總結微信小程式元件
- 面試題抽答(補充)面試題
- MCMC 、抽樣演算法與軟體實現演算法
- MaxComputeTunnel上傳典型問題場景
- git cherry-pickGit
- PHP+jQuery開發簡單的翻牌抽獎例項PHPjQuery
- HTML入門(樣例)HTML