码迷,mamicode.com
首页 > 其他好文 > 详细

<Random>382 380

时间:2019-11-13 09:16:41      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:lis   null   integer   public   solution   lin   bool   class   last   

382. Linked List Random Node

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

 

380. Insert Delete GetRandom O(1)

class RandomizedSet {
    ArrayList<Integer> nums;
    HashMap<Integer, Integer> locs;
    Random rand = new Random();
    /** Initialize your data structure here. */
    public RandomizedSet() {
        nums = new ArrayList<Integer>();
        locs = new HashMap<Integer, Integer>();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        boolean contain = locs.containKey(val);
        if( contain ) return false;
        locs.put(val, nums.size());
        nums.add(val);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        boolean contain = locs.containKey(val);
        if( !contain ) return false;
        int loc = locs.get(val);
        if(loc < nums.size() - 1){// not the last one than swap the last one with this val
            int lastOneVal = nums.get(nums.size() - 1);
            nums.set(loc, lastOneVal);
            locs.put(lastOneVal, loc);
        }
        locs.remove(val);
        nums.remove(nums.size() - 1);
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        retrn nums.get(rand.nextInt(num.size()));  
    }
}

 

<Random>382 380

标签:lis   null   integer   public   solution   lin   bool   class   last   

原文地址:https://www.cnblogs.com/Afei-1123/p/11846326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!