• 382. 链表随机节点


    给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。

    进阶:
    如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?

    示例:

    // 初始化一个单链表 [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()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。
    solution.getRandom();

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/linked-list-random-node
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
        ListNode *pCur,*pHead;
        int step=0;
    public:
        /** @param head The linked list's head.
            Note that the head is guaranteed to be not null, so it contains at least one node. */
        Solution(ListNode* head) {
            pCur=head;
            pHead=head;
            step=0;
            ListNode *pTmp=head;
            while(pTmp!=NULL){//get the length of the list
                step++;
                pTmp=pTmp->next;
            }
        }
        
        /** Returns a random node's value. */
        int getRandom() {
            int step_cur=rand()%step;//get a valid random step
            for(int i=0;i<step_cur;i++){
                if(pCur->next==NULL){//if meeting the end
                    pCur=pHead;//then go to the head
                }else{
                    pCur=pCur->next;//go to the next node
                }
            }
            return pCur->val;
        }
    };
    
    /**
     * Your Solution object will be instantiated and called as such:
     * Solution* obj = new Solution(head);
     * int param_1 = obj->getRandom();
     */

  • 相关阅读:
    广域网(ppp协议、HDLC协议)
    0120. Triangle (M)
    0589. N-ary Tree Preorder Traversal (E)
    0377. Combination Sum IV (M)
    1074. Number of Submatrices That Sum to Target (H)
    1209. Remove All Adjacent Duplicates in String II (M)
    0509. Fibonacci Number (E)
    0086. Partition List (M)
    0667. Beautiful Arrangement II (M)
    1302. Deepest Leaves Sum (M)
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13899596.html
Copyright © 2020-2023  润新知