本帖最后由 825344491 于 2023-8-30 23:25 编辑
Akuna Quant Research OA,三道算法题,一个小时,第三题全部Test Cases AC不算特别直接(暴力解部分Test Cases会超时),所以题量不算小。
1. Frequency Sort. 1point 3acres
用Counter()计算出items中各元素的频率,然后在排序时将频率作为自定义规则,比较简单
Python3:- def itemSort(items):
- freq_counter = Counter(items)
- # Sort by frequency and then by value
- return = sorted(items, key=lambda x: (freq_counter[x], x))
复制代码 2. Delivery Management System
Dijkstra应用题。. 1point 3 acres
因为图为无向图,所以建图时注意同一条边的两个方向都要加。
heap里放的tuple第一个值均为1(图为无权图),第二个值为节点号-1(原始节点号从1开始),如此heap在pop元素时就会先按照距离再按照节点号。
【无权图也可以直接用BFS,这里为了省事直接默写了Dijkstra】
注意:题目不是返回距离,而是除初始节点外的访问顺序(即每个节点pop出heap的顺序),因此在每个节点刚被pop出heap时记录答案。
. 1point3acres.com
Python3:.1point3acres
- import heapq
- def order(city_nodes, city_from, city_to, company):
- graph = [[] for _ in range(city_nodes)].
- for i in range(len(city_from)):
- graph[city_from[i] - 1].append((1, city_to[i] - 1)).google и
- graph[city_to[i] - 1].append((1, city_from[i] - 1))
- heap = [(0, company - 1)].google и
- distance = [city_nodes + 1 for _ in range(city_nodes)]
- distance[company - 1] = 0
- city_order = []
- while heap:
- cur = heapq.heappop(heap)
- if cur[1] + 1 != company:
- city_order.append(cur[1] + 1)
-baidu 1point3acres - for vertex in graph[cur[1]]:
- if distance[cur[1]] + vertex[0] < distance[vertex[1]]:
- distance[vertex[1]] = distance[cur[1]] + vertex[0]
- heapq.heappush(heap, (distance[vertex[1]], vertex[1]))
- return city_order
- city_nodes = 5
- city_from = [1, 2, 2]
- city_to = [2, 3, 4]. 1point 3 acres
- company = 1. .и
- print('Case in description: ', order(city_nodes, city_from, city_to, company))
- city_nodes = 5
- city_from = [1, 1, 2, 3, 1]
- city_to = [2, 3, 4, 5, 5]
- company = 1
- print('Test Case 0: ', order(city_nodes, city_from, city_to, company))
- city_nodes = 3
- city_from = [1]
- city_to = [2]
- company = 2
- print('Test Case 1: ', order(city_nodes, city_from, city_to, company))
复制代码 3. Extraordinary Substrings. 1point 3 acres
这道题感觉不算是纯粹的滑动窗口,因为两重for循环是把所有可能的子串都遍历了一遍。但符合滑动窗口特质的地方是第8行和第10行,即每次变更, 26):
string_int[chr(ord('a') + i)] = (i - 2) // 3 + 2
. 1point3acres
extraordinary = 0
for i in range(length):
string_sum = 0
for j in range(i, length):.--
string_sum += string_int[input_str[j]]
if not string_sum % (j - i + 1):
extraordinary += 1
return extraordinary
print(countSubstrings('abcd')) # 6
print(countSubstrings('bdh')) # 4
print(countSubstrings('abcd')) # 6
``` |