【发布时间】:2018-11-09 16:09:23
【问题描述】:
我有一个整数数组列表 5, 12, 5, 17, 5, 5, 5, 39 我试图找到 重复次数最多的 数将打印5的作品。
但是,我想使用分而治之的方法来编写它。
任何提示都会有所帮助(伪代码、Java 代码或任何帮助...)
public static void main(String[] args) {
int[] repetitive = { 5, 12, 5, 17, 5, 5, 5, 39 };
int counter = 1;
int temp = 0;
int checker = 1;
Arrays.sort(repetitive);
int cont = repetitive[0];
for (int i = 1; i < repetitive.length; i++) {
if (repetative[i] == repetitive[i - 1] && cont == repetitive[i]) {
counter++;
temp = repetitive[i];
} else if (repetitive[i] == repetitive[i - 1]) {
checker++;
if (checker > counter) {
temp = repetitive[i];
} else if (repetitive[i] != repetitive[i - 1]) {
checker = 1;
}
}
}
System.out.println(temp);
}
【问题讨论】:
-
你的意思是要找模式吗?
-
在您的示例中,5 和 12 都出现了 3 次。为清楚起见,您可能应该确保示例中只有一个“重复次数最多”的数字。
-
感谢@JimMischel 的警告,我已修复。
-
@johntame 您所描述的是模式,即“最常出现的值”。 en.wikipedia.org/wiki/Mode_(statistics)
-
对于建议使用地图的每个人,这不是 OP 所要求的。他在问如何使用分而治之的方式来做到这一点。你们都缺少的一点是,如果
Arrays.sort()使用快速排序(一种分而治之的算法),那么他已经解决了他的问题。 OP 可以说他想在不使用任何显式额外内存的情况下解决问题,例如地图所需的 O(n) 内存。那会澄清很多事情。
标签: java algorithm dynamic-programming divide-and-conquer