Reservoir Samplings

Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

思路
蓄水池原理

  1. 從頭到尾遍歷鏈表
  2. 在遍歷1~i個結(jié)點時,直接放進結(jié)果集
  3. 遍歷到第k(k > i)個結(jié)點時团甲,以i/k的概率決定是否將結(jié)點i放進結(jié)果集逾冬。如果不放,直接忽略躺苦。如果放身腻,就從結(jié)果集的i個結(jié)點中隨機取出一個,替換為結(jié)點k
  4. 重復3匹厘,一直到尾節(jié)點霸株。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    ListNode head = null;

    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    public Solution(ListNode head) {
        this.head = head;
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        ListNode result = this.head;
        ListNode curNode = this.head;
        Random random = new Random();
        
        for (int i = 1; curNode != null; i++) {
            if (random.nextInt(i) == i - 1) {
                result = curNode;
            }
            curNode = curNode.next;
        }
        return result.val;
    }
}
/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */

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.

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:

int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);

// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);

// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);

思路
Use random to ensure equal possibility, key point is save extra space.

  1. Create arraylist to store all index of target, and count total.
  2. Then use random from [0,total), to equally pick any element in the array.

Complexity: O(N)time O(m)space - # of target in nuts

class Solution {
    private int[] nums;

    public Solution(int[] nums) {
        this.nums = nums;
    }
    
    public int pick(int target) {
        List<Integer> list = new ArrayList<Integer>();
        int count = 0;
        int result = -1;
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                count++;
                list.add(i);
            }
        }
        
        Random random = new Random();
        result = list.get(random.nextInt(count));
        return result;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市集乔,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌坡椒,老刑警劉巖扰路,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異倔叼,居然都是意外死亡汗唱,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進店門丈攒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哩罪,“玉大人,你說我怎么就攤上這事巡验〖什澹” “怎么了?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵显设,是天一觀的道長框弛。 經(jīng)常有香客問我,道長捕捂,這世上最難降的妖魔是什么瑟枫? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮指攒,結(jié)果婚禮上慷妙,老公的妹妹穿的比我還像新娘。我一直安慰自己允悦,他們只是感情好膝擂,可當我...
    茶點故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般猿挚。 火紅的嫁衣襯著肌膚如雪咐旧。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天绩蜻,我揣著相機與錄音铣墨,去河邊找鬼。 笑死办绝,一個胖子當著我的面吹牛伊约,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播孕蝉,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼屡律,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了降淮?” 一聲冷哼從身側(cè)響起超埋,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎佳鳖,沒想到半個月后霍殴,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡系吩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年来庭,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片穿挨。...
    茶點故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡月弛,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出科盛,到底是詐尸還是另有隱情帽衙,我是刑警寧澤,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布贞绵,位于F島的核電站佛寿,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏但壮。R本人自食惡果不足惜冀泻,卻給世界環(huán)境...
    茶點故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蜡饵。 院中可真熱鬧弹渔,春花似錦、人聲如沸溯祸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至博杖,卻和暖如春椿胯,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背剃根。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工哩盲, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人狈醉。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓廉油,卻偏偏與公主長得像,于是被迫代替她去往敵國和親苗傅。 傳聞我的和親對象是個殘疾皇子抒线,可洞房花燭夜當晚...
    茶點故事閱讀 45,876評論 2 361

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,748評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,586評論 0 23
  • 投資風險難自持 輸贏參半未可知 錢去財往平常事 卷土重來犟女子
    紅色陽光閱讀 451評論 0 1
  • (5) “你還是什么都不說嗎渣慕?”丁仁語氣嚴厲嘶炭。 李博低著頭,默不作聲逊桦。 “這個你總認識吧眨猎?”李博看到丁...
    紫蘇卡卡閱讀 219評論 0 1
  • 經(jīng)歷了一些事情,好的卫袒,壞的,成功了单匣,會激動夕凝,失敗了,會痛苦户秤,迷茫码秉,有時候想的很多,想的頭疼鸡号,不說話转砖,會壓抑,說多了...
    徐偉_快樂505閱讀 358評論 0 0