你现有的算法对于作业任务来说已经很好了。你可以做各种优化代码的事情,例如:
- 使用二叉树提高效率,
- 使用计数的数组,其中索引是数字(假设数字范围有限)。
但我认为在这种情况下它们并不是必要的。对于作业,意图只是展示你理解如何编程,而不是你知道各种技巧来挤出最后一点性能。你的教育者更关注可读性强、结构良好的代码,而不是巧妙的优化。
下面我将描述我会做的事情。你可以自由地使用我的建议,取决于你想要多少满意度。我只提供伪代码,这是我对作业问题的标准做法。
我会从一个结构开始,包含一个数字、一个计数和一个下一个指针(用于你的链表),以及指向第一个指针的全局指针:
typedef struct sElement {
int number;
int count;
struct sElement *next;
} tElement;
tElement first = NULL;
然后创建一些函数来创建和使用列表:
tElement *incrementElement (int number);
tElement *getMaxCountElement (void);
tElement *getNextMatching (tElement *ptr, int count);
这些函数将会:
- 增加元素的计数(如果该元素不存在,则创建并将计数设置为1)。
- 扫描所有元素,返回最大计数。
- 从给定点开始获取下一个匹配计数的元素指针,或者是NULL(如果没有更多匹配的元素)。
每个函数的伪代码:
def incrementElement (number):
# Find matching number in list or NULL.
set ptr to first
while ptr is not NULL:
if ptr->number is equal to number:
return ptr
set ptr to ptr->next
# If not found, add one at start with zero count.
if ptr is NULL:
set ptr to newly allocated element
set ptr->number to number
set ptr->count to 0
set ptr->next to first
set first to ptr
# Increment count.
set ptr->count to ptr->count + 1
def getMaxCountElement (number):
if first is NULL:
return NULL
set retptr to first
set ptr to first->next
while ptr is not NULL:
if ptr->count is greater than retptr->count:
set retptr to ptr
set ptr to ptr->next
return retptr
def getNextMatching (ptr, number):
while ptr is not NULL:
if ptr->number is equal to number:
return ptr
set ptr to ptr->next
return NULL
那么你的主程序将变成:
# Process all the numbers, adding to (or incrementing in) list .
for each n in numbers to process:
incrementElement (n)
# Get the mode quantity, only look for modes if list was non-empty.
maxElem = getMaxCountElement ()
if maxElem is not NULL:
# Find the first one, whil exists, print and find the next one.
ptr = getNextMatching (first, maxElem->count)
while ptr is not NULL:
print ptr->number
ptr = getNextMatching (ptr->next, maxElem->count)