首页 > 其他 > 详细

382. Linked List Random Node

时间:2016-08-21 06:26:03      阅读:300      评论:0      收藏:0      [点我收藏+]
     /*
      * 382. Linked List Random Node
      * 2016-8-20 by Mingyang
      * 直接进行长度计算就好了,再根据随机数,便利到指定的位置找到结果
      */
     class Solution {
            int len = 0;
            ListNode head;
            /** @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;
                ListNode cur = head;
                while(cur!=null){
                    len++;
                    cur = cur.next;
                }
            }
            
            /** Returns a random node‘s value. */
            public int getRandom() {
                int r = (int)(Math.random() * len);
                ListNode cur = head;
                while(r > 0){
                    cur = cur.next;
                    r--;
                }
                return cur.val;
            }
        }

 

382. Linked List Random Node

原文:http://www.cnblogs.com/zmyvszk/p/5792053.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!