classSolution { public: intfindLeastNumOfUniqueInts(vector<int>& arr, int k){ unordered_map<int,int> count; for (int i : arr) { ++count[i]; } vector<int> frequence; frequence.reserve(count.size()); for (constauto& p : count) { frequence.push_back(p.second); } sort(frequence.begin(), frequence.end()); int i = 0; constint n = frequence.size(); if (i == k) return n; for (int j = 0; j < frequence.size(); ++j) { i += frequence[j]; if (i == k) { return n - j - 1; } elseif (i > k) { return n - j; } } return0; } };
classSolution { public: intminDays(vector<int>& bloomDay, int m, int k){ auto determine = [&](int x) -> bool { int sub = 0; int ans = 0; for (int i : bloomDay) { if (i <= x) { ++sub; } else { ans += sub / k; sub = 0; } } ans += sub / k; return ans >= m; }; int lo = 1, hi = 1e9 + 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (determine(mid)) { hi = mid; } else { lo = mid + 1; } } return lo > 1e9 ? -1 : lo; } };
classTreeAncestor { vector<vector<int>> ancestors; public: TreeAncestor(int n, vector<int>& parent) { // time: N * log N vector<vector<int>> children(n); for (int i = 1; i < n; ++i) { children[parent[i]].push_back(i); } ancestors.resize(n); function<void(int,vector<int>&)> dfs = [&](int root, vector<int>& path) -> void { int depth = path.size(); for (int i = 0; depth - (1 << i) >= 0; ++i) { ancestors[root].push_back(path[depth - (1 << i)]); } path.push_back(root); for (int child : children[root]) { dfs(child, path); } path.pop_back(); }; vector<int> path; path.push_back(-1); dfs(0, path); } intgetKthAncestor(int node, int k){ // time: log K int i = 20; while (k > 0 && node != -1) { if ((k & (1 << i)) != 0) { if (i < ancestors[node].size()) node = ancestors[node][i]; else node = -1; k -= (1 << i); } --i; } return node; } };
/** * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor* obj = new TreeAncestor(n, parent); * int param_1 = obj->getKthAncestor(node,k); */