zoukankan      html  css  js  c++  java
  • [Locked] Best Meeting Point

    Best Meeting Point

    A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

    For example, given three people living at (0,0)(0,4), and(2,2):

    1 - 0 - 0 - 0 - 1
    |   |   |   |   |
    0 - 0 - 0 - 0 - 0
    |   |   |   |   |
    0 - 0 - 1 - 0 - 0

    The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.

    分析:

      第一反应就是求二维平面上的距离最优值;由于是曼哈顿距离,所以x维和y维可以分开求最小,最终结果也会最小,这样转化成了一维轴上绝对值之和最小,中学学过嘛,画图可知。

    解法:

      找到x轴上所有为1的点,然后从外到内依次两两index求差,这些差的总和为x轴上的最小值;y轴上也做同样的操作得到y轴最小值。两轴上的最小值之和为最小曼哈顿距离。时间复杂度为m*n,空间复杂度为1的个数。

    代码:

    int minDist(vector<vector<int> > v) {
        deque<int> inum, jnum;
        int dist = 0;
        for(int i = 0; i < v.size(); i++) {
            for(int j = 0; j < v[0].size(); j++) {
                if(v[i][j])
                    inum.push_back(i);
            }
        }
        while(inum.size() >= 2) {
            dist += inum.back() - inum.front();
            inum.pop_front();
            inum.pop_back();
        }
        for(int j = 0; j < v[0].size(); j++) {
            for(int i = 0; i < v.size(); i++) {
                if(v[i][j])
                    jnum.push_back(j);
            }
        }
        while(jnum.size() >= 2) {
            dist += jnum.back() - jnum.front();
            jnum.pop_front();
            jnum.pop_back();
        }
        return dist;
    }
  • 相关阅读:
    Java遍历JsonObject对象
    fastjson.JSONObject之对象与JSON转换方法
    Java HotSpot VM中的JIT编译
    JAVA 反射类 捕获异常 method.invoke方法如何捕获异常
    手动调用hibernate的参数校验器和springboot参数校验器 验证
    Netty-Socketio API
    Netty-socketio集成redis,服务端集群推送消息
    mysql 导出csv格式数据解决乱码
    自建dns服务器
    MySQL 8.0 克隆(clone)插件快速搭建主从复制
  • 原文地址:https://www.cnblogs.com/littletail/p/5202028.html
Copyright © 2011-2022 走看看