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.
具体代码如下:
思路:
假如给定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; }
相关文章推荐
- Java获取URL地址图片
- POI-JAVA操作WORD文档
- Fedora 22 上安装 fcitx 五笔输入法
- JAVA操作PDF
- Ubuntu 下搭建Qt Webkit(三)
- JAVA压缩图片
- Ubuntu 下搭建Qt Webkit(二)
- Ubuntu 下搭建Qt Webkit(一)
- 【DB.MySQL】Mac下MySQL卸载方法
- 02Scala-函数定义、流程控制、异常处理入门实战
- JAVA_DATE
- 【Open】2015.08.03-连接脚本配置错误导致“不精确的数据访问违例”
- JAVA内存机制
- JVM内存原型剖析
- 柯塔娜大合唱,互联网安全观
- 查找北大未名BBS上任意ID的所有發帖
- Oracle 11G Client 客户端安装步骤(图文详解)
- IOS开发基础之NSBundle
- 泛形的使用
- REPRINT CALLBACK