class Solution { fun waysToSplit(nums: IntArray): Int { val MOD = 1000000007 val n = nums.size // 前缀和 for (i in 1 until n) { nums[i] += nums[i - 1] } var ret = 0L for (i in 1 .. n - 2) { // 在第 [i] 位前分割 if (nums[i - 1] * 3 > nums[n - 1]) break for (j in i + 1 .. n - 1) { // 在第 [j] 位前分割 val k1 = nums[i - 1] val k2 = nums[j - 1] - nums[i - 1] val k3 = nums[n - 1] - nums[j - 1] if (k2 in k1 .. k3) ret = (ret + 1) % MOD } } return ret.toInt() } }
class Solution { fun waysToSplit(nums: IntArray): Int { val MOD = 1000000007 val n = nums.size // 前缀和 for (i in 1 until n) { nums[i] += nums[i - 1] } var ret = 0L for (i in 0 .. n - 3) { // 在第 [i] 位分割 if (nums[i] * 3 > nums[n - 1]) break // x - nums[i] >= nums[i] // 寻找大于等于 2 * nums[i] 的第一个元素 var left = i + 1 var right = n - 2 while (left < right) { val mid = (left + right) ushr 1 if (nums[mid] >= 2 * nums[i]) { right = mid } else { left = mid + 1 } } if (nums[left] < 2 * nums[i]) continue val from = left // x - nums[i] <= top - x // 寻找小于等于 (nums[n - 1] + nums[i]) / 2 的最后一个元素 right = n - 2 while (left < right) { val mid = (left + right + 1) ushr 1 if (nums[mid] <= (nums[n - 1] + nums[i]) / 2) { left = mid } else { right = mid - 1 } } if (nums[left] > (nums[n - 1] + nums[i]) / 2) continue val to = left ret = (ret + to - from + 1) % MOD } return ret.toInt() } }