我得到一個二維陣列,其中 City 的 ID 是外部陣列的索引,內部陣列中的數字代表 Highways ID。
List = [[1,2],[4,5,8],[1,2,3],[1,3]]
我試圖找到一個孤立的城市,所以沒有高速公路將它連接到另一個城市(其中的所有高速公路在串列中都是唯一的,并且只出現一次?)。在上面的示例中,帶有 [4,5,8] 的城市 1 將被隔離,因此對函式 findIsolatedCity(List) 的呼叫應回傳 1。如果找不到城市,則該函式回傳 -1。
我嘗試用偽代碼實作一個解決方案,但我能想出的只是效率很低(4 個嵌套回圈)。有誰知道更有效的解決方案?
function findIsolatedCity(List)
isolated_city = -1
for city in range(len(List):
highway_count = 0
list_unique_highways = []
for highway in List[city]:
// check if the highway connects to any other city
for city_2 in range(len(List)): // iterate over all cities
for highway_2 in List[city_2]: // iterate over all highways in other cities
if highway == highway_2:
highway_count = 1
if highway_count == 1:
list_unique_highways.append(highway)
if length(list_) == length(List[city]):
isolated_city = city
return isolated_city
return isolated_city
uj5u.com熱心網友回復:
根據@user3386109 的評論,這里是 Python 中的解決方案:
from collections import Counter
cities = [[1, 2], [4, 5, 8], [1, 2, 3], [1, 3]]
def find_isolated_cities(cities):
cnt = Counter(h for c in cities for h in c)
return sum(all(cnt[h] == 1 for h in c) for c in cities)
print(find_isolated_cities(cities))
印刷:
1
首先,我們構造計數器來計算所有子串列中每個高速公路的數量,然后計算所有高速公路的計數都等于 1 的城市。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/514860.html
上一篇:回文鏈表Python解釋
