📣 VIP通行证夏日特惠 限时立减$68
查看: 762| 回复: 4
跳转到指定楼层
上一主题 下一主题
收起左侧

[高频题] 刀大师面经题时间间隔

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 nexttomexxd 于 2022-2-19 16:28 编辑

input 是两个 string,e.g. “mon 11:00 am”,“mon 11:15 am”,返回 a list of strings[“11100”,“111105”,“111110”,“111115”],第一个 digit 是 day,mon -> 1,tue -> 2,
后面是四位时间,24 小时制,每两个时间中间间隔五分钟。需要 validate input,如果
invalid,返回空。
input 可能有 12 小时制,也可能有 24 小时制(没有 am,pm)。时间可能有 leading
zeros,可能不在范围内。开始时间不保证早于结束时间。如果 input 时间不是 5 的倍数,
要四舍五入到最近的点
  1. # Online Python compiler (interpreter) to run Python online.
  2. # Write Python 3 code in this online editor and run it.

  3. from typing import List

  4. class Time:
  5.     days_to_num = {'mon': 0, 'tue': 1, 'wed': 2, 'thur':3, 'fri': 4, 'sat': 5, 'sun': 6}
  6.     nums_to_day = {v: k for k, v in days_to_num.items()}
  7.     def __init__(self, timec: List[int]):
  8.         self.timec = timec
  9.         
  10.     @classmethod
  11.     def from_s(cls, s: str):
  12.         timec = cls.parse_time(s)
  13.         return cls(timec)
  14.         
  15.     def __add__(self,  m: int) -> List[int]:
  16.         day, hh, mm, tf = self.timec
  17.         mm_r = (mm + m) // 60
  18.         mm_m = (mm + m) % 60
  19.         hh_r = (hh + mm_r) // 24
  20.         hh_m = (hh + mm_r) % 24
  21.         day_r = (day + hh_r) // 7
  22.         day_m = (day + hh_r) % 7
  23.         day, hh, mm, tf = day_m, hh_m, mm_m, tf
  24.         return Time([day, hh, mm, tf])
  25.         
  26.     def __eq__(self, other) -> bool:
  27.         return self.timec == other.timec
  28.         
  29.     def __gt__(self, other) -> bool:
  30.         gt = all(i >= j for i, j in zip(self.timec[:-1], other.timec[:-1]))
  31.         g = any(i > j for i, j in zip(self.timec[:-1], other.timec[:-1]))
  32.         return gt and g
  33.         
  34.     def __ge__(self, other) -> bool:
  35.         return self.__gt__(other) or self.__eq__(other)
  36.         
  37.     @classmethod   
  38.     def parse_time(cls, s: str) -> List[int]:
  39.         splits = s.split()
  40.         day = splits[0].lower()
  41.         hh, mm = map(int, splits[1].split(':'))
  42.         if len(splits) == 2:
  43.             return [cls.days_to_num[day], hh, mm, 1]
  44.         if len(splits) == 3:
  45.             am_pm = splits[2]
  46.             if am_pm.lower() == 'am' or hh == '12':
  47.                 return [Time.days_to_num[day], hh, mm, 0]
  48.             else:
  49.                 return [Time.days_to_num[day], hh + 12, mm, 0]
  50.             return 1
  51.             
  52.     def __str__(self) -> str:
  53.         day, hh, mm, tf = self.timec
  54.         if tf == 0:
  55.             if hh >= 12:
  56.                 if hh > 12:
  57.                     hh = hh % 12
  58.                 return f"{Time.nums_to_day[day]} {hh//10}{hh%10}:{mm//10}{mm%10} pm"
  59.             return f"{Time.nums_to_day[day]} {hh//10}{hh%10}:{mm//10}{mm%10} am"
  60.         return f"{Time.nums_to_day[day]} {hh//10}{hh%10}:{mm//10}{mm%10}"
  61.         
  62.         
  63. def get_time_interval(s1: Time, s2: Time) -> List[str]:
  64.     s1 = Time.from_s(s1)
  65.     s2 = Time.from_s(s2)
  66.    
  67.     if s1.timec[2] % 10 < 5:
  68.         s1.timec[2] = s1.timec[2] - s1.timec[2] % 4
  69.     if s1.timec[2] % 10 > 5:
  70.         s1 = s1.add(10-(s1.timec[2] % 10))
  71.     if s1 > s2: return list()
  72.     stop = False
  73.     result = list()
  74.     while not stop:
  75.         if s1.timec[2] % 5 == 0:
  76.             result.append(str(s1))
  77.         s1 = s1+1
  78.         if s2 > s1:
  79.             stop = True
  80.     return result
  81.    
  82. print(get_time_interval("mon 10:00 am", "mon 11:00 am"))
  83. print(get_time_interval("mon 10:00 pm", "tue 01:00 am"))
  84. print(get_time_interval("mon 10:00 pm", "mon 10:00 pm"))
  85. print(get_time_interval("mon 10:00", "tue 00:00"))
  86. print(get_time_interval("mon 10:00", "mon 00:00"))            
复制代码

补充内容 (2022-02-22 02:40 +8:00):
汇总刀大师面经python手撕解法, 求加米

评分

参与人数 3大米 +17 收起 理由
bryanjhy + 10 给你点个赞!
west0428 + 1 很有用的信息!
14417335 + 6 给你点个赞!

查看全部评分


上一篇:刀大师经典题
下一篇:求买它tag 列表,多谢!
🔗
 楼主| nexttomexxd 2022-2-20 11:59:03 | 只看该作者
全局:

1. Given array of pick up and delivery options, make sure that the array is valid.
Example 1:
Input: ['P1', 'D1']
Output: True
Explanation: P1 comes before D1
Example 2:
Input: ['P2', 'D1', 'P1', 'D2']
Output: False
Explanation: D1 comes before P1, but it should come after.
Note to future solver: Make sure you cover case like P11 and P99 etc. where number followed
by P and D is in double digits.
My thoughts: Was able to solve this, got stuck at the P11 test case, they hide the test cases
from you, so it's difficult to know/ think of all edge cases. Was able to produce working output.
  1. from typing import List, Tuple
  2. def all_valid(n: int) -> List[str]:
  3.     result = list()
  4.     visited = [0] * n
  5.     def dfs(path, i):
  6.         if len(path) == 2*n:
  7.             result.append(path.copy())
  8.             return
  9.         # pick i
  10.         if i < n:
  11.             path.append('P' + str(i))
  12.             dfs(path, i+1)
  13.             # or deli one
  14.             path.pop(-1)
  15.         for j in range(n):
  16.             if visited[j] == 0:
  17.                 path.append(f"D{j}")
  18.                 visited[j] = 1
  19.                 dfs(path, i)
  20.                 visited[j] = 0
  21.                 path.pop(-1)
  22.     dfs([],  0)
  23.     return result
  24.    
  25. print(all_valid(2))
复制代码
回复

使用道具 举报

🔗
 楼主| nexttomexxd 2022-2-22 02:39:54 | 只看该作者
全局:

给一张 city 的地图和一个列表 locations,问从 locations 里的每个位置到 D 的最短步数,
地图中 X 为 blocked 的部分。locations 的长度远大于 D 的数量。
类似 leetcode 286
inputs:
char[][] city = {
// 0 1 2 3 4 5 6 7 8
{'X', ' ', ' ', 'D', ' ', ' ', 'X', ' ', 'X'}, //0
{'X', ' ', 'X', 'X', ' ', ' ', ' ', ' ', 'X'}, //1

{' ', ' ', ' ', 'D', 'X', 'X', ' ', 'X', ' '}, //2
{' ', ' ', ' ', 'D', ' ', 'X', ' ', ' ', ' '}, //3
{' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X'}, //4
{' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X', 'X'} //5
}
int[][] locations =
{
{200, 200},
{1, 4},
{0, 3},
{5, 6},
{5, 8}
}
outputs:
int[]
[-1, 2, 0, 8, -1]
  1. def find_dis(mapping, locations, d):
  2.     c, r = len(mapping[0]), len(mapping)
  3.     results = [-2] * len(locations)
  4.     target = dict()
  5.     for i, (ir, ic) in enumerate(locations):
  6.         if (not 0 <= ir < r) or (not 0<= ic < c):
  7.             results[i] = -1
  8.         elif mapping[ir][ic] == 'X':
  9.             results[i] = -1
  10.         elif mapping[ir][ic] == 'D':
  11.             results[i] = 0   
  12.         else:
  13.             target[(ir, ic)] = i
  14.     q = list()
  15.     dist = dict()
  16.     for i in range(len(d)):
  17.         q.append((d[i][0], d[i][1]))
  18.         dist[(d[i][0], d[i][1])] = 0
  19.     finished = False
  20.     while q and (not finished):
  21.         print(q)
  22.         print(dist)
  23.         print(results)
  24.         size = len(q)
  25.         for _ in range(size):
  26.             cur = q.pop(0)
  27.             if cur in target:
  28.                 results[target[cur]] = dist[cur]
  29.                 if all([i != -2 for i in results]):
  30.                     finished = True
  31.             for n in get_neib(cur, r, c):
  32.                 if (n not in dist) and (mapping[n[0]][n[1]] not in ('X', 'D')):
  33.                     q.append(n)
  34.                     dist[n] = dist[cur] + 1
  35.     return results
  36.    
  37. def get_neib(cur, R, C):
  38.     r, c = cur
  39.     dirs = [[0, -1], [0, 1], [-1, 0], [1, 0]]
  40.     for dr, dc in dirs:
  41.         nr, nc = r + dr, c + dc
  42.         if (0 <= nr < R) and (0 <= nc < C):
  43.             yield (nr, nc)
  44.             
  45. mapping = [['X', 'D',  '', ''],
  46.            ['',  'X',  '', 'D'],
  47.            ['',  '',  '',  'X'],
  48.            ['',  'X',  'D',  'X']]
  49. locations = [[1, 0], [0, 3], [10, 9], [0, 1]]
  50. d = [[0, 1], [1, 3], [3, 2]]
  51. print(find_dis(mapping, locations, d))
  52.    
  53.             
  54.    
  55.         
  56.         
  57.         
  58.    
  59.             
  60.             
  61.       
  62.    
复制代码
回复

使用道具 举报

🔗
 楼主| nexttomexxd 2022-2-22 02:41:44 | 只看该作者
全局:
给一张 city 的地图和一个列表 locations,问从 locations 里的每个位置到 D 的最短步数,
地图中 X 为 blocked 的部分。locations 的长度远大于 D 的数量。
类似 leetcode 286
inputs:
char[][] city = {
// 0 1 2 3 4 5 6 7 8
{'X', ' ', ' ', 'D', ' ', ' ', 'X', ' ', 'X'}, //0
{'X', ' ', 'X', 'X', ' ', ' ', ' ', ' ', 'X'}, //1

{' ', ' ', ' ', 'D', 'X', 'X', ' ', 'X', ' '}, //2
{' ', ' ', ' ', 'D', ' ', 'X', ' ', ' ', ' '}, //3
{' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X'}, //4
{' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X', 'X'} //5
}
int[][] locations =
{
{200, 200},
{1, 4},
{0, 3},
{5, 6},
{5, 8}
}
outputs:
int[]
[-1, 2, 0, 8, -1]
  1. def find_dis(mapping, locations, d):
  2.     c, r = len(mapping[0]), len(mapping)
  3.     results = [-2] * len(locations)
  4.     target = dict()
  5.     for i, (ir, ic) in enumerate(locations):
  6.         if (not 0 <= ir < r) or (not 0<= ic < c):
  7.             results[i] = -1
  8.         elif mapping[ir][ic] == 'X':
  9.             results[i] = -1
  10.         elif mapping[ir][ic] == 'D':
  11.             results[i] = 0   
  12.         else:
  13.             target[(ir, ic)] = i
  14.     q = list()
  15.     dist = dict()
  16.     for i in range(len(d)):
  17.         q.append((d[i][0], d[i][1]))
  18.         dist[(d[i][0], d[i][1])] = 0
  19.     finished = False
  20.     while q and (not finished):
  21.         print(q)
  22.         print(dist)
  23.         print(results)
  24.         size = len(q)
  25.         for _ in range(size):
  26.             cur = q.pop(0)
  27.             if cur in target:
  28.                 results[target[cur]] = dist[cur]
  29.                 if all([i != -2 for i in results]):
  30.                     finished = True
  31.             for n in get_neib(cur, r, c):
  32.                 if (n not in dist) and (mapping[n[0]][n[1]] not in ('X', 'D')):
  33.                     q.append(n)
  34.                     dist[n] = dist[cur] + 1
  35.     return results
  36.    
  37. def get_neib(cur, R, C):
  38.     r, c = cur
  39.     dirs = [[0, -1], [0, 1], [-1, 0], [1, 0]]
  40.     for dr, dc in dirs:
  41.         nr, nc = r + dr, c + dc
  42.         if (0 <= nr < R) and (0 <= nc < C):
  43.             yield (nr, nc)
  44.             
  45. mapping = [['X', 'D',  '', ''],
  46.            ['',  'X',  '', 'D'],
  47.            ['',  '',  '',  'X'],
  48.            ['',  'X',  'D',  'X']]
  49. locations = [[1, 0], [0, 3], [10, 9], [0, 1]]
  50. d = [[0, 1], [1, 3], [3, 2]]
  51. print(find_dis(mapping, locations, d))
  52.    
  53.             
  54.    
  55.         
  56.         
  57.         
  58.    
  59.             
  60.             
  61.       
  62.    
复制代码
回复

使用道具 举报

🔗
 楼主| nexttomexxd 2022-2-22 07:03:55 | 只看该作者
全局:
Given an integer matrix, find the length of the longest path that have same values. The matrix
has no boundary limits. (like, Google Maps - see edit for context)
From each cell, you can either move to two directions: horizontal or vertical. You may NOT
move diagonally or move outside of the boundary.
nums = [
[1,1],
[5,5],
[5,5]
]
Return 4 ( Four 5's).
Follow Up:

• follow up 是 如果 matrix 是 no boundaries 怎么解
  1. def find_longest(m):
  2.     def get_neib(r, c):
  3.         dirs = ((0, 1), (0, -1), (-1, 0), (1, 0))
  4.         for dr, dc in dirs:
  5.             nr, nc = r + dr, c + dc
  6.             if (0 <= nr < len(m)) and (0 <= nc < len(m[0])):
  7.                 yield (nr, nc)

  8.             
  9.     def dfs(r, c):
  10.         max_p = 0
  11.         for nr, nc in get_neib(r, c):
  12.             if (nr, nc) not in visited:
  13.                 if m[r][c] == m[nr][nc]:
  14.                     visited.add((nr , nc))
  15.                     pathl = dfs(nr , nc)
  16.                     max_p = max(pathl, max_p)
  17.                     visited.remove((nr , nc))
  18.         return max_p + 1
  19.    
  20.     result = 1
  21.     r, c = len(m), len(m[0])
  22.    
  23.     visited = set()
  24.     for ir in range(r):
  25.         for ic in range(c):
  26.             visited.add((ir, ic))
  27.             result = max(result, dfs(ir, ic))
  28.             visited.remove((ir, ic))
  29.     return result

  30. m = [[0,0,0,0,0],
  31.     [1,1,1,1,1],         
  32.     [1,1,1,0,0]]         
  33. print(find_longest(m))
  34.                
  35.                
  36.                
  37.    
  38.             
  39.    
  40.         
  41.         
  42.         
  43.    
  44.             
  45.             
  46.       
  47.    
复制代码
回复

使用道具 举报

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

本版积分规则

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