Description

Given a 2D grid, each cell is either an house 1 or empty 0 (the number zero, one), find the place to build a post office, the distance that post office to all the house sum is smallest. Return the smallest distance. Return -1 if it is not possible.
  • You can pass through house and empty.
  • You only build post office on an empty.
  • The distance between house and the post office is Manhattan distance

Example

Example 1:

  1. Input:[[0,1,0,0],[1,0,1,1],[0,1,0,0]]
  2. Output 6
  3. Explanation
  4. Placing a post office at (1,1), the distance that post office to all the house sum is smallest.
  5.  
  6. Example 2:
  1. Input:[[0,1,0],[1,0,1],[0,1,0]]
  2. Output 4
  3. Explanation
  4. Placing a post office at (1,1), the distance that post office to all the house sum is smallest.
    思路:

方法一:

  • 由于题中所求两点间距离表示为d(i,j)=|xi-xj|+|yi-yj|,所以可以在x方向和y方向分别计算,然后求和即可,实现一维方向的计算即可。
  • 首先遍历网格,为1的方格,将其横纵坐标,即i和j分别存储,然后排序,方便接下来的查找计算。然后利用sumx和sumy前缀和,sumx代表起点到各个点的x方向距离和,sumy同理。
  • 再次遍历网格,当前处为0时,首先二分查找该方向i或j的位置,如果有多个相同的,寻找最右边的,即可,设为index。
  • 然后求和即可
  • sum.get(n) - sum.get(index + 1) - pos * (n - index - 1) + (index + 1) * pos - sum.get(index + 1);
  • sum.get(n) - sum.get(index + 1)计算出当前点右侧部分到起点的距离和
    • pos * (n - index - 1) 减去多余部分,因为之前是到起点的距离和,现在要求到当前点的距离和
  • (index + 1) * pos - sum.get(index + 1) 此处开始计算当前点左侧部分,index+1个当前点距离和减去index+1到起点的距离和,即为左侧部分的距离和。

方法二:

    • 处理前缀:
      prefixSum1记录数组 a 的前缀和,即:prefixSum1[i]=a[0]+a[1]+..+a[i].
      prefixSum2记录数组 prefixSum1 前缀和,prefixSum2即为前 i 个点到第 i 个点的代价和。
    • 处理后缀:
      prefixSum1记录数组 a 的后缀和,即:prefixSum1[i]=a[n-1]+a[n-2]+..+a[i].
      prefixSum2记录数组 prefixSum1 的后缀和,prefixSum2即为 i 之后的点到第 i 个点的代价和。
      1. public class Solution {
      2. /**
      3. * @param grid: a 2D grid
      4. * @return: An integer
      5. */
      6. public int shortestDistance(int[][] grid) {
      7. // Write your code here
      8. int n = grid.length;
      9. if (n == 0)
      10. return -1;
      11.  
      12. int m = grid[0].length;
      13. if (m == 0)
      14. return -1;
      15.  
      16. List<Integer> sumx = new ArrayList<Integer>();
      17. List<Integer> sumy = new ArrayList<Integer>();
      18. List<Integer> x = new ArrayList<Integer>();
      19. List<Integer> y = new ArrayList<Integer>();
      20.  
      21. int result = Integer.MAX_VALUE;
      22. for (int i = 0; i < n; ++i)
      23. for (int j = 0; j < m; ++j)
      24. if (grid[i][j] == 1) {
      25. x.add(i);
      26. y.add(j);
      27. }
      28.  
      29. Collections.sort(x);
      30. Collections.sort(y);
      31.  
      32. int total = x.size();
      33.  
      34. sumx.add(0);
      35. sumy.add(0);
      36. for (int i = 1; i <= total; ++i) {
      37. sumx.add(sumx.get(i-1) + x.get(i-1));
      38. sumy.add(sumy.get(i-1) + y.get(i-1));
      39. }
      40.  
      41. for (int i = 0; i < n; ++i)
      42. for (int j = 0; j < m; ++j)
      43. if (grid[i][j] == 0) {
      44. int cost_x = get_cost(x, sumx, i, total);
      45. int cost_y = get_cost(y, sumy, j, total);
      46. if (cost_x + cost_y < result)
      47. result = cost_x + cost_y;
      48. }
      49.  
      50. return result;
      51. }
      52.  
      53. public int get_cost(List<Integer> x, List<Integer> sum, int pos, int n) {
      54. if (n == 0)
      55. return 0;
      56. if (x.get(0) > pos)
      57. return sum.get(n) - pos * n;
      58.  
      59. int l = 0, r = n - 1;
      60. while (l + 1 < r) {
      61. int mid = l + (r - l) / 2;
      62. if (x.get(mid) <= pos)
      63. l = mid;
      64. else
      65. r = mid - 1;
      66. }
      67.  
      68. int index = 0;
      69. if (x.get(r) <= pos)
      70. index = r;
      71. else
      72. index = l;
      73. return sum.get(n) - sum.get(index + 1) - pos * (n - index - 1) +
      74. (index + 1) * pos - sum.get(index + 1);
      75. }
      76. }

        

Build Post Office的更多相关文章

  1. Build Post Office II

    Description Given a 2D grid, each cell is either a wall 2, an house 1 or empty 0 (the number zero, o ...

  2. Post Office Problem

    Description There are n houses on a line. Given an array A and A[i] represents the position of i-th  ...

  3. 九章lintcode作业题

    1 - 从strStr谈面试技巧与代码风格 必做题: 13.字符串查找 要求:如题 思路:(自写AC)双重循环,内循环读完则成功 还可以用Rabin,KMP算法等 public int strStr( ...

  4. BFS总结

    能够用 BFS 解决的问题,一定不要用 DFS 去做! 因为用 Recursion 实现的 DFS 可能造成 StackOverflow! (NonRecursion 的 DFS 一来你不会写,二来面 ...

  5. sharepoint OOS巨大坑

    首先,我们安装的操作系统是windows server 2016 datacenter最新版,然后安装了OOS2016年的那个版本,打好语言包,安装必备软件,所有的步骤都没问题,但是你配置OOS场的时 ...

  6. How to Build Office Developer Tools Projects with TFS Team Build 2012

    Introduction Microsoft Visual Studio 2012 provides a new set of tools for developing apps for Office ...

  7. UWP?UWP! - Build 2015有些啥?(2)

    UWP?UWP! - Build 2015有些啥? Build 2015圆满落幕了,不知大家有多少人刷夜看了直播呢?不管怎么说,想必各位都很好奇在这场微软开发者盛宴上,Microsoft又发布了什么令 ...

  8. 微软 Build 2016年开发者大会发布多项功能升级

    微软Build 2016开发者大会在美国旧金山的莫斯康展览中心开幕.本次大会对一些重点功能进行了完善.如手写笔支持技术Windows Ink.语音识别Cortana应用集(Cortana Collec ...

  9. Devexpress VCL Build v2014 vol 15.2.3 发布

    2016年第一个版本,继续修补. New Major Features in 15.2 What's New in VCL Products 15.2 Breaking Changes To lear ...

随机推荐

  1. [转帖](区块链补习班)ERC20很多人都听过,但ERC是什么你真的了解吗?

    (区块链补习班)ERC20很多人都听过,但ERC是什么你真的了解吗? http://baijiahao.baidu.com/s?id=1600948969290990883&wfr=spide ...

  2. 服务器BMC资料整理

    1. 现在服务器都有BMC管理了,可以直接连上服务器进行处理. bios里面进行简单设置就可以了, 连接上IPMI的口进行管理. 2. 可以使用 远程控制安装操作系统. 安装系统时 比较清楚的能够看到 ...

  3. Anaconda的pip加速下载命令

    pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

  4. PHP下载远程图片到本地的几种方法总结(tp5.1)

    1.CURL 2.使用file_get_contents 3.使用fopen 参考链接:https://www.jb51.net/article/110615.htm

  5. JAVA知识点总结篇(二)

    数组 一维数组 声明 数据类型[] 数组名: 数据类型 数组名[]: 分配空间 数组名 = new 数据类型 [数组长度]: 可以在声明的同时分配空间,分配空间之后数组中才能放数据,数组元素都是通过下 ...

  6. *** WARNING L16: UNCALLED SEGMENT, IGNORED FOR OVERLAY PROCESS

    Warning提示的原因是 一些未使用的函数被编译进入芯片,浪费了RAM/ROM. 解决的方法: 1.将不用的函数注释: 2.在未使用函数的首尾加条件编译 #ifdef 函数名 和 #endif ,不 ...

  7. 【基本知识】UART接口

    1.简介 (1)UART一种通用异步串口数据总线,最低采用两路信号(TX/RX)即可实现全双工通信,十分简单: (2)UART采用LSB模式传输,串口数据传输格式如下图所示: 起始位:长度为1位的时间 ...

  8. KEPServerEX 6 配置连接 Allen-Bradley MicroLogix 1400

    =============================================== 2019/7/28_第1次修改                       ccb_warlock == ...

  9. VMware 网络介绍

       3.1 网卡介绍 如图所示,你的机器有两块网卡,一个是有线,一个是无线. 装完VM之后,会出现两块虚拟网卡,如图 VM有四种连接方式,我们着重介绍前三种    3.2 桥接 选择桥接模式,说明V ...

  10. java基础 Math

    package cn.mantishell.day08.demo04; /** * java.util.Math类是数学相关的工具类,里面提供类大量的静态方法,完成与数学运算相关的操作 * * pub ...