楼主: 14417335
跳转到指定楼层
上一主题 下一主题
收起左侧

[高频题] 最方便的寓所

🔗
neozhang9233 2019-3-29 09:20:10 | 只看该作者
全局:
粘一个个人的答案,无论是求距离和还是最远都可以用这个方法,速度为O(nk),k为requires项数。

  1. class Solution {

  2.     /*
  3.     * Input: 1. 给一条路,路上的不同位置有不同的设施,有多个设施在不同位置的情况, List<Set<String>>
  4.     *        2. 给一个需求设施的set
  5.     * Output: 希望给出一个位置,距离所有设施的距离最近的和
  6.     *
  7.     * Example:
  8.     *   Road: {
  9.     *           [bookstore, school],
  10.     *           [grocery] ,
  11.     *           [],
  12.     *           [],
  13.     *           [bookstore, library],
  14.     *           []
  15.     *           [grocery]
  16.     *        }
  17.     *   Requires: [bookstore, library, grocery]
  18.     *   Output: the best place is 4, to bookstore and lib is 0, and grocery is 2, so in sum is 2.
  19.     * */

  20.     public int findBestLocationn(List<Set<String>> road, List<String> requires) {
  21.         Map<String, List<Integer>> roadMap = createMap(road);
  22.         int minSum = Integer.MAX_VALUE, index = 0;
  23.         for (int i = 0; i < road.size(); i++) {
  24.             int sum = 0;
  25.             for (int j = 0; j < requires.size(); j++) {
  26.                 sum += getMinLen(roadMap, requires.get(j), i);
  27.             }
  28.             if (sum < minSum) {
  29.                 minSum = sum;
  30.                 index = i;
  31.             }
  32.         }
  33.         return index;
  34.     }

  35.     private Map<String, List<Integer>> createMap(List<Set<String>> road) {
  36.         Map<String, List<Integer>> roadMap = new HashMap<>();
  37.         for (int i = 0; i < road.size(); i++) {
  38.             for (String facility: road.get(i)) {
  39.                 List<Integer> list = roadMap.getOrDefault(facility, new ArrayList<>());
  40.                 list.add(i);
  41.                 roadMap.put(facility, list);
  42.             }
  43.         }
  44.         return null;
  45.     }

  46.     private int getMinLen(Map<String, List<Integer>> roadMap, String require, int index) {
  47.         List<Integer> list = roadMap.get(require);
  48.         int minLen = Integer.MAX_VALUE;
  49.         for (int pos: list) {
  50.             minLen = Math.min(minLen, Math.abs(pos-index));
  51.         }
  52.         return minLen;
  53.     }
  54.    
  55. }
复制代码

补充内容 (2019-3-29 09:21):
return raodMap;

第二个method最后应该是,忘了改了

评分

参与人数 5大米 +19 收起 理由
薏米红豆芡实 + 1 给你点个赞!
dddaisy + 2 给你点个赞!
admin + 10
magmag + 1 很有用的信息!
14417335 + 5 很有用的信息!

查看全部评分

回复

使用道具 举报

🔗
kaipeng21 2019-3-29 13:06:14 | 只看该作者
全局:
brave2 发表于 2019-3-29 11:59
我怎么感觉你这方法不对呢。。是我理解错了吗。
为啥“找所有符合条件的移动窗口中的最小值,纪录最小窗 ...

跟利口漆遛一样,sliding window 中必须要包含所有的requirement,window的开始与结束两端必有requirement ,这个window越小表示requirement 之间的距离越近,根据题意最短距离指的是公寓到最远的requirement poi 的距离,而window的正中间到两端的距离是最短的,离开window中点就会使到其中一端的距离变长,就不是最近了

这是相对而言我比较不确定算法是不是完全正确的,如果有反例欢迎指出修正
回复

使用道具 举报

全局:
brave2 发表于 2019/03/29 13:36:36


反例比如说:

7个点:0,0,0,0,0,0,1000

距离所有点之和最近的点 应该是点0,距离为1000;而不是点500,距离为3500

题意有误解,这题有两种问法,一种是问距离和,一种是问到最远的一个的距离,距离和的话这个作法当然是不对的,如果只是到最远的requirement 的距离,500距离0和1000都是500,这例子就没问题

补充内容 (2019-3-29 13:52):
所以我的第一种方法也是写max(dist[i].values()) 不是sum(dist[i].values())
回复

使用道具 举报

全局:
kaipeng21 发表于 2019/03/28 23:34:13
根据面经讨论写了两个方案,附上代码和unittest,如有错误或遗漏的case欢迎留言指教,followup用第一种改好像比较容易

[hide=200]
[mw_shl_code=python...

补充:我这题写的最近的定义是,离最远的requirement 的距离,也有的题目是问到所有requirement 的距离和,距离和的问法方案二就不适用,方案一要小修改
回复

使用道具 举报

🔗
ymqu 2019-3-29 19:43:24 | 只看该作者
全局:
我也觉得这涨积分大米的要求特别高。如果一年60的会费我早买了,只有一个月,也太贵了。新人什么都看不到,也伤心
回复

使用道具 举报

🔗
 楼主| 14417335 2019-3-29 22:42:39 | 只看该作者
全局:
ymqu 发表于 2019-3-29 19:43
我也觉得这涨积分大米的要求特别高。如果一年60的会费我早买了,只有一个月,也太贵了。新人什么都看不到, ...

我对毛线的关于大米门槛回复写到公社里去了。

https://www.1point3acres.com/bbs ... read&tid=495720

第9垅
回复

使用道具 举报

🔗
Lunluen 2019-3-31 02:15:18 | 只看该作者
全局:
贴个自己的解法, 时间复杂度是O(KN)而非O(KNL)

另外感谢kaipeng21的test cases

Time complexity: O(KN)
Space complexity: O(KL)

N: street長度
K: requirements長度
L: 同一個requirement在*不同*index上出現的最大次數

  1. import collections
  2. from typing import List


  3. class Interview(object):

  4.     def solution(self, street: List[List[str]], requirements: List[str]) -> int:
  5.         dists = {}
  6.         road_map = collections.defaultdict(collections.deque)

  7.         # Builds the road map.
  8.         for i, location in enumerate(street):
  9.             for facility in set(location):  # Note: use `set` to deduplicate.
  10.                 if facility in requirements:
  11.                     road_map[facility].append(i)
  12.         
  13.         for facility in requirements:
  14.             # Adds additional two ends to avoid some annoying if statements.
  15.             road_map[facility].appendleft(float('-inf'))
  16.             road_map[facility].append(float('inf'))

  17.             dists[facility] = float('inf')

  18.         index = -1  # Returns -1 if no solution exists.
  19.         dist_sum = float('inf')
  20.         for i in range(len(street)):
  21.             # Updates minimum distances
  22.             for facility in requirements:
  23.                 left, right = road_map[facility][0], road_map[facility][1]
  24.                 dists[facility] = min(i - left, right - i)
  25.                 if i == right:
  26.                     road_map[facility].rotate(-1)  # Rotates one step left.
  27.             
  28.             # Updates the best location.
  29.             current_sum = sum(dists.values())
  30.             if current_sum < dist_sum:
  31.                 dist_sum = current_sum
  32.                 index = i
  33.         
  34.         return index


  35. # Don't specify return value if it's None.
  36. test_cases = [
  37.     [
  38.         ["Store", "School", "Museum"],
  39.         ["Hospital", "Restaurant"],
  40.         ["School", "Restaurant"],
  41.     ],
  42.     ["Store", "Museum", "Hotel"],
  43.     -1,
  44.     [
  45.         ["Store", "School", "Museum"],
  46.         ["Hospital", "Restaurant"],
  47.         ["School", "Restaurant"],
  48.         [],
  49.         ["Museum"],
  50.     ],
  51.     ["Store", "Museum", "Restaurant"],
  52.     0,
  53.     #
  54.     [
  55.         ["Store", "School", "Museum"],
  56.         ["Hospital", "Restaurant"],
  57.         ["School", "Restaurant"],
  58.         [],
  59.         ["Museum"],
  60.     ],
  61.     ["Hospital", "Restaurant"],
  62.     1,
  63.     #
  64.     [
  65.         ["Store", "School", "Museum"],
  66.         ["Hospital", "Restaurant"],
  67.         ["School", "Restaurant"],
  68.         [],
  69.         ["Museum"],
  70.     ],
  71.     ["Museum", "Hospital"],
  72.     0,
  73.     ###
  74.     [
  75.         ["School", "Store", "School"],
  76.         ["Park"],
  77.         [],
  78.         ["Restaurant"],
  79.         ["Hospital"],
  80.     ],
  81.     ["Park","Restaurant"],
  82.     1,
  83.     #
  84.     [
  85.         ["School", "Store", "School"],
  86.         ["Park"],
  87.         [],
  88.         ["Restaurant"],
  89.         ["Hospital"],
  90.     ],
  91.     ["School","Restaurant"],
  92.     0,
  93.     #
  94.     [
  95.         ["School", "Store", "School"],
  96.         ["Park"],
  97.         [],
  98.         ["Restaurant"],
  99.         ["Hospital"],
  100.     ],
  101.     ["Hospital"],
  102.     4,
  103.     ###
  104.     [
  105.         ["A", "B", "C"],
  106.         ["D", "E", "F"],
  107.         ["G", "H"],
  108.         ["I", "J", "K"],
  109.         ["L", "M", "N"],
  110.         ["O", "P", "Q", "R", "S", "T", "U", "V"],
  111.         ["W", "X", "Y"],
  112.         [],
  113.         ["Z"],
  114.     ],
  115.     ["F", "K"],
  116.     1,
  117.     #
  118.     [
  119.         ["A", "B", "C"],
  120.         ["D", "E", "F"],
  121.         ["G", "H"],
  122.         ["I", "J", "K"],
  123.         ["L", "M", "N"],
  124.         ["O", "P", "Q", "R", "S", "T", "U", "V"],
  125.         ["W", "X", "Y"],
  126.         [],
  127.         ["Z"],
  128.     ],
  129.     ["A", "Z"],
  130.     0,
  131.     #
  132.     [
  133.         ["A", "B", "C"],
  134.         ["D", "E", "F"],
  135.         ["G", "H"],
  136.         ["I", "J", "K"],
  137.         ["L", "M", "N"],
  138.         ["O", "P", "Q", "R", "S", "T", "U", "V"],
  139.         ["W", "X", "Y"],
  140.         [],
  141.         ["Z"],
  142.     ],
  143.     ["C", "V", "Z"],
  144.     5,
  145.     ###
  146.     [
  147.         ["A", "B", "C"],
  148.         ["F"],
  149.         [],
  150.         ["D", "E"],
  151.         [],
  152.         [],
  153.         [],
  154.         ["D", "E"],
  155.         [],
  156.         [],
  157.         ["C", "B", "A"]
  158.     ],
  159.     ["A", "E"],
  160.     0,
  161.     #
  162.     [
  163.         ["A", "B", "C"],
  164.         ["F"],
  165.         [],
  166.         ["D", "E"],
  167.         [],
  168.         [],
  169.         [],
  170.         ["D", "E"],
  171.         [],
  172.         [],
  173.         ["C", "B", "A"]
  174.     ],
  175.     ["F", "A"],
  176.     0,
  177.     #
  178.     [
  179.         ["A", "B", "C"],
  180.         ["F"],
  181.         [],
  182.         ["D", "E"],
  183.         [],
  184.         [],
  185.         [],
  186.         ["D", "E"],
  187.         [],
  188.         [],
  189.         ["C", "B", "A"]
  190.     ],
  191.     ["D", "E"],
  192.     3,
  193.     ###
  194.     [
  195.         ["A", "B", "C"],
  196.         [],
  197.         [],
  198.         ["D", "E"],
  199.         ["F", "G", "H"],
  200.         ["I", "J", "K"],
  201.         ["L"],
  202.         ["M"],
  203.         ["E"],
  204.         ["N"]
  205.     ] * 3,
  206.     ["A", "D"],
  207.     0,
  208.     #
  209.     [
  210.         ["A", "B", "C"],
  211.         [],
  212.         [],
  213.         ["D", "E"],
  214.         ["F", "G", "H"],
  215.         ["I", "J", "K"],
  216.         ["L"],
  217.         ["M"],
  218.         ["E"],
  219.         ["N"]
  220.     ] * 3,
  221.     ["D", "M"],
  222.     3,
  223.     #
  224.     [
  225.         ["A", "B", "C"],
  226.         [],
  227.         [],
  228.         ["D", "E"],
  229.         ["F", "G", "H"],
  230.         ["I", "J", "K"],
  231.         ["L"],
  232.         ["M"],
  233.         ["E"],
  234.         ["N"]
  235.     ] * 3,
  236.     ["B", "N"],
  237.     9,
  238.     #
  239.     [
  240.         ["A", "B", "C"],
  241.         [],
  242.         [],
  243.         ["D", "E"],
  244.         ["F", "G", "H"],
  245.         ["I", "J", "K"],
  246.         ["L"],
  247.         ["M"],
  248.         ["E"],
  249.         ["N"]
  250.     ] * 3,
  251.     ["E", "F", "M"],
  252.     4,
  253. ]


  254. if __name__ == '__main__':
  255.     interview = Interview()
  256.     args_count = Interview.solution.__code__.co_argcount - 1  # - 1 for self.
  257.    
  258.     args = []
  259.     iterator = iter(test_cases)
  260.     while True:
  261.         try:
  262.             args.append(next(iterator))
  263.         except StopIteration:
  264.             break

  265.         if len(args) == args_count:
  266.             result = interview.solution(*args)
  267.             if result is not None:
  268.                 try:
  269.                     answer = next(iterator)
  270.                     assert result == answer
  271.                 except AssertionError:
  272.                     print(f'Input:')
  273.                     for arg in args:
  274.                         print(f'\t{arg}')
  275.                     print(f'Expected: {answer}')
  276.                     print(f'Your output: {result}')
  277.             args = []

  278.     print('End.')
复制代码

补充内容 (2019-3-31 02:21):
忘记设限制
没办法删文的吗?

补充内容 (2019-3-31 02:24):
解释一下
概念就是最初就纪录各requirements的位置
之后利用deque只比较最接近的两个
为了方便只回传符合要求的最小index

follow-up直接对没有apartment的index给continue就好了

评分

参与人数 1大米 +2 收起 理由
zdzapple + 2 给你点个赞!

查看全部评分

回复

使用道具 举报

🔗
Lunluen 2019-3-31 02:19:45 | 只看该作者
全局:
kaipeng21 发表于 2019-3-28 23:34
根据面经讨论写了两个方案,附上代码和unittest,如有错误或遗漏的case欢迎留言指教,followup用第一种改好 ...

有个test case错了
应该是5
  1.     def test_3(self):
  2.         street = [
  3.             ["A", "B", "C"],
  4.             ["D", "E", "F"],
  5.             ["G", "H"],
  6.             ["I", "J", "K"],
  7.             ["L", "M", "N"],
  8.             ["O", "P", "Q", "R", "S", "T", "U", "V"],
  9.             ["W", "X", "Y"],
  10.             [],
  11.             ["Z"]
  12.         ]
  13.         requirements = ["C", "V", "Z"]
  14.         assert sorted(best_apartment(street, requirements)) == [4]
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表