您的位置:首页 > 健康 > 美食 > Java | Leetcode Java题解之第327题区间和的个数

Java | Leetcode Java题解之第327题区间和的个数

2024/12/24 1:27:39 来源:https://blog.csdn.net/m0_57195758/article/details/141100461  浏览:    关键词:Java | Leetcode Java题解之第327题区间和的个数

题目:

题解:

class Solution {public int countRangeSum(int[] nums, int lower, int upper) {long s = 0;long[] sum = new long[nums.length + 1];for (int i = 0; i < nums.length; ++i) {s += nums[i];sum[i + 1] = s;}return countRangeSumRecursive(sum, lower, upper, 0, sum.length - 1);}public int countRangeSumRecursive(long[] sum, int lower, int upper, int left, int right) {if (left == right) {return 0;} else {int mid = (left + right) / 2;int n1 = countRangeSumRecursive(sum, lower, upper, left, mid);int n2 = countRangeSumRecursive(sum, lower, upper, mid + 1, right);int ret = n1 + n2;// 首先统计下标对的数量int i = left;int l = mid + 1;int r = mid + 1;while (i <= mid) {while (l <= right && sum[l] - sum[i] < lower) {l++;}while (r <= right && sum[r] - sum[i] <= upper) {r++;}ret += r - l;i++;}// 随后合并两个排序数组long[] sorted = new long[right - left + 1];int p1 = left, p2 = mid + 1;int p = 0;while (p1 <= mid || p2 <= right) {if (p1 > mid) {sorted[p++] = sum[p2++];} else if (p2 > right) {sorted[p++] = sum[p1++];} else {if (sum[p1] < sum[p2]) {sorted[p++] = sum[p1++];} else {sorted[p++] = sum[p2++];}}}for (int j = 0; j < sorted.length; j++) {sum[left + j] = sorted[j];}return ret;}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com