实例四十七:统计数组元素出现次数
问题描述:
从键盘输入 n(0<n<100) 个整数,计算并输出其中出现次数最多且数值最大的元素及出现次数。
算法思路:
首先要明白题目的要求:“出现次数最多且数值最大”,显然,出现次数最多是主要条件,也就是说,当有 “3个2” 与 “2个3” 时,结果是 “3个2”。
First of all, we must understand the requirements of the topic: “The maximum number of occurrences and the maximum number of values”. Obviously, the maximum number of occurrences is the main condition. That is, when there are “3 2” and “2 3”, the result is “3 2”. ".
先假设第 0 个元素是当前出现次数最多且数值最大的元素,至少出现次数为 1 次,然后再从第 0 个元素开始,一一统计其元素的出现次数,其后只要是发现比当前出现次数最多的元素次数还要多的元素(或出现次数相等,但数值更大),就用它代替当前元素,并用他的出现次数代替当前元素得出现次数。
First assume that the 0 element is the element with the highest number of occurrences and the largest number of values, at least one occurrence, and then start with the 0 element, counting the number of occurrences of its elements one by one. Later, as long as it is an element that finds more elements than the current number of occurrences(or the number of occurrences is equal, but the value is larger), it is used instead of the current element and its occurrence is replaced by the number of occ