leetcode 327. Count of Range Sum 字段和问题
来源:互联网 发布:窃听风暴知乎 编辑:程序博客网 时间:2024/06/05 22:42
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.
Example:
Given nums = [-2, 5, -1], lower = -2, upper = 2,
Return 3.
The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.
我没有想到更好的方法,直接循环做的。
代码如下:
/* * 有使用归并排序或者线段树的该方法,可以优化到 O(long(n)) * 不过我肯定是想不到 * 所以我这里的是循环遍历的 O(n^2)解法 * */class Solution { public int countRangeSum(int[] nums, int lower, int upper) { if(nums==null || nums.length<=0) return 0; long[] sum=new long[nums.length]; sum[0]=nums[0]; for(int i=1;i<nums.length;i++) sum[i]=sum[i-1]+nums[i]; int count=0; for(int i=0;i<nums.length;i++) { for(int j=i;j<nums.length;j++) { long tmp=i==0?sum[j]:sum[j]-sum[i-1]; if(tmp>=lower && tmp<=upper) count++; } } return count; }}
阅读全文
0 0
- leetcode 327. Count of Range Sum 字段和问题
- LeetCode 327. Count of Range Sum(区间和计数)
- <LeetCode OJ> 327. Count of Range Sum
- leetcode 327. Count of Range Sum
- Leetcode 327. Count of Range Sum[hard]
- LeetCode 327. Count of Range Sum
- leetcode 327.Count of Range Sum
- LeetCode 327. Count of Range Sum
- LeetCode 327. Count of Range Sum
- leetcode 327. Count of Range Sum
- [leetcode]327. Count of Range Sum
- leetcode 327. Count of Range Sum
- leetcode Count of Range Sum
- LeetCode Count of Range Sum
- [LeetCode]Count of Range Sum
- Leetcode Count of Range Sum
- leetcode Count of Range Sum
- []LeetCode]Count of Range Sum
- hibernate注解异常:java.lang.NoSuchMethodError javax.persistence.JoinColumn.foreignKey()Ljavax/persistenc
- CodeForces
- Hibernate入门-搭建框架实现基本的增删改查
- 提高Ubuntu音效
- python引入外部文件
- leetcode 327. Count of Range Sum 字段和问题
- 栈的应用1--圆括号平衡
- 微信热修复方案深入理解
- js创建对象
- 渗透测试 | 无线渗透 | 5-身份认证与密钥交换
- 04jQuery源码解析
- 旋转卡壳伪代码
- 教你无视校园网认证
- 画圆