<LeetCode OJ> 327. Count of Range Sum

本文介绍了一个算法问题——计数范围内和,即计算数组中所有子数组的和落在指定区间内的总数。文章首先给出了一个时间复杂度为O(n^2)的简单解法,并通过实例解释了如何计算每个子数组的和。随后,文章提出了一种更高效的解法,利用分治思想和归并排序中的思想来优化计算过程。

327. Count of Range Sum

My Submissions
Total Accepted: 93  Total Submissions: 316  Difficulty: Hard

给定一个整数数组nums,返回该数组某个"范围内的和"在 [ lower,upper ] 之间的总数量

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.

Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.注意:你的算法必须比O(N^2)性能更快

Example:
Given nums = [-2, 5, -1]lower = -2upper = 2,
Return 3.
The three ranges are : [0, 0][2, 2][0, 2] and their respective sums are: -2, -1, 2.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Similar Problems
  (H) Count of Smaller Numbers After Self


分析:

1,朴素的模拟思路:

1),令S(i)表示前i个数之和,比如,比如【-2,5,-1】,s(0)=-2,s(1)=3,s(2)=2...先将所有的和计算出来

2),S(i, j)表示数组中位置i到j的元素之和,S(i, j)=S(j)-S(i)+a(i)

但是这样做time,o(n^2),space,o(n), Time Limit Exceeded

class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        if(nums.size()==0)
            return 0;
        vector<int> sums(nums.size(),0);
        sums[0]=nums[0];
        for (int i = 1; i < nums.size(); ++i)
            sums[i] = sums[i-1] + nums[i];
        int cnt = 0;
        for (int i = 0; i < nums.size(); ++i)
            for (int j = i; j < nums.size(); ++j)
            {
                int gapsum=sums[j] - sums[i]+nums[i];
                if ( gapsum>= lower && gapsum <= upper)
                    cnt++;
            }
        return cnt;
    }
};

优化中.......若干时间后....不会!

参考讨论区:对两层for循环进行优化

class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        int size_nums=nums.size();
        vector<long> sums(size_nums+1, 0);
        for(int i=0; i<size_nums; i++)   
            sums[i+1]=sums[i]+nums[i];
        return help(sums, 0, size_nums+1, lower, upper);
    }
    
    int help(vector<long> &sums, int start, int end, int lower, int upper){
        /***  end condition  ***/
        if(end - start <= 1) return 0;
        /***  recursive devidely  ***/
        int mid=(start+end)/2;
        int count=help(sums, start, mid, lower, upper) + help(sums, mid, end, lower, upper);
        int j=mid, k=mid, t=mid;
        vector<long> cache(end-start, 0);
        for(int i=start, r=0; i<mid; i++, r++)
        {
            while(k<end && sums[k]-sums[i] < lower) k++;
            while(j<end && sums[j]-sums[i] <= upper) j++;
            /***  merge sorting parts  ***/
            while(t<end && sums[t] < sums[i])  cache[r++]=sums[t++];
            cache[r]=sums[i];
            count+=j-k;
        }
        //copy the merge sorted array to the original sums
        for(int i=0; i<t-start; i++)  
            sums[start+i]=cache[i];
        return count;
    }
};




注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/50492602

原作者博客:http://blog.youkuaiyun.com/ebowtang


<think>我们正在解决LeetCode题目时出现的NameError: Solution类未定义的问题。这个问题通常发生在尝试运行或测试TwoSum(两数之和)问题的解决方案时。 根据引用内容,我们有几个不同版本的TwoSum解决方案,但都是定义一个名为Solution的类,其中包含一个名为twoSum的方法。 错误信息"NameError: Solution class not defined"意味着在代码执行环境中,没有找到名为Solution的类。这可能是由于以下原因: 1. 代码没有正确包含Solution类的定义。 2. 代码存在语法错误,导致类定义失败。 3. 运行环境没有正确加载代码。 我们以引用[1]中的Python代码为例: ```python class Solution: def twoSum(self, nums, target): a = {} for i, v in enumerate(nums): if v in a: return a[v], i a[target - v] = i ``` 如果我们在运行这段代码之前没有定义Solution类,或者代码中有语法错误(比如缩进错误),就会导致这个错误。 解决步骤: 1. 确保在运行代码之前,已经完整定义了Solution类。例如,在LeetCode的在线编辑器中,我们只需要提交这个类,而不需要额外的代码(如创建实例和调用方法的代码)。 2. 在本地测试时,我们需要创建一个Solution类的实例,然后调用twoSum方法,并传入参数。但是,注意LeetCode要求我们只提交类,而不需要提交测试代码。如果我们在本地测试,需要自己编写测试代码。 例如,在本地测试时,我们可以这样写: ```python class Solution: def twoSum(self, nums, target): a = {} for i, v in enumerate(nums): if v in a: return [a[v], i] # 注意:LeetCode要求返回的是列表,所以这里最好返回列表 a[target - v] = i # 测试代码 if __name__ == '__main__': sol = Solution() print(sol.twoSum([2, 7, 11, 15], 9)) # 应该输出 [0,1] 或 [1,0]?注意:在代码中,我们返回的是先出现的数的索引和当前索引,而当前索引大于先出现的索引。对于[2,7],当遍历到7时,2已经在a中,所以返回a[2](即0)和当前索引1。 ``` 3. 注意代码缩进:在Python中,缩进非常重要,必须一致。通常使用4个空格。 4. 另外,注意方法名的大小写:twoSum,在Python中习惯使用下划线分隔(如two_sum),但LeetCode的题目要求方法名为twoSum,所以必须保持一致。 5. 如果是在LeetCode提交,确保没有额外的输出(如print语句)和多余的代码(如测试代码)。 6. 如果是在本地运行,确保保存了文件,并且运行的是包含Solution类定义的文件。 7. 如果使用Jupyter Notebook,确保已经运行了包含Solution类定义的单元格。 根据引用[5]的例子,输入是[2,7,11,15],目标值是9,返回[0,1](因为2+7=9,索引0和1)。 因此,遇到NameError时,请检查: - 是否正确定义了Solution类(包括正确的缩进)。 - 在需要实例化Solution类的地方,是否在定义之后(比如先定义类,再创建实例)。 - 是否有拼写错误(如将Solution拼错)。 如果问题仍然存在,请提供具体的代码和运行环境,以便进一步排查。 下面,我们根据引用[1]的Python代码,写一个完整的本地测试示例(注意:在LeetCode提交时,只需要提交Solution类,不需要提交测试部分):</think>### 解决 LeetCode "Solution类未定义" 的错误 在 LeetCode 上提交 TwoSum 解决方案时遇到 `NameError: Solution class not defined` 错误,通常由以下原因造成: #### 1. **代码结构错误**(最常见原因) LeetCode 要求严格遵循指定的类名和方法签名: ```python # 必须包含 Solution 类定义 class Solution: # ✅ 正确定义类 def twoSum(self, nums: List[int], target: int) -> List[int]: # ✅ 方法签名匹配 num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i ``` **错误示例**: ```python # ❌ 缺少类定义 def twoSum(nums, target): # 直接定义函数 # ...代码... ``` #### 2. **本地测试时的环境问题** 在本地运行需额外处理: ```python # 本地测试时需添加执行代码 class Solution: # ...twoSum方法... if __name__ == "__main__": sol = Solution() print(sol.twoSum([2, 7, 11, 15], 9)) # ✅ 创建实例调用方法 ``` #### 3. **语法错误导致类未定义** 常见语法问题: - 缩进错误(Python 严格要求4空格缩进) - 缺少冒号 `:` 在 `class Solution:` 和 `def twoSum(...):` 后 - 方法参数类型提示错误(如误用 `List` 而未导入) #### 4. **LeetCode 平台特殊要求** - 方法必须返回指定类型(如 `List[int]`) - 不可修改方法签名(参数名/顺序必须一致) - 不能添加额外输出(如 `print` 语句) ### 正确解决方案示例 ```python from typing import List # 类型提示需要导入 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: seen = {} for i, num in enumerate(nums): diff = target - num if diff in seen: return [seen[diff], i] seen[num] = i return [] # 确保所有路径有返回值 ``` ### 验证步骤 1. **检查类定义**:确认存在 `class Solution:` 2. **检查方法签名**:`def twoSum(self, nums: List[int], target: int) -> List[int]` 3. **本地测试**:在实例化后调用 `sol.twoSum(...)` 4. **提交代码**:删除所有测试代码后再提交 > 在 LeetCode 的代码编辑器中,只需提交 `Solution` 类(不含测试代码),平台会自动实例化并调用方法[^1][^2][^3]。 --- ### 相关问题 1. 如何正确处理 LeetCode 中的类型提示(如 `List[int]`)? 2. 为什么 LeetCode 的输入参数有时是 `self`,本地运行时却不需要? 3. 除了 `NameError`,还有哪些常见的 LeetCode 提交错误? 4. 如何为 TwoSum 问题设计有效的测试用例?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值