您的位置:首页 > 其它

Find maximum repeating number

2015-08-03 02:32 302 查看
给你一个长度是n的整数数组,数组中数字的范围是 [0, k-1] , k 满足 k<=n。找到该数组中,重复出现次数最多的数字(当出现次数相同时,找出值最大的那个)。例如 k=10, arr[] = {1, 2, 2, 2, 0, 2, 0, 2, 3, 8, 0, 9, 2, 3},那么符合条件的是数字 2 。请给出一个时间复杂度是O(n),空间复杂度是O(1)的算法。

思路:

假如给定arr[] = {2, 3, 3, 5, 3, 4, 1, 7}, k = 8, n = 8。那么,

Iterate though input array arr[], for every element arr[i], increment arr[arr[i]%k] by k (arr[] becomes {2, 11, 11, 29, 11, 12, 1, 15 })
Find the maximum value in the modified array (maximum value is 29). Index of the maximum value is the maximum repeating element (index of 29 is 3).
If we want to get the original array back, we can iterate through the array one more time and do arr[i] = arr[i] % k where i varies from 0 to n-1.

具体代码如下:
#include<iostream>
using namespace std;

// Returns maximum repeating element in arr[0..n-1].
// The array elements are in range from 0 to k-1
int maxRepeating(int* arr, int n, int k)
{
// Iterate though input array, for every element
// arr[i], increment arr[arr[i]%k] by k
for (int i = 0; i< n; i++)
arr[arr[i]%k] += k;

// Find index of the maximum repeating element
int max = arr[0], result = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
result = i;
}
}

/* Uncomment this code to get the original array back
for (int i = 0; i< n; i++)
arr[i] = arr[i]%k; */

// Return index of the maximum element
return result;
}

// Driver program to test above function
int main()
{
int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 8;

cout << "The maximum repeating number is " <<
maxRepeating(arr, n, k) << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: