如上图所示,如果快排每次选的节点恰好为中间节点,也就是二叉树是平衡的,那么二叉树的深度为 log(n+1) ,而在遍历每一层的时候,n个节点都会访问到。如上图 B 和 C 节点,虽然递归后不是一次访问n个节点,B 和 C 两次递归加起来就是总的节点个数n,一共有 log(n+1) 层,所以其时间复杂度为 O(n*log(n+1)) = O(nlogn)
publicintpartition(int[] nums, int begin, int end){ int tmp_value = nums[begin]; while(begin<end) { while(begin<end && nums[end]>=tmp_value) end -= 1; if(begin < end) nums[begin] = nums[end]; while(begin<end && nums[begin]<=tmp_value) begin += 1; if(begin < end) nums[end] = nums[begin]; } nums[begin] = tmp_value; return begin; }
publicintmajorityElement(int[] nums){ int index = 0, begin = 0, end = nums.length-1; while(index!=nums.length/2) { index = partition(nums, begin, end); if(index>nums.length/2) end = index-1; elseif(index<nums.length/2) begin = index+1; } return nums[index]; }
Design a data structure that supports all following operations in average O(1) time. 1. insert(val): Inserts an item val to the set if not already present. 2. remove(val): Removes an item val from the set if present. 3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
/** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
// Initialize your data structure here. publicRandomizedSet(){ map = new HashMap(); list = new ArrayList(); } // Inserts a value to the set. // Returns true if the set did not already contain the specified element. publicbooleaninsert(int val){ if(map.putIfAbsent(val, list.size())==null) { list.add(val); returntrue; } returnfalse; } // Removes a value from the set. // Returns true if the set contained the specified element. publicbooleanremove(int val){ int index = map.getOrDefault(val, Integer.MAX_VALUE); if(index==Integer.MAX_VALUE) returnfalse; else { map.remove(val); if(index<list.size()-1) { // 用list中的最后一个元素替换该位置的值 list.set(index, list.get(list.size()-1)); // 改变map中该元素对应的value值,即其在list中的索引 map.put(list.get(list.size()-1), index); } list.remove(list.size()-1); // 删除list中的最后一个元素 returntrue; } } // Get a random element from the set. publicintgetRandom(){ int p = (int)(Math.random()*(list.size())); return list.get(p); } }
Note: Duplicate elements are allowed. 1. insert(val): Inserts an item val to the collection. 2. remove(val): Removes an item val from the collection if present. 3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.