【LC周赛391】3102. 最小化曼哈顿距离

题目描述

image

解析

一道很有意思的题目和一份写得很优雅的C++代码。
问题关键在于如何高效求解曼哈顿距离
借用一位大神的图:
image
因此有公式:曼哈顿距离=\(max(|x_1'-x_2'|, |y_1'-y_2'|)\),其中\(x'=x+y, y'=y-x\).【切比雪夫距离】
为方便求解数组中的最大值和最小值,使用multiset数据结构维护序列,该结构底层结构为红黑树,对插入删除具有\(O(logn)\)复杂度,且默认升序排序。

class Solution {
public:
    int minimumDistance(vector<vector<int>> &points) {
        multiset<int> xs, ys;
        for (auto &p : points) {
            xs.insert(p[0] + p[1]);
            ys.insert(p[1] - p[0]);
        }
        int ans = INT_MAX;
        for (auto &p : points) {
            int x = p[0] + p[1], y = p[1] - p[0];
            xs.erase(xs.find(x));
            ys.erase(ys.find(y));
            ans = min(ans, max(*xs.rbegin() - *xs.begin(), *ys.rbegin() - *ys.begin()));
            xs.insert(x);
            ys.insert(y);
        }
        return ans;
    }
};

作者:灵茶山艾府
链接:https://leetcode.cn/problems/minimize-manhattan-distances/solutions/2716755/tu-jie-man-ha-dun-ju-chi-heng-deng-shi-b-op84/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在集合中删除元素和取最大最小值的方法值得学习。

posted @ 2024-04-03 23:26  yichen111  阅读(171)  评论(0)    收藏  举报