LeetCode.382. 链表随机节点

23 篇文章 0 订阅
13 篇文章 0 订阅

LeetCode.382. 链表随机节点

 

 方法一:动态整数数组

Java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    List<Integer> list;
    Random random;
    public Solution(ListNode head) {
        list = new ArrayList<>();
        ListNode cur = head;
        random = new Random();
        while (cur != null) {
            list.add(cur.val);
            cur = cur.next;
        }
    }
    
    public int getRandom() {
        return list.get(random.nextInt(list.size()));
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */

复杂度分析

  • 时间复杂度:初始化为 O(n),随机选择为 O(1),其中 nn 是链表的元素个数。
  • 空间复杂度:O(n)。我们需要 O(n) 的空间存储链表中的所有元素。

 

方法二:水塘抽样

class Solution {
    ListNode head;
    Random random;
    public Solution(ListNode head) {
        this.head = head;
        random  = new Random();
    }
    
    public int getRandom() {
        int ans = 0, i = 1;
        for (ListNode node = head; node != null; node = node.next) {
            if (random.nextInt(i) == 0) {
                ans = node.val;
            }
            i++;
        }
        return ans;
    }
}

复杂度分析

  • 时间复杂度:初始化为 O(1),随机选择为 O(n),其中 n 是链表的元素个数。
  • 空间复杂度:O(1)。我们只需要常数的空间保存若干变量。

终于放假啦,开始寒假的学习啦!!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值