Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7.
The floor() function returns the integer part of the division.
Example 1:
Input: nums = [2,5,9]
Output: 10
Explanation:
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
floor(5 / 2) = 2
floor(9 / 2) = 4
floor(9 / 5) = 1
We calculate the floor of the division for every pair of indices in the array then sum them up.
Example 2:
Input: nums = [7,7,7,7,7,7,7]
Output: 49
Constraints:
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 105
对于 n, m, 如果 m < n, 则 floor(m / n) = 0, 如果 n <= m < 2n, 则 floor(m / n) = 1, 以此类推当 i _ n <= m < (i + 1) _ n 时, floor(m / n) = i。我们再反过来想, 我们遍历 i, 查找处于[i _ n, (i+1) _ n)的 m 的数量就可以得到以 n 作为分母部分的答案。我们把所有以 n 为分母的答案加和起来就是最终答案。这里要快速的查出 m 的数量, 我们要对 nums 做一个 prefix sum, prefix_sum[(i+1)n - 1] - prefix_sum[in-1]就是我们要的 m 的数量。为了对应大量重复数字的情况, 我们对数字进行计数
use std::collections::HashMap;
const MOD: i64 = 1000000007;
impl Solution {
pub fn sum_of_floored_pairs(nums: Vec<i32>) -> i32 {
let mut max = 0i64;
let mut freq = vec![0i64; 100000 * 2 + 1];
let mut counts = HashMap::new();
for &n in &nums {
max = max.max(n as i64);
freq[n as usize] += 1;
*counts.entry(n as i64).or_insert(0i64) += 1;
}
for i in 1..freq.len() {
freq[i] += freq[i - 1];
}
let mut ans = 0;
for (n, c) in counts {
let mut m = 1i64;
while n * m <= max {
ans +=
(freq[((m + 1) * n - 1) as usize] - freq[(n * m - 1) as usize]) * m * c % MOD;
m += 1;
}
}
(ans % MOD) as i32
}
}