统计桌面上的不同数字
难度:
标签:
题目描述
You are given a positive integer n
, that is initially placed on a board. Every day, for 109
days, you perform the following procedure:
- For each number
x
present on the board, find all numbers1 <= i <= n
such thatx % i == 1
. - Then, place those numbers on the board.
Return the number of distinct integers present on the board after 109
days have elapsed.
Note:
- Once a number is placed on the board, it will remain on it until the end.
%
stands for the modulo operation. For example,14 % 3
is2
.
Example 1:
Input: n = 5 Output: 4 Explanation: Initially, 5 is present on the board. The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. After that day, 3 will be added to the board because 4 % 3 == 1. At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5.
Example 2:
Input: n = 3 Output: 2 Explanation: Since 3 % 2 == 1, 2 will be added to the board. After a billion days, the only two distinct numbers on the board are 2 and 3.
Constraints:
1 <= n <= 100
代码结果
运行时间: 13 ms, 内存: 16.0 MB
/*
* 题目思路:
* 与Java普通解法类似,但是利用Java Stream流式编程来实现。
* 初始时数字n在桌面上,之后每一天都会在桌面上寻找满足条件的数字。
* 这些满足条件的数字会一直保留在桌面上直到结束。
* 因此,我们只需要计算出这些满足条件的数字数量即可。
*/
import java.util.stream.IntStream;
public class Solution {
public int distinctIntegers(int n) {
// 初始值为1,因为n本身就在桌面上
return (int) IntStream.range(2, n) // 生成范围为2到n-1的数字流
.filter(i -> n % i == 1) // 过滤出n % i == 1的数字
.count() + 1; // 计数,并加上n本身的1个计数
}
}
解释
方法:
此题解使用一个集合 `board` 来存储每一天结束时桌面上的所有数字。初始时,集合中只包含数字 `n`。每天对当前集合中的每个数字 `x` 进行遍历,对于每个 `x`,再次遍历从 `1` 到 `x-1` 的所有整数 `i`,检查 `x % i == 1` 是否成立。如果条件满足,则将 `i` 添加到一个新的临时集合 `new_board` 中。如果在某一天结束时 `new_board` 和 `board` 相同,意味着没有新的数字被添加到集合中,因此可以停止迭代,返回集合中不同整数的数目。这反映出了算法的收敛性,即达到了一个固定点,新的数字不再被生成。
时间复杂度:
O(n^2)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么选择使用集合(set)数据结构来存储桌面上的数字,而不是列表(list)或其他容器?
▷🦆
在算法中,为何需要检查新集合`new_board`和旧集合`board`是否相同来决定是否继续迭代,这种方法的时间复杂度是多少?
▷🦆
遍历从1到x-1的整数时,算法是否考虑了任何优化措施以降低时间复杂度,例如跳过某些不必要的检查?
▷