国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] 382. Linked List Random Node

崔曉明 / 811人閱讀

Problem

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();

Solution
class Solution {

    /** @param head The linked list"s head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    ListNode head;
    Random random;
    public Solution(ListNode head) {
        this.head = head;
        random = new Random();
    }
    
    /** Returns a random node"s value. */
    public int getRandom() {
        ListNode cur = head;
        int res = cur.val, count = 1;
        while (cur.next != null) {
            cur = cur.next;
            if (random.nextInt(count+1) == count) {
                res = cur.val;
            }
            count++;
        }
        return res;
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72335.html

相關文章

  • leetcode382. Linked List Random Node

    摘要:題目要求要求從單鏈表中,隨機返回一個節點的值,要求每個節點被選中的概率是相等的。假如一共有個物品,需要從其中挑選出個物品,要求確保個物品中每個物品都能夠被等概率選中。對于這種等概率問題,簡答的做法是通過隨機數獲取選中物品的下標。 題目要求 Given a singly linked list, return a random nodes value from the linked li...

    xiaodao 評論0 收藏0
  • LeetCode[138] Copy List with Random Pointer

    LeetCode[138] Copy List with Random Pointer A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of t...

    novo 評論0 收藏0
  • [LintCode/LeetCode] Copy List with Random Pointer

    摘要:大體意思就是,先復制到,順便將所有的放在再復制所有的到,順便將所有的放在最后令,令,將和分離,返回的頭結點 Problem A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. ...

    Jacendfeng 評論0 收藏0
  • [Leetcode] Copy List with Random Pointer 復制隨機指針

    摘要:棧迭代復雜度時間空間如果不算新鏈表的空間則是思路由于隨機指針有可能產生環路,我們不能直接沿著隨機指針的方向一個一個復制。同時我們又不能沿著指針直接復制,因為我們不知道隨機指針所指向的新節點是哪個。 Copy List with Random Pointer A linked list is given such that each node contains an additiona...

    Olivia 評論0 收藏0
  • LeetCode 138:復制帶隨機指針的鏈表 Copy List with Random Poin

    摘要:給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。要求返回這個鏈表的深拷貝。提示你必須返回給定頭的拷貝作為對克隆列表的引用。確定隨機節點的關系之后再拆分鏈表。其時間復雜度為,空間復雜度為。 給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。 要求返回這個鏈表的深拷貝。 A linked list is g...

    entner 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<