LeetCode 303 Range Sum Query - Immutable

标签: 数组类题目 LeetCode 发布于:2022-02-12 14:48:13 编辑于:2022-02-12 14:49:15 浏览量:1143

概述

https://leetcode.com/problems/range-sum-query-immutable/

暴力遍历法

class NumArray {
public:
    vector<int>* nums;
    NumArray(vector<int>& nums) {
        this->nums = &nums;
    }
    
    int sumRange(int left, int right) {
        int sum = 0;
        for (int i = left; i <= right; i ++ ) {
            sum += nums->at(i);
        }
        return sum;
    }
};

预计算前缀和

以下代码导致:runtime error: addition of unsigned offset to 0x6030000002e0 overflowed to 0x6030000002dc (stl_vector.h)

class NumArray {
public:
    vector<int> sums;
    NumArray(vector<int>& nums) {
        sums.push_back(nums[0]);
        for (int i = 1; i < nums.size(); i ++) {
            sums.push_back(sums[i - 1] + nums[i]);
        }
    }
    
    int sumRange(int left, int right) {
        int lsum = 0 ? left == 0 : sums[left - 1];
        return sums[right] - lsum;
    }
};

这是因为三元运算符写错了,Python 写多了淦,应该是 int lsum = left == 0 ? 0 : sums[left - 1],绝了,看了半天没看出问题来。

未经允许,禁止转载,本文源站链接:https://iamazing.cn/