• <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()));  
        }
    }
  • 相关阅读:
    [对对子队]会议记录5.27(Scrum Meeting12)
    [对对子队]会议记录5.25(Scrum Meeting11)
    [对对子队]会议记录5.24(Scrum Meeting10)
    [对对子队]会议记录5.22(Scrum Meeting9)
    [对对子队]会议记录5.21(Scrum Meeting8)
    [对对子队]会议记录5.20(Scrum Meeting7)
    团队作业第六次——Beta冲刺日志集合
    团队作业第六次——Beta冲刺日志集合
    团队作业第五次——敏捷冲刺日志集合
    Beta冲刺答辩
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11846326.html
Copyright © 2020-2023  润新知