222. Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
解题思路
直接递归遍历所有节点,但是超时,考虑优化如下:
题目中是完全二叉树,非空节点都在左边,所以只需要在最后一层找到第一个空节点即可,使用二分法。在树中,二分法使用如下:
程序
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
int hl=1,hr=1;
TreeNode * l=root->left, *r=root->right;
while(l){hl++; l=l->left;}
while(r){hr++; r=r->right;}
if(hl==hr) return pow(2,hr)-1;
return countNodes(root->left)+countNodes(root->right)+1;
}
};
710. Random Pick with Blacklist
Given a blacklist B
containing unique integers from [0, N)
, write a function to return a uniform random integer from [0, N)
which is NOT in B
.
Optimize it such that it minimizes the call to system’s Math.random()
.
Note:
1 <= N <= 1000000000
0 <= B.length < min(100000, N)
[0, N)
does NOT include N. See interval notation.
Example 1:
Input:
["Solution","pick","pick","pick"]
[[1,[]],[],[],[]]
Output: [null,0,0,0]
Example 2:
Input:
["Solution","pick","pick","pick"]
[[2,[]],[],[],[]]
Output: [null,1,1,1]
Example 3:
Input:
["Solution","pick","pick","pick"]
[[3,[1]],[],[],[]]
Output: [null,0,0,2]
Example 4:
Input:
["Solution","pick","pick","pick"]
[[4,[2]],[],[],[]]
Output: [null,1,3,1]
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution
’s constructor has two arguments, N
and the blacklist B
. pick
has no arguments. Arguments are always wrapped with a list, even if there aren’t any.
解题思路
对黑名单blacklist
排序,复杂度为O(BlogB)
,每次取一随机数,二分搜索是否在黑名单中,正确但超时。
为提高速度,考虑使用哈希,每次查找为O(1)
;当B > N / 2
时,构造白名单,直接从白名单中随机抽取即可,构造复杂度为O(B) = O(N) since N / B <= 2
。
程序
class Solution {
private:
unordered_set<int> black;
vector<int> white;
int interval;
public:
Solution(int N, vector<int> blacklist):interval(N) {
srand(time(0));
black = unordered_set<int>(blacklist.begin(), blacklist.end());
if (black.size() > N / 2)
for (int i = 0; i < N; i++)
if (!black.count(i)) white.push_back(i);
}
int pick() {
if (white.size()) return white[rand()%white.size()];
while(1){
int a = rand() % interval;
if (!black.count(a)) return a;
}
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(N, blacklist);
* int param_1 = obj.pick();
*/