[leetcode]327. Count of Range Sum

来源:互联网 发布:js对象深拷贝 编辑:程序博客网 时间:2024/06/05 04:30

题目链接:https://leetcode.com/problems/count-of-range-sum/description/

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 = -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.

思路:

利用归并排序算法的将数组分成左右两边, 在合并左右数组的时候对于左边数组中的每一个元素在右边数组找到一个范围, 使得在这个范围中的的元素与左边的元素构成的区间和落在[lower, upper]之间.  即在右边数组找到两个边界, 设为m, n, 其中m是在右边数组中第一个使得sum[m] - sum[i] >= lower的位置, n是第一个使得sum[n] - sum[i] > upper的位置, 这样n-m就是与左边元素i所构成的位于[lower, upper]范围的区间个数. 因为左右两边都是已经有序的, 这样可以避免不必要的比较. 

其时间复杂度为O(n log n)

class Solution {  public:      int mergeSort(vector<long>& sum, int lower, int upper, int low, int high)      {          if(high-low <= 1) return 0;          int mid = (low+high)/2, m = mid, n = mid, count =0;          count = mergeSort(sum,lower,upper,low,mid) + mergeSort(sum,lower,upper,mid,high);          for(int i =low; i< mid; i++)          {              while(m < high && sum[m] - sum[i] < lower) m++;              while(n < high && sum[n] - sum[i] <= upper) n++;              count += n - m;          }          inplace_merge(sum.begin()+low, sum.begin()+mid, sum.begin()+high);          return count;      }        int countRangeSum(vector<int>& nums, int lower, int upper) {          int len = nums.size();          vector<long> sum(len + 1, 0);          for(int i =0; i< len; i++) sum[i+1] = sum[i]+nums[i];          return mergeSort(sum, lower, upper, 0, len+1);      }  };



原创粉丝点击