- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
因此,“diffs”是一个数组,例如 [1, 1, 2, 2] 或 [1, 2, 4, 4]。 “count”本质上是一个直方图,其中每个索引的值是该索引出现在“diffs”中的次数。因此,第一个示例的直方图将为 [0, 2, 2](直方图的大小为 1 + 索引 0 的最大值)。
在“计数”正确初始化后,我通过向后工作并更新模式来运行它。如果“count”中当前评估的元素等于模式,则模式设置回-1,表示无模式。这适用于我拥有的小型测试用例,但对于较大的测试用例,我不确定这里是否存在判断失误。
int mode = -1;
if (diffs.size() != 0) {
int[] count = new int[Collections.max(diffs) + 1];
for (int j = 0; j < diffs.size(); j++) {
count[diffs.get(j)]++;
}
int index = count.length - 1;
for (int j = count.length - 2; j >= 0; j--) {
if (count[j] > count[index]) {
if (count[j] == count[index]) {
mode = -1;
break;
}
index = j;
mode = j;
}
}
}
最佳答案
我不知道为什么如果你发现两个计数元素具有相同的值,你将模式设置为-1。我看的问题描述here表示模式是
the number that appears more times in the array than any other number
和
If there are multiple solutions, i.e. two or more most frequent numbers occur equally many times, function should return any of them.
即使你被要求在多个解决方案的情况下返回-1,你的逻辑也是错误的,因为你只检查 if ( count[j] > count[index])
,所以它永远不会为真。此外,即使你在那个条件之外检查,跳出循环也是错误的,因为可能还有一个数字出现了更多次。
你可能想要这样的东西:
int mode = -1;
if (diffs.size() != 0) {
int[] count = new int[Collections.max(diffs) + 1];
for (int j = 0; j < diffs.size(); j++) {
count[diffs.get(j)]++;
}
int index = count.length - 1;
for (int j = count.length - 2; j >= 0; j--) {
if (count[j] > count[index]) {
index = j;
mode = j;
} else if (count[j] == count[index]) {
mode = -1;
// don't break, since we may still find j such that count[j] > count[index]
}
}
}
关于java - 有人可以检查我的算法以获得数组的模式,决胜局根本没有模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849125/
对于家庭作业,我需要根据启发式比较节点,以便我可以将它们放入 TreeSet 中。但是,当两个节点的启发值相等时,我需要一些方法来打破平局。 我不允许修改提供的 Node 类,据我所知,Node 没有
我在 Python 3.3.x 中有一个 Counter 我想对其进行排序。 我知道我可以使用 .most_common(x) 但我希望键在值相同的情况下按字母顺序排序。 有什么办法可以做到这一点?设
我是一名优秀的程序员,十分优秀!