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;
    }
};
相关推荐
代码游侠7 分钟前
复习——网络基础知识
网络·笔记·网络协议·算法·http
我命由我1234517 分钟前
Photoshop - Photoshop 工具栏(46)渐变工具
经验分享·笔记·学习·ui·职场和发展·学习方法·photoshop
沈阳信息学奥赛培训17 分钟前
CCF GESP 2025/12/24 模拟测试 C++ 4级 编程题2
数据结构·算法
dddddppppp12318 分钟前
c 模拟一个fat16文件系统
c语言·c++·算法
行走的bug...38 分钟前
利用计算机辅助数学运算
人工智能·算法·机器学习
CoderCodingNo40 分钟前
【GESP】C++五级真题(数论-素数、贪心思想考点) luogu-B4050 [GESP202409 五级] 挑战怪物
开发语言·c++·算法
小O的算法实验室1 小时前
2026年AEI SCI1区TOP,基于多策略集成粒子群算法+无人机平滑覆盖路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
不一样的故事1261 小时前
高速采集箱
算法·信号处理
会员果汁2 小时前
算法-拓扑排序-C
c语言·开发语言·算法
YGGP2 小时前
【Golang】LeetCode 72. 编辑距离
算法·leetcode