小编Mic*_*ael的帖子

O(n)中各点的绝对距离

我陷入了困境.问题的一部分需要计算各点的点的绝对距离之和.| x - x1 | + | x - x2 | + | x - x3 | + | x - x4 | ....

我必须在每个点的O(n)中计算这个距离,同时在数组中迭代,例如:

array = {3,5,4,7,5}
与先前点的距离之和

dis[0] = 0;
dis[1] = |3-5| = 2
dis[2] = |3-4| + |5-4| = 2
dis[3] = |3-7| + |5-7| + |4-7| = 9
dis[4] = |3-5| + |5-5| + |4-5| + |7-5| = 5
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议算法这样做吗?将理解小于O(n ^ 2)的算法(不一定是O(n)).

代码为O(n ^ 2)

REP(i,n){
   LL ans = 0;
   for(int j=0;j<i;j++)
      ans= ans + …
Run Code Online (Sandbox Code Playgroud)

c algorithm graph distance dynamic-programming

7
推荐指数
1
解决办法
261
查看次数

使用列表中的键创建字典,将值作为另一个列表中的列表创建

我有一份清单

key_list = ['m.title', 'm.studio', 'm.gross', 'm.year']
cols = [
    ['Titanic', 'The Lord of the Rings: The Return of the King', 'Toy Story 3'], 
    ['Par.', 'NL', 'BV'],
    ['2186.8', '1119.9', '1063.2'],
    ['1997', '2003', '2010']
]
Run Code Online (Sandbox Code Playgroud)

我想构建一个字典table_dict,其键是key_list的元素,值是cols的各个子列表.

我目前的代码如下:

i = 0
for key in key_list:
    table_dict[key] = cols[i]
    i = i + 1

return table_dict
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到错误,但当我运行它时,我得到:

dict[key] = cols[i]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

python dictionary list

1
推荐指数
1
解决办法
128
查看次数

标签 统计

algorithm ×1

c ×1

dictionary ×1

distance ×1

dynamic-programming ×1

graph ×1

list ×1

python ×1