fast Update, sum operation of 2D matrix

Given a 2D space of maximum size NxN which supports two operations :
[1] void UPDATE(x,y,v) - sets the value of cell [x,y] to v
[2] int SUM(x1,y1,x2,y2) - returns sub-rectangle sum (x1,y1) to (x2,y2)
inclusive, and there is an infinite stream of such 2 types of operations which have to supported. How would you store the values for efficient updates and retrievals ?

SOLUTION

A. optimize for the case where updates are frequent - make update as fast as possible

Store the values in a 2D array - x and y are indexes into the array
To update O(1): array[x][y] = v
To sum O(n^2):
sum = 0
for (int x = x1; x <= x2; x++) {
  for (int y = y1; y <= y2; y++ {
    sum += array[x][y];
}
return sum;


B. To have the sum be O(1), store the sum of every element in (0,0) to (i,j) in arr[i][j]

1   3   6
5   12  21
12  27  45

SUM = arr[x2][x2] - arr[x1-1][y2] - arr[x2][y1-1] + arr[x1-1][y1-1]
UPDATE[i,j] only have to take care of everything on or after i,j in sum array
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值