Input:
arr -- list of int, for example [0,1,2,3,4,5]
summary_index --list of index range, for example[(0,2),(3,4),(0,5)]
Output:
result -- list of sum of arr of the index range in summary_index, for example[3, 7,15]
传统写法:只需要一条sum函数结合列表就能完成
优点:代码简洁,只需要一行
缺点:算法复杂是O(n2) (说明:python自带的sum()函数实现就有for循环)
>>>arr=[0,1,2,3,4,5]
>>>summary_index=[(0,2),(3,4),(0,5)]
>>>result=[sum(arr[item[0]:item[1]+1]) for item in summary_index]
>>>print(result)
[3,7,15]
进阶写法:降低算法复杂度,大思路只能是空间换时间
优点:算法复杂度降到O(n)
缺点:无,多写点代码又算什么呢?
思路:
1) 先生成一个数组arr_sum,元素是arr前n项的和(n<=len(arr))
2) arr数组x到y的和,如果x等于0,和等于arr_sum[y];如果x大于0,和等于arr_sum[y]-arr_sum[x-1]
>>> arr=[0,1,2,3,4,5]
>>> summary_index=[(0,2),(3,4),(0,5)]
>>> for i,value in enumerate(arr):
... sum=value if i==0 else arr_sum[i-1]+value
... arr_sum.append(sum)
...
>>> print(arr_sum)
[0, 1, 3, 6, 10, 15]
>>> result=[]
>>> for item_sum in summary_index:
... value=arr_sum[item_sum[1]]-arr_sum[item_sum[0]-1] if item_sum[0]>0 else arr_sum[item_sum[1]]
... result.append(value)
...
>>> print(result2)
[3, 7, 15]