2025.12.03 力扣每日一题

​​​​​​3625.统计梯形的数目||

困难。。。

cpp 复制代码
class Solution {
public:
    int countTrapezoids(vector<vector<int>>& points) {
        unordered_map<double, vector<double>> groups; // 斜率 -> [截距]
        unordered_map<int, vector<double>> groups2; // 中点 -> [斜率]

        int n = points.size();
        for (int i = 0; i < n; i++) {
            int x = points[i][0], y = points[i][1];
            for (int j = 0; j < i; j++) {
                int x2 = points[j][0], y2 = points[j][1];
                int dy = y - y2;
                int dx = x - x2;
                double k = dx ? 1.0 * dy / dx : DBL_MAX;
                double b = dx ? 1.0 * (y * dx - x * dy) / dx : x;
                groups[k].push_back(b);
                int mid = (x + x2 + 2000) << 16 | (y + y2 + 2000); // 把二维坐标压缩成一个 int
                groups2[mid].push_back(k);
            }
        }

        int ans = 0;
        for (auto& [_, g] : groups) {
            if (g.size() == 1) {
                continue;
            }
            // 对于本题的数据,map 比哈希表快
            map<double, int> cnt;
            for (double b : g) {
                cnt[b]++;
            }
            int s = 0;
            for (auto& [_, c] : cnt) {
                ans += s * c;
                s += c;
            }
        }

        for (auto& [_, g] : groups2) {
            if (g.size() == 1) {
                continue;
            }
            map<double, int> cnt;
            for (double k : g) {
                cnt[k]++;
            }
            int s = 0;
            for (auto& [_, c] : cnt) {
                ans -= s * c; // 平行四边形会统计两次,减去多统计的一次
                s += c;
            }
        }

        return ans;
    }
};
相关推荐
A923A4 分钟前
【洛谷刷题 | 第四天】
算法·前缀和·贪心·洛谷·差分
bai_lan_ya16 分钟前
使用linux的io文件操作综合实验_处理表格
linux·服务器·算法
计算机安禾21 分钟前
【C语言程序设计】第36篇:二进制文件的读写
c语言·开发语言·c++·算法·github·visual studio code·visual studio
ZPC821022 分钟前
OLOv11 + 深度相机的方案实现高精度3D定位
人工智能·数码相机·算法·机器人
_日拱一卒26 分钟前
LeetCode:字母异位词分组
算法·leetcode·职场和发展
Dfreedom.28 分钟前
机器学习经典算法全景解析与演进脉络(监督学习篇)
人工智能·学习·算法·机器学习·监督学习
Zaly.28 分钟前
【Python刷题】LeetCode 3567 子矩阵的最小绝对差
python·leetcode·矩阵
2301_8073671935 分钟前
C++代码风格检查工具
开发语言·c++·算法
Morwit36 分钟前
*【力扣hot100】 215. 数组中的第K个最大元素
数据结构·c++·算法·leetcode·职场和发展
奔袭的算法工程师37 分钟前
用AI写天线阵列排布算法
人工智能·算法·信号处理