zoukankan      html  css  js  c++  java
  • <Random>382 380

    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()));  
        }
    }
  • 相关阅读:
    android入门之三【应用程序组成】
    Palm应用开发之一开发环境搭建
    android 入门之一【开发环境搭建】
    在DataGridView中的CheckBox值变更后立即获取值。
    根据字符串返回类型
    CSS模拟不同的拐角效果
    SQL查询生成交叉列表
    LinkButton 的 OnClick 事件 可以是一个方法
    代替marquee的滚动字幕效果代码
    JavaScript实现DataGrid中添加CheckBox列(全选与否)
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11846326.html
Copyright © 2011-2022 走看看