我是 MATLAB 简介类(class)的助教,类(class)尚未学习数组(或在 MATLAB 中,向量)的使用。马上就要考试了,其中一个学习指南上的问题如下:
[棘手问题] 众数是序列中出现次数最多的数字。提示用户以非递减顺序逐个输入一系列非负数。用户通过输入一个负数来指示序列的结束。编写一个脚本来获取这样的用户输入并确定序列的模式。如果有多种模式,您可以将其中任何一种报告为模式。不要使用数组。下面是一个运行示例:
Determine mode of a set of nonnegative integers.
Use a negative number to quit.
Give me a number: 70
Another number not smaller than the previous: 71
Another number not smaller than the previous: 80
Another number not smaller than the previous: 80
Another number not smaller than the previous: 80
Another number not smaller than the previous: 91
Another number not smaller than the previous: 93
Another number not smaller than the previous: -1
Mode is 80.
我一直在想,但我想不出一个好的解决方案。 有谁知道是否有解决这个问题的好方法?
我能想出的唯一解决方案是试图通过其他方式模拟数组使用的丑陋黑客,例如使用带分隔符的字符串来模拟类似字典的对象。
最佳答案
这里的重点是“另一个不小于前一个的数:”。这意味着输入序列总是排序的,如果有相同的数字,它们必须彼此相邻出现。假设只需要一种模式,使用变量 current_mode_so_far
推导它应该是微不足道的, frequency_of_current_mode
, input
和 frequency_of_input
.
关于algorithm - 在不使用数组/向量的情况下计算数字序列的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2312630/