C++ 中丑数子数组的最大长度
问题陈述
给定一个包含 N 个元素的数组 arr[](0 ≤ arr[i] ≤ 1000)。任务是找到仅包含丑数的子数组的最大长度。
丑数是指其唯一质因数为 2、3 或 5 的数。
例如,以下是该序列中的一些数字:1、2、3、4、5、6、8、9、10、12、15……
示例
如果输入数组为 {1, 2, 7, 9, 120, 810, 374},则答案为 3,因为:
最长的丑数子数组是 {9, 120, 810}
算法
- 创建一个无序集合,并将所有小于 1000 的丑数插入到集合中。
- 使用两个名为 current_max 和 max_so_far 的变量遍历数组。
- 检查每个元素是否在集合中。
- 如果找到一个丑数,则递增 current_max 并将其与 max_so_far 进行比较。
- 如果 current_max > max_so_far,则 max_so_far = current_max。
- 每当找到一个非丑数元素时,将 current_max 重置为 0。
示例
#include <bits/stdc++.h>
using namespace std;
unsigned getUglyNumbers(int n) {
int ugly[n];
int i2 = 0, i3 = 0, i5 = 0;
int next_multiple_of_2 = 2;
int next_multiple_of_3 = 3;
int next_multiple_of_5 = 5;
int next_ugly_no = 1;
ugly[0] = 1;
for (int i = 1; i < n; i++) {
next_ugly_no = min(next_multiple_of_2, min(next_multiple_of_3, next_multiple_of_5));
ugly[i] = next_ugly_no;
if (next_ugly_no == next_multiple_of_2) {
i2 = i2 + 1;
next_multiple_of_2 = ugly[i2] * 2;
}
if (next_ugly_no == next_multiple_of_3) {
i3 = i3 + 1;
next_multiple_of_3 = ugly[i3] * 3;
}
if (next_ugly_no == next_multiple_of_5) {
i5 = i5 + 1;
next_multiple_of_5 = ugly[i5] * 5;
}
}
return next_ugly_no;
}
int maxUglySubarray(int arr[], int n) {
unordered_set<int> s;
int i = 1;
while (1) {
int next_ugly_number = getUglyNumbers(i);
if (next_ugly_number > 1000)
break;
s.insert(next_ugly_number);
i++;
}
int current_max = 0, max_so_far = 0;
for (int i = 0; i < n; i++) {
if (s.find(arr[i]) == s.end())
current_max = 0;
else {
current_max++;
max_so_far = max(current_max,
max_so_far);
}
}
return max_so_far;
}
int main() {
int arr[] = {1, 2, 7, 9, 120, 810, 374};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum sub-array size of consecutive ugly numbers = " << maxUglySubarray(arr, n) << endl;
return 0;
}输出
编译并执行以上程序时,会生成以下输出:
Maximum sub-array size of consecutive ugly numbers = 3
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP