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:

Input:[[0,1,0,0],[1,0,1,1],[0,1,0,0]]
Output: 6
Explanation:
Placing a post office at (1,1), the distance that post office to all the house sum is smallest.
Example 2:
Input:[[0,1,0],[1,0,1],[0,1,0]]
Output: 4
Explanation:
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 个点的代价和。
      public class Solution {
      /**
      * @param grid: a 2D grid
      * @return: An integer
      */
      public int shortestDistance(int[][] grid) {
      // Write your code here
      int n = grid.length;
      if (n == 0)
      return -1; int m = grid[0].length;
      if (m == 0)
      return -1; List<Integer> sumx = new ArrayList<Integer>();
      List<Integer> sumy = new ArrayList<Integer>();
      List<Integer> x = new ArrayList<Integer>();
      List<Integer> y = new ArrayList<Integer>(); int result = Integer.MAX_VALUE;
      for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j)
      if (grid[i][j] == 1) {
      x.add(i);
      y.add(j);
      } Collections.sort(x);
      Collections.sort(y); int total = x.size(); sumx.add(0);
      sumy.add(0);
      for (int i = 1; i <= total; ++i) {
      sumx.add(sumx.get(i-1) + x.get(i-1));
      sumy.add(sumy.get(i-1) + y.get(i-1));
      } for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j)
      if (grid[i][j] == 0) {
      int cost_x = get_cost(x, sumx, i, total);
      int cost_y = get_cost(y, sumy, j, total);
      if (cost_x + cost_y < result)
      result = cost_x + cost_y;
      } return result;
      } public int get_cost(List<Integer> x, List<Integer> sum, int pos, int n) {
      if (n == 0)
      return 0;
      if (x.get(0) > pos)
      return sum.get(n) - pos * n; int l = 0, r = n - 1;
      while (l + 1 < r) {
      int mid = l + (r - l) / 2;
      if (x.get(mid) <= pos)
      l = mid;
      else
      r = mid - 1;
      } int index = 0;
      if (x.get(r) <= pos)
      index = r;
      else
      index = l;
      return sum.get(n) - sum.get(index + 1) - pos * (n - index - 1) +
      (index + 1) * pos - sum.get(index + 1);
      }
      }

        

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. flask源码系列

    更新中 HTML文档中元素存在,但是在浏览器中不显示.一般用于配合JavaScript代码使用. 04 LocalStack和Local对象实现栈的管理 05 Flask源码之:配置加载 06 Fla ...

  2. 大数据之路【第十四篇】:数据挖掘--推荐算法(Mahout工具)

    数据挖掘---推荐算法(Mahout工具) 一.简介 Apache顶级项目(2010.4) Hadoop上的开源机器学习库 可伸缩扩展的 Java库 推荐引擎(协同过滤).聚类和分类 二.机器学习介绍 ...

  3. spring整合RabbitMQ

    今天就来康康spring怎么整合RabbitMQ 注意一点,在发送消息的时候对template进行配置mandatory=true保证监听有效 生产端还可以配置其他属性,比如发送重试,超时时间.次数. ...

  4. (十二)一个简单的pdf文件体

    %PDF-1.0                     % 文件头,说明符合PDF1.0规范 1 0 obj                          %对象号     产生号(修改次数)  ...

  5. 论文笔记:DeepCF

    Abstract 推荐系统可以看作用户和物品的匹配问题,不过user以及item两者的语义空间差异太大,直接匹配不太符合实际.主流的改进CF的方法有两类:基于表示学习的CF方法以及基于函数学习的表示方 ...

  6. 使用 EnumWindows 找到满足你要求的窗口

    原文:使用 EnumWindows 找到满足你要求的窗口 在 Windows 应用开发中,如果需要操作其他的窗口,那么可以使用 EnumWindows 这个 API 来枚举这些窗口. 本文介绍使用 E ...

  7. drf中的各种view,viewset

    drf中的各种view,viewset Django REST framework里有各种各样的view,让我有点蒙,得好好捋一捋这关系. 视图的作用 Django用"视图"这个概 ...

  8. Idea创建一个SpringBoot工程

    1.打开Idea,点击新建工程 File—New—Project 2.点击下一步后可能会很一直在请求,或者直接报如下错误, 解决办法:直接点OK后再点Previous返回上一步,继续重新Next 3. ...

  9. Spring源码——IOC控制反转

    1.基础知识 Spring有两个核心功能,分别是ioc和aop,其中ioc是控制反转,aop是切面编程. 在ioc中,还有一个名次叫DI,也就是依赖注入.嗯,好像IOC和DI是指同一个,好像又感觉他俩 ...

  10. Linux排查PHP-FPM进程过量常用命令

    命令如下: 查看每个PHP-FPM进程的内存占用:ps -ylC php-fpm –sort:rss 查看消耗内存最多的前 40 个进程:ps auxw|head -1;ps auxw|sort -r ...