栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

算法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法

文章目录
  • 树状数组简介
  • 一、关键要点
      • 1. lowbit操作
      • 2. 数组中元素的实质
      • 3. 树状数组的结构
  • 二、Java实现
  • 总结


树状数组简介

树状数组(Binary Index Tree, BIT)可以以 O ( l o g n ) O(logn) O(logn)的时间复杂度实现单点修改、区间查询等功能。

相关LeetCode问题


一、关键要点 1. lowbit操作

用于获取某数的最低位的1,计算公式为:
x & (   x + 1 ) x & (~x+1) x&( x+1) 或 x & ( − x ) x & (-x) x&(−x)

  • 设 x x x为20,则其二进制表示为10100
  • 则   x + 1 ~x+1  x+1为01011+1 --> 01100
  • 可见, x x x和   x + 1 ~x+1  x+1最低位的1左边每一位都不同(包括符号位),而最低位的1以及其右边每一位都相同。
  • 两者相与,则只有 x x x最低位的1会保留下来

lowbit 操作在树状数组中及其重要

2. 数组中元素的实质

设原数组为 n u m s nums nums,树状数组为 t r e e tree tree,为了方便取值,使两个数组的下标均从1开始。则:

  • 若 i i i的二进制表示为 ∗ ∗ ∗ 100 ***100 ∗∗∗100
  • 则 t r e e [ i ] tree[i] tree[i]是nums中第 ∗ ∗ ∗ 100 ***100 ∗∗∗100, ∗ ∗ ∗ 001 ***001 ∗∗∗001, ∗ ∗ ∗ 010 ***010 ∗∗∗010, ∗ ∗ ∗ 011 ***011 ∗∗∗011 个元素的和

换一种方式描述

  • 若取出 i i i的最低位1的结果为 a a a
  • 则 t r e e [ i ] tree[i] tree[i]= n u m s [ i ] + n u m s [ i − 1 ] + n u m s [ i − 2 ] + . . . + n u m s [ i − a + 1 ] nums[i]+nums[i-1]+nums[i-2]+...+nums[i-a+1] nums[i]+nums[i−1]+nums[i−2]+...+nums[i−a+1]
3. 树状数组的结构

二、Java实现
public class BinaryIndexTree {

    private int[] tree;
    private int[] nums;
    public BinaryIndexTree(int[] nums) {
        this.nums = nums;
        // 数组长度+1,避免采用0下标
        this.tree = new int[nums.length+1];
        for(int i = 0; i
            this.insert(i,nums[i]);
        }
    }

    
    private void insert(int index, int val){
        // nums索引转为tree索引
        index++;
        for(int i = index; i
            this.tree[i]+=val;
        }
    }

    
    public void update(int index, int val) {
        try {
            checkIndex(index);
            // nums索引转为tree索引
            index++;
            // 更新树状数组和原数组
            for(int i = index; i
                this.tree[i] = this.tree[i] + val - nums[index-1];
            }
            nums[index-1] = val;
        } catch (Exception e) {
            System.out.println("下标越界,修改失败");
        }

    }

    
    public int sumRange(int left, int right) {
        try {
            checkIndex(left,right);
            if(right
            e.printStackTrace();
        }
        return -1;
    }

    
    public int query(int index){
        // nums索引转为tree索引
        index++;
        int res = 0;
        for(int i = index; i>0; i-=lowBit(i)){
            res+=this.tree[i];
        }
        return res;
    }

    
    private void checkIndex(int ... indexes) throws Exception {
        for (int index : indexes) {
            if(index<0||index>=nums.length)throw new Exception();
        }
    }

    
    int lowBit(int x){
        return x&(-x);
    }
    
}

总结

树状数组是一种十分优雅的数据结构,自己现在对它的了解还不够深,之后要多接触相关题目,把树状数组练会,练精!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914256.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号