gpt4 book ai didi

java - 有人可以检查我的算法以获得数组的模式,决胜局根本没有模式吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:03 26 4
gpt4 key购买 nike

因此,“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com