privateintmergeSort(long[] preSum, int left, int right){ if (left >= right) { return0; } int mid = left + ((right - left) >> 1); //满足累加和在lower和upper之间的子数组的个数分为三部分: //左侧自己merge时找到的子数组个数(i、j都在左侧) //右侧自己merge时找到的子数组个数(i、j都在右侧) //左侧和右侧merge时找到的子数组个数(i在左侧、j在右侧) return mergeSort(preSum, left, mid) + mergeSort(preSum, mid + 1, right) + merge(preSum, left, mid, right); }
privateintmerge(long[] preSum, int left, int mid, int right){ // 统计i在左半段、j在右半段的情况下满足条件的子数组个数 // 左半段为[left, mid],右半段为[mid + 1, right] // j的左右边界分别为L和R int res = 0; int i = left; int L = mid + 1, R = mid + 1; while (i <= mid) { while (L <= right && preSum[L] - preSum[i] < lower) L++; while (R <= right && preSum[R] - preSum[i] <= upper) R++; res += R - L; i++; }
//进行归并排序的标准merge操作 int[] help = newint[right - left + 1]; int p1 = left, p2 = mid + 1; int idx = 0;