LeetCode 题解工作台

分类求和并作差

给你两个正整数 n 和 m 。 现定义两个整数 num1 和 num2 ,如下所示: num1 :范围 [1, n] 内所有 无法被 m 整除 的整数之和。 num2 :范围 [1, n] 内所有 能够被 m 整除 的整数之和。 返回整数 num1 - num2 。 示例 1: 输入: n = 10…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们遍历区间 $[1, n]$ 中的每一个数,如果它能被 整除,那么答案就减去这个数,否则答案就加上这个数。 遍历结束后,返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个正整数 nm

现定义两个整数 num1num2 ,如下所示:

  • num1:范围 [1, n] 内所有 无法被 m 整除 的整数之和。
  • num2:范围 [1, n] 内所有 能够被 m 整除 的整数之和。

返回整数 num1 - num2

 

示例 1:

输入:n = 10, m = 3
输出:19
解释:在这个示例中:
- 范围 [1, 10] 内无法被 3 整除的整数为 [1,2,4,5,7,8,10] ,num1 = 这些整数之和 = 37 。
- 范围 [1, 10] 内能够被 3 整除的整数为 [3,6,9] ,num2 = 这些整数之和 = 18 。
返回 37 - 18 = 19 作为答案。

示例 2:

输入:n = 5, m = 6
输出:15
解释:在这个示例中:
- 范围 [1, 5] 内无法被 6 整除的整数为 [1,2,3,4,5] ,num1 = 这些整数之和 =  15 。
- 范围 [1, 5] 内能够被 6 整除的整数为 [] ,num2 = 这些整数之和 = 0 。
返回 15 - 0 = 15 作为答案。

示例 3:

输入:n = 5, m = 1
输出:-15
解释:在这个示例中:
- 范围 [1, 5] 内无法被 1 整除的整数为 [] ,num1 = 这些整数之和 = 0 。 
- 范围 [1, 5] 内能够被 1 整除的整数为 [1,2,3,4,5] ,num2 = 这些整数之和 = 15 。
返回 0 - 15 = -15 作为答案。

 

提示:

  • 1 <= n, m <= 1000
lightbulb

解题思路

方法一:模拟

我们遍历区间 [1,n][1, n] 中的每一个数,如果它能被 mm 整除,那么答案就减去这个数,否则答案就加上这个数。

遍历结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nn 是题目给定的整数。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def differenceOfSums(self, n: int, m: int) -> int:
        return sum(i if i % m else -i for i in range(1, n + 1))
speed

复杂度分析

指标
时间complexity is O(1) because all sums are computed using closed formulas. Space complexity is O(1) as only a few integer variables are needed.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ask candidate to derive sums without iteration, hinting at arithmetic progression usage.

  • question_mark

    Check if the candidate correctly identifies divisible and non-divisible sets and computes sums separately.

  • question_mark

    Watch for off-by-one mistakes when calculating the number of multiples of m.

warning

常见陷阱

外企场景
  • error

    Forgetting to include n when computing sums can cause off-by-one errors.

  • error

    Using loops instead of formulas reduces efficiency and fails the O(1) expectation.

  • error

    Confusing sum of divisible and non-divisible integers, leading to incorrect subtraction order.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute the difference for a list of multiple m values simultaneously.

  • arrow_right_alt

    Return the ratio instead of difference between divisible and non-divisible sums.

  • arrow_right_alt

    Handle large n and m using modular arithmetic to avoid overflow.

help

常见问题

外企场景

分类求和并作差题解:数学·driven | LeetCode #2894 简单