本文共 862 字,大约阅读时间需要 2 分钟。
Fedwick树(也称为Fenwick树或树状数组)是一种高效处理前缀和查询的数据结构。以下是用Objective-C实现的Fedwick树的完整代码示例。
#import @interface FenwickTree : NSObject @property (nonatomic, strong) NSMutableArray *tree; @end @implementation FenwickTree - (id)initWithSize:(int)size{ self.tree = [NSMutableArray new]; [self.tree addDouble:0.0]; // 初始化数组,第一个元素为0.0 return self; } - (void)update:(int)index value:(double)value{ while (index < self.tree.count){ self.tree[index] += value; index += index & -index; // 计算下一个需要更新的位置 } } - (double)query:(int)index{ double result = 0.0; while (index > 0){ result += self.tree[index]; index -= index & -index; // 计算当前位置的前缀和 } return result; } @end Fedwick树是一种高效的数据结构,能够在O(log n)时间复杂度内完成前缀和查询和更新操作。上述代码展示了Objective-C中实现Fedwick树的基本思路和常用方法。
转载地址:http://tsnfk.baihongyu.com/