博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
边工作边刷题:70天一遍leetcode: day 86-2
阅读量:4500 次
发布时间:2019-06-08

本文共 1824 字,大约阅读时间需要 6 分钟。

Best Meeting Point

要点:

  • 题本身不难理解,manhattan distance。follow up就变成weighted了(因为一个地方可以有多个住户)
  • 注意input是grid的形式,一种方法是2d iterate,然后用两个数组分别存x,y,只需要对column sort,row是按顺序的iterate的。最后直接取中
  • 这题之所以是Hard,因为有另一种方法:不用sort,不用找median,类似于nested weighted sum II,只不过变成双向而非单向
    • 假设到某一点i和j分别对应左右的某点(注意,和另一边无关),left表示所有i左边的人,right表示所有j右边的人。如果i右移,j左移,每移动一步所有当前left,right的距离d都会增加1。显然,在每一步选最小的增加距离最合算(到目前为止,不同层总的增加数是不同的)。而如果当前i/j上有人,人口也会增加(即left/right增加)。
    • 为什么是i<j?当i==j的时候,这个位置的新增人(either left or right)距离都是0,所以不需要计入距离。推广到一般的过程,所有新增人口,都不会对当前轮的d有影响。所以要d+=left/right是上一轮的
    • 另外,也利用了each row/col的sum,i.e.,把行列浓缩成一个值来降维。
    • 显然,这个方法也可以处理weighted的情况。所以time complexity: O(mn)

错误点:

  • 最后结果不是/2
# 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.# Hint:# Try to solve it in one dimension first. How can this solution apply to the two dimension case?# Hide Company Tags Twitter# Hide Tags Math Sort# Hide Similar Problems (H) Shortest Distance from All Buildingsclass Solution(object):    def minTotalDistance(self, grid):        """        :type grid: List[List[int]]        :rtype: int        """        row_num = [sum(row) for row in grid]        col_num = [sum(col) for col in zip(*grid)]        def minDist(sum_list):            l, r = -1, len(sum_list)            left,right=0,0            d=0            while l

转载于:https://www.cnblogs.com/absolute/p/5815789.html

你可能感兴趣的文章
配置打开IE浏览器
查看>>
SVN A C D M G U R I 的含义
查看>>
ZooKeeper--大数据系统的僚机
查看>>
css3新属性object-fit,对页面img处理
查看>>
设计模式--工厂模式Factory
查看>>
五年修炼SEO、一年五万,多嘛?(看时间如何管理?五点论……)
查看>>
Mesos源码分析(16): mesos-docker-executor的运行
查看>>
echarts柱状图点击阴影部分触发事件
查看>>
3771: Triple
查看>>
使用PyPDF2库对pdf文件进行指定页面删除操作
查看>>
Python:yield关键字
查看>>
EasyRTSPClient:基于live555封装的支持重连的RTSP客户端RTSPClient
查看>>
EasyDarwin云存储方案调研:海康萤石云采用的是MPEG-PS打包的方式进行的存储
查看>>
MySQL巡检
查看>>
学习笔记之传说中的圣杯布局
查看>>
oh-my-zsh的使用
查看>>
共享内存的设计
查看>>
deque容器
查看>>
2017-2018-1 20155203 20155204 实验二 固件程序设计
查看>>
三方贸易-drop ship
查看>>