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;    }}