【Leetcode】Linked List Random Node

题目链接:https://leetcode.com/problems/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();

思路:

链表中随即选取一个数,直接的想法:先计算链表长度len,获取[1,len]范围内的随机数作为随机到节点的下标,遍历链表获得节点值。

考虑follow up,不确定链表长度的情况下,上述做法第一步就做不了,看了tag 是 Reservoir Sampling,搜索了一下,原来这种算法解决的就是:

在不确定范围的情况下获取随机数。    参考该算法http://blog.csdn.net/yeqiuzs/article/details/52169369很容易ac了。

算法:

    ListNode head = null;
    /** @param head The linked list's head. Note that the head is guanranteed 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() {
        int choice = -1;
        int idx = 0;
        ListNode p = head;
        java.util.Random r = new java.util.Random();
        while(p!=null){
            idx++;
            int rn = r.nextInt(idx);
            if(rn==idx-1){
                choice = p.val;
            }
            p = p.next;

        }
        return choice;
    }
时间: 2024-10-12 12:24:31

【Leetcode】Linked List Random Node的相关文章

【Leetcode】Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up: Can you solve it without using extra space? 思路:由[Leetcode]Linked List Cycle可知,利用一快一慢两个指针能够判断出链表是否存在环路.假设两个指针相遇之前slow走了s步,则fast走了2s步,并且fast已经在长度

【leetcode】Linked List Cycle (python)

题目分析见这里 class Solution: # @param head, a ListNode # @return a list node def detectCycle(self, head): if None == head or None == head.next: return None pfast = head pslow = head #找第一次相遇的点,若存在环路,则肯定会相遇 while pfast and pfast.next: pfast = pfast.next.nex

【LeetCode】Linked List Cycle

Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space? 做完Linked List Cycle II在做这题简直就是阉割版.. fast每次前进两步,slow每次前进一步,如果相遇则为true,否则false class Solution { public: bool hasCycle(ListNo

[LeetCode] 382. Linked List Random Node

https://leetcode.com/problems/linked-list-random-node /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { List<ListNode> array = new ArrayList&l

【leetcode】Linked List Cycle II (middle)

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up:Can you solve it without using extra space? 思路: 做过,就当复习了. 先用快慢指针判断相交,关键是环开始点的获取. 用上图说明一下,设非环的部分长度为a(包括环的入口点), 环的长度为b(包括环的入口点). 快慢指针相交的位置为绿色的点,距离

【LeetCode】 19. Remove Nth Node From End of List 解题小结

题目: Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. 首先容易想到的是

【LeetCode】19. Remove Nth Node From End of List

题目: 思路:如果链表为空或者n小于1,直接返回即可,否则,让链表从头走到尾,每移动一步,让n减1. 1.链表1->2->3,n=4,不存在倒数第四个节点,返回整个链表 扫过的节点依次:1-2-3 n值得变化:3-2-1 2.链表1->2->3,n=3 扫过的节点依次:1-2-3 n值得变化:2-1-0 3.链表1->2->3,n=2 扫过的节点依次:1-2-3 n值得变化:1-0--1 当走到链表结尾时:1.n>0,说明链表根本没有第n个节点,直接返回原链表:

【LeetCode】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 the list. 思路:第一遍正常复制链表,同时用哈希表保存链表中原始节点和新节点的对应关系,第二遍遍历链表的时候,再复制随机域. 这是一种典型的空间换时间的做法,n个节点,需要大小为O(n

【LeetCode】链表 linked list(共34题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [2]Add Two Numbers (2018年11月30日,第一次review,ko) 两个链表,代表两个整数的逆序,返回一个链表,代表两个整数相加和的逆序. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 =