17.0k views
1 vote
An array A contains n integers taken from the interval [0,4n], with repetitions allowed. Write an efficient algorithm for determining an integer value k that occurs the most often in A. What is the running time of your algorithm? Calculate and include the running time in a comment, preferably at the top of your code.Use the following array for testing: int [] arr = { 55, 9, 118, 220, 152, 200, 198, 319, 245, 315, 379, 99, 191, 343, 394, 31, 3, 345, 274, 43, 52, 324, 283, 7, 65, 70, 56, 344, 18, 360, 104, 349, 309, 149, 94, 160, 111, 370, 235, 8, 81, 379, 213, 379, 201, 399, 390, 160, 369, 113, 340, 178, 281, 160, 232, 241, 348, 160, 29, 179, 65, 327, 7, 88, 305, 180, 334, 27, 303, 281, 341, 260, 393, 105, 219, 170, 346, 380, 14, 134, 169, 336, 54, 178, 177, 122, 21, 145, 398, 170, 201, 104, 161, 380, 332, 234, 48, 251, 105, 33 }

1 Answer

6 votes

Final answer:

To find the most frequent integer in an array, a hash map can be used to keep track of each integer's frequency and then find the integer with the highest count. The running time of this approach is O(n), making it an efficient algorithm for solving this problem.

Step-by-step explanation:

To solve this problem, we will use a hash map to keep track of the frequency of each integer in the array. Then, we will iterate over the hash map to find the integer with the highest frequency (most occurrences). The running time of this algorithm will be O(n), where n is the number of elements in the array, as we are just passing through the array once to fill the hash map, and then passing through the potentially smaller map to find the most frequent element.

  • Initialize a hash map to store integers and their frequencies.
  • Iterate through the array, and for each integer, increment its frequency in the hash map.
  • Iterate through the hash map to find the integer with the highest frequency.
  • Return the integer that occurs most often.

Here is the algorithm implementation in Java:


// Running time comment:
// The running time of this algorithm is O(n)
int findMostFrequent(int[] arr) {
HashMap frequencyMap = new HashMap<>();
int maxFrequency = 0;
int mostFrequent = -1;
for (int num : arr) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
if (frequencyMap.get(num) > maxFrequency) {
maxFrequency = frequencyMap.get(num);
mostFrequent = num;
}
}
return mostFrequent;
}

User Jimenez
by
7.5k points