2023-11-13 LeetCode每日一题(区域和检索 - 数组可修改)

2023-11-13每日一题

一、题目编号

307. 区域和检索 - 数组可修改

二、题目链接

点击跳转到题目位置

三、题目描述

给你一个数组 nums ,请你完成两类查询。

  1. 其中一类查询要求 更新 数组 nums 下标对应的值
  2. 另一类查询要求返回数组 nums 中索引 left 和索引 right 之间( 包含 )的nums元素的 ,其中 left <= right

实现 NumArray 类:

  • NumArray(int[] nums) 用整数数组 nums 初始化对象
  • void update(int index, int val) 将 nums[index] 的值 更新 为 val
  • int sumRange(int left, int right) 返回数组 nums 中索引 left 和索引 right 之间( 包含 )的nums元素的 (即,nums[left] + nums[left + 1], …, nums[right])

示例 1:
2023-11-13 LeetCode每日一题(区域和检索 - 数组可修改)_第1张图片

提示:

  • 1 <= nums.length <= 3 * 104
  • -100 <= nums[i] <= 100
  • 0 <= index < nums.length
  • -100 <= val <= 100
  • 0 <= left <= right < nums.length
  • 调用 update 和 sumRange 方法次数不大于 3 * 104

四、解题代码

class NumArray {
    vector<int> Fenwick;
    vector<int> num;
    int n ;
    int lowbit(int x){
        return x&(-x);
    }

public:
    NumArray(vector<int>& nums) {
        num = nums;
        n = nums.size();
        Fenwick.resize(n+1);
        for(int i = 0; i < n; ++i){
            int index = i + 1;
            while(index <= n){
                Fenwick[index] += nums[i];
                index += lowbit(index);
            }
        }
    }
    
    void update(int index, int val) {
        int change = (val - num[index]);
        num[index] = val; 
        index++;
        while(index <= n){
            Fenwick[index] += change; 
            index += lowbit(index); 
        }
    }
    
    int calculate(vector<int> &Fenwick, int k){
	    int ret = 0;
	    while(k > 0){
		    ret += Fenwick[k];
		    k -= lowbit(k);
	    }
    return ret;
    }

    int sumRange(int left, int right) {
        return calculate(Fenwick, right+1) - calculate(Fenwick, left);    
    }
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * obj->update(index,val);
 * int param_2 = obj->sumRange(left,right);
 */

五、解题思路

(1) 树状数组。

你可能感兴趣的:(LeetCode每日一题,leetcode,算法,数据结构)