classSolution { public: intminLengthAfterRemovals(vector<int>& nums){ int ans = nums.size(); unordered_map<int, int> cnt; for (auto v : nums) cnt[v]++; vector<int> arr; for (auto [k, v] : cnt) { arr.emplace_back(v); }
priority_queue<int, vector<int>, less<int>> pq(arr.begin(), arr.end()); while (pq.size() > 1) { int x = pq.top(); pq.pop(); int y = pq.top(); pq.pop(); x--; y--; ans -= 2; if (x > 0) pq.emplace(x); if (y > 0) pq.emplace(y); }
return ans; } };
classSolution { public: intminLengthAfterRemovals(vector<int> &nums){ int n = nums.size(); int x = nums[n / 2]; int max_cnt = upper_bound(nums.begin(), nums.end(), x) - lower_bound(nums.begin(), nums.end(), x); returnmax(max_cnt * 2 - n, n % 2); } };
6988. 统计距离为 k 的点对
给你一个 二维 整数数组 coordinates 和一个整数 k ,其中 coordinates[i] = [xi, yi] 是第 i 个点在二维平面里的坐标。
classSolution { public: intcountPairs(vector<vector<int>>& coordinates, int k){ int n = coordinates.size(); unordered_map<longlong, int> cnt; int ans = 0; for (int i = 0; i < n; i++) { longlong x = coordinates[i][0]; longlong y = coordinates[i][1]; for (int j = 0; j <= k; j++) { longlong a = x ^ j; longlong b = y ^ (k - j); longlong key = (a << 32) + b; if (cnt.count(key)) { ans += cnt[key]; } } cnt[(x << 32) + y]++; } return ans; } };
100041. 可以到达每一个节点的最少边反转次数
给你一个 n 个点的 简单有向图 (没有重复边的有向图),节点编号为 0 到 n - 1 。如果这些边是双向边,那么这个图形成一棵 树 。
给你一个整数 n 和一个 二维 整数数组 edges ,其中 edges[i] = [ui, vi] 表示从节点 ui 到节点 vi 有一条 有向边 。
边反转 指的是将一条边的方向反转,也就是说一条从节点 ui 到节点 vi 的边会变为一条从节点 vi 到节点 ui 的边。
对于范围 [0, n - 1] 中的每一个节点 i ,你的任务是分别 独立 计算 最少 需要多少次 边反转 ,从节点 i 出发经过 一系列有向边 ,可以到达所有的节点。
请你返回一个长度为 n 的整数数组 answer ,其中 answer[i]表示从节点 i 出发,可以到达所有节点的 最少边反转 次数。
classSolution { public: vector<int> minEdgeReversals(int n, vector<vector<int>>& edges){ vector<vector<int>> graph(n); vector<unordered_set<int>> cnt(n); for (auto e : edges) { graph[e[0]].emplace_back(e[1]); graph[e[1]].emplace_back(e[0]); cnt[e[0]].emplace(e[1]); }
function<int(int, int)> dfs1 = [&](int root, int parent) -> int { int res = 0; for (auto v : graph[root]) { if (v == parent) continue; res += dfs1(v, root); if (cnt[v].count(root)) res++; } return res; };
int tot = dfs1(0, -1); vector<int> ans(n); function<void(int, int, int)> dfs2 = [&](int root, int parent, int tot) { ans[root] = tot; for (auto v : graph[root]) { if (v == parent) continue; if (cnt[v].count(root)) { dfs2(v, root, tot - 1); } else { dfs2(v, root, tot + 1); } } }; dfs2(0, -1, tot);