JavaInterview JavaInterview
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)

『Java面试+Java学习』
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)
  • 指南
  • 简历

  • Java

  • 面试

  • 算法

  • algorithm
  • leetcode
JavaInterview.cn
2025-06-09
目录

1862. 向下取整数对和Java

文章发布较早,内容可能过时,阅读注意甄别。

# 题目

给你一个整数数组 nums ,请你返回所有下标对 0 <= i, j < nums.length 的 floor(nums[i] / nums[j]) 结果之和。由于答案可能会很大,请你返回答案对109 + 7 取余 的结果。

函数 floor() 返回输入数字的整数部分。

示例 1:

输入:nums = [2,5,9]
输出:10
解释:
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
我们计算每一个数对商向下取整的结果并求和得到 10 。

示例 2:

输入:nums = [7,7,7,7,7,7,7]
输出:49

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105

# 思路

for

# 解法

class Solution {
    // 
    public int sumOfFlooredPairs(int[] nums) {
        int n = nums.length, mod = 1000000007, max = 0;
        long sum = 0;
        for (int x : nums) {
            max = Math.max(max, x);
            sum += x;
        }
        int[] f = new int[max + 1];
        for (int x : nums) f[x]++;
        
        for (int i = 1; i <= max; i++) f[i] += f[i - 1];
        
        long res = 0;
        
        for (int i = 0; i < n; i++) {
            // 避免 1 导致复杂度退化
            if (nums[i] == 1) res = res + sum;
            else {
                for (int j = nums[i], cost = 1; j <= max; j += nums[i], cost++) {
                    res = (res + (f[Math.min(max, j + nums[i] - 1)] - f[j - 1]) * cost) % mod;
                }
            }
            
        }
        return (int)(res % mod);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 总结

  • 分析出几种情况,然后分别对各个情况实现
微信 支付宝
#Java
最近更新
01
1644.测试路径 Java
02-25
02
1888. 使二进制字符串字符交替的最少反转次数 Java
02-25
03
1890. 2020年最后一次登录 Java
02-25
更多文章>
Theme by Vdoing | Copyright © 2019-2026 JavaInterview.cn
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式