Algorithm Notes
  • Introduction
  • Search & Backtracking 搜索与回溯
    • Tree 与 BackTracking 的比较
    • Subsets, Combination 与 Permutation
    • Subsets & Combinations & Combination Sum
    • 枚举法
    • N 皇后 + 矩阵 Index Trick
    • Sudoku 数独 + 矩阵 Index Trick
    • Word Ladder I & II
    • Number of ways 类
    • DFS flood filling
    • Strobogrammatic 数生成
    • String 构造式 DFS + Backtracking
    • Word Pattern I & II
    • (G) Binary Watch
    • (FB) Phone Letter Combination
    • 常见搜索问题的迭代解法
  • String,字符串类
    • 多步翻转法
    • Substring 结构和遍历
    • Palindrome 问题
    • Palindrome Continued
    • String / LinkedList 大数运算
    • 序列化与压缩
    • 5/24 String 杂题
    • Knuth–Morris–Pratt 字符串匹配
    • Lempel–Ziv–Welch 字符串压缩算法
    • (G) Decode String
    • (G) UTF-8 Validation
  • Binary Tree,二叉树
    • 各种 Binary Tree 定义
    • LCA 类问题
    • 三序遍历,vertical order
    • Post order traversal 的应用
    • Min/Max/Balanced Depth
    • BST
    • 子树结构
    • Level Order traversal
    • Morris 遍历
    • 修改结构
    • 创建 / 序列化
    • 子树组合,BST query
    • 路径与路径和
    • NestedInteger 类
    • (FB) 从 Binary Tree Path 看如何递归转迭代
    • (FB) Binary Tree Path 比较路径大小
    • 比较好玩的 Binary Tree 概率题
  • Segment & Fenwick Tree,区间树
    • Segment Tree 基础操作
    • Segment Tree 的应用
    • Fenwick Tree (Binary Indexed Tree)
    • Range Sum Query 2D - Immutable
  • Union-Find,并查集
    • Union-Find,并查集基础
    • Union-Find, 并查集应用
  • Dynamic Programming, 动态规划
    • 6/20, 入门 House Robber
    • 7/12, Paint Fence / House
    • 6/24, 滚动数组
    • 6/24, 记忆化搜索
    • 6/24, 博弈类 DP
    • 博弈类DP, Flip Game
    • 6/25, 区间类DP
    • 6/27, subarray 划分类,股票
    • 7/2, 字符串类
    • Bomb Enemies
    • 8/2,背包问题
    • (G) Max Vacation
    • (11/4新增) AST 子树结构 DP
  • LinkedList,链表
    • 6/9, LinkedList,反转与删除
    • 6/11, LinkedList 杂题
    • (FB) 链表的递归与倒序打印
  • LinkedIn 面经,算法题
    • 6/17, LinkedIn 面经题
    • 6/28, LinkedIn 面经题
    • 7/6, LinkedIn 面经
    • Shortest Word Distance 类
    • DFA Parse Integer
  • Two Pointers,双指针
    • 3 Sum, 3 Sum Closest / Smaller, 4 Sum
    • 对撞型,灌水类
    • 对撞型,partition类
    • Wiggle Sort I & II
    • 双指针,窗口类
    • 双指针,窗口类
    • Heap,排序 matrix 中的 two pointers
  • Bit & Math,位运算与数学
    • Bit Manipulation,对于 '1' 位的操作
    • Math & Bit Manipulation, Power of X
    • 坐标系 & 数值计算类
    • Add Digits
    • 用 int 做字符串 signature
  • Interval 与 扫描线
    • Range Addition & LCS
    • 7/5, Interval 类,扫描线
  • Trie,字典树
    • 6/9, Trie, 字典树
  • 单调栈,LIS
    • 4/13 LIS
    • 栈, 单调栈
    • Largest Divisible Subset
  • Binary Search 类
    • Matrix Binary Search
    • Array Binary Search
    • Find Peak Element I & II
    • **Median of Two Sorted Arrays
  • Graph & Topological Sort,图 & 拓扑排序
    • 有向 / 无向 图的基本性质和操作
    • 拓扑排序, DFS 做法
    • 拓扑排序, BFS 做法
    • Course Schedule I & II
    • Alien Dictionary
    • Undirected Graph, BFS
    • Undirected Graph, DFS
    • 矩阵,BFS 最短距离探索
    • 欧拉回路,Hierholzer算法
    • AI, 迷宫生成
    • AI, 迷宫寻路算法
    • (G) Deep Copy 无向图成有向图
  • 括号与数学表达式的计算
  • Iterator 类
  • Majority Element,Moore's Voting
  • Matrix Inplace Operations
  • 常见数据结构设计
  • (G) Design / OOD 类算法题
  • 随机算法 & 数据结构
  • (FB) I/O Buffer
  • (FB) Simplify Path, H-Index I & II
  • (FB) Excel Sheet, Remove Duplicates
  • Integer 的构造,操作,序列化
  • Frequency 类问题
  • Missing Number 类,元素交换,数组环形跳转
  • 8/10, Google Tag
  • (FB) Rearrange String k Distance Apart
  • Abstract Algebra
    • Chap1 -- Why Abstract Algebra ?
    • Chap2 -- Operations
    • Chap3 -- The Definition of Groups
Powered by GitBook
On this page
  • 给定 n 个元素 array,时间复杂度为
  • Fenwick Tree 主要用于求各种维度的区间 sum,主要缺点在于建树时间长于 segment tree ,需要 O(n log n) 时间,还有和面试官解释的时候比较麻烦。。主要优点是好写,而且非常容易扩展到多维情况。
  • Youtube 视频讲解
  • binary index tree ,另一个教程贴在这里,还有这里,加上这个陈老师推荐的中文帖子
  • Range Sum Query - Mutable
  • 图文并茂的视频讲解~
  • 在图上的树状结构中,任意一个点的 parent 等于其 binary representation 的最右一个 1 的 bit 上再 +1; 比如 3 = 0011 ,parent = 8 = 0100.
  • 从 child 到 parent 这条线,代表着更新。上图的结构,也是相对于更新操作的 tree structure.
  • 而 query 是另一种结构和搜索过程,是一步一步把 index 的 binary representation 拆出来,变成 13 = 001011 ,对应 BIT[001000] + BIT[000010] + BIT[000001] 的过程
  • Range Sum Query 2D - Mutable
  • 这题如果 int[][] nums 直接指向 matrix 会在 update 操作之后得到错误结果,目前我还没仔细想为什么。。。稳妥起见还是老老实实新建一个吧。

Was this helpful?

  1. Segment & Fenwick Tree,区间树

Fenwick Tree (Binary Indexed Tree)

PreviousSegment Tree 的应用NextRange Sum Query 2D - Immutable

Last updated 4 years ago

Was this helpful?

陈老师说花三天时间研究明白这个没啥意义。不过我看了小半天就看完了。。也没啥难的嘛。。。

给定 n 个元素 array,时间复杂度为

  • build O(n log n)

  • update O(log n)

  • query O(log n)

Fenwick Tree 主要用于求各种维度的区间 sum,主要缺点在于建树时间长于 segment tree ,需要 O(n log n) 时间,还有和面试官解释的时候比较麻烦。。主要优点是好写,而且非常容易扩展到多维情况。

Youtube

,另一个教程贴在,还有,加上这个陈老师推荐的

The two's complement of an N-bit number is defined as the complement with respect to 2^N; in other words, it is the result of subtracting the number from 2^N

和之前那道题一样,把 segment tree 改成 fenwick tree 的写法如下:

  • fenwick tree 可以用 array 存,纯靠 bit manipulation 操作。

  • tree 有一个 dummy root,所以对于单维度大小为 n 的输入,实际数组会在每一个维度 +1 的 padding.

  • 因此在每次更新原数组 index 位置的数时,在树上实际的 update 位置是 index + 1.

  • 树的 update 过程很像机器学习里面的 forward/backward propagation,每次更新之后先计算 diff,再把 diff 传导过去。因此 fenwick tree 有时候需要一个数组去保存所有值,用于计算 diff.

  • 对于给定 index,树的 update 是一个 index 逐渐增加的过程,相对的,树的求和是个不断寻找 parent,index 逐渐减小的过程。

在图上的树状结构中,任意一个点的 parent 等于其 binary representation 的最右一个 1 的 bit 上再 +1; 比如 3 = 0011 ,parent = 8 = 0100.

从 child 到 parent 这条线,代表着更新。上图的结构,也是相对于更新操作的 tree structure.

而 query 是另一种结构和搜索过程,是一步一步把 index 的 binary representation 拆出来,变成 13 = 001011 ,对应 BIT[001000] + BIT[000010] + BIT[000001] 的过程

public class NumArray {
    int[] fenwickTree;
    int length;
    int[] arr;
    public NumArray(int[] nums) {
        length = nums.length;
        arr = new int[length];
        fenwickTree = new int[length + 1];

        for(int i = 0; i < length; i++){
            update(i, nums[i]);
        }
    }

    void update(int i, int val) {
        int diff = val - arr[i];
        arr[i] = val;
        for(int index = i + 1; index <= length; index += (index & -index)){
            fenwickTree[index] += diff;
        }
    }

    private int getSum(int i){
        int sum = 0;
        while(i > 0){
            sum += fenwickTree[i];
            i -= (i & -i);
        }
        return sum;
    }

    public int sumRange(int i, int j) {
        return getSum(j + 1) - getSum(i);
    }
}

Fenwick Tree 在增加维度上的优势在这题中体现的非常好。

这题如果 int[][] nums 直接指向 matrix 会在 update 操作之后得到错误结果,目前我还没仔细想为什么。。。稳妥起见还是老老实实新建一个吧。

增加维度的逻辑非常简单,只需要把对应的 tree array 增加维度就可以了,这时候新的getSum(i,j)所代表的是,从 (0,0) 开始到 (i,j) 的矩形范围内的 sum,相对于一维 fenwick tree 中的 (0, index) 的和。

  • fenwick tree 本质上是树状的 prefix sum 数组,维度非常灵活,每一个位置上的getSum()都代表当前坐标到 origin 原点的 cumulative sum.

  • 因此对于矩阵中任意矩形,都可以看做四个以原点为起点的矩形的相互覆盖,可以以同样的时间复杂度求解矩阵中任意位置任意形状的矩形和。

public class NumMatrix {
    int[][] fenwickTree;
    int[][] nums;
    int rows;
    int cols;

    public NumMatrix(int[][] matrix) {
        if(matrix == null || matrix.length == 0) return;

        rows = matrix.length;
        cols = matrix[0].length;
        fenwickTree = new int[rows + 1][cols + 1];
        nums = new int[rows][cols];

        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                update(i, j, matrix[i][j]);
            }
        }
    }

    public void update(int row, int col, int val) {
        int diff = val - nums[row][col];
        nums[row][col] = val;
        for(int i = row + 1; i <= rows; i += (i & -i)){
            for(int j = col + 1; j <= cols; j += (j & -j)){
                fenwickTree[i][j] += diff;
            }
        }
    }

    private int getSum(int row, int col){
        int sum = 0;
        for(int i = row; i > 0; i -= (i & -i)){
            for(int j = col; j > 0; j -= (j & -j)){
                sum += fenwickTree[i][j];
            }
        }
        return sum;
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        return getSum(row2 + 1, col2 + 1) + getSum(row1, col1) -
               getSum(row1, col2 + 1) - getSum(row2 + 1, col1);
    }
}

Range Sum Query 2D - Mutable
视频讲解
binary index tree
这里
这里
中文帖子
Range Sum Query - Mutable
图文并茂的视频讲解~