Find maximum repeating number
来源:互联网 发布:淘宝属于b2b吗 编辑:程序博客网 时间:2024/05/08 06:29
给你一个长度是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-1int 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 functionint 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;}
0 0
- Find maximum repeating number
- 448. Find All Numbers Disappeared in an Array \ 414. Third Maximum Number
- Find k most repeating elements
- codeforces C. Find Maximum
- codeforce Find Maximum
- CCI: Find maximum subsquare
- Algorithm: Find the maximum
- find random maximum
- Maximum Number Of Divisors
- leetcode Create Maximum Number
- Create Maximum Number | LeetCode
- leetcode Create Maximum Number
- LeetCode Create Maximum Number
- leetcode - Create Maximum Number
- leetcode_321 Create Maximum Number
- Create Maximum Number
- 321. Create Maximum Number
- LintCode_552 Create Maximum Number
- 查找北大未名BBS上任意ID的所有發帖
- JAVA内存机制
- JVM内存原型剖析
- JAVA_DATE
- JAVA封装访问控制
- Find maximum repeating number
- 02Scala-函数定义、流程控制、异常处理入门实战
- Ubuntu 下搭建Qt Webkit(一)
- 【DB.MySQL】Mac下MySQL卸载方法
- Ubuntu 下搭建Qt Webkit(二)
- JAVA之多线程
- JAVA压缩图片
- JAVA操作PDF
- Ubuntu 下搭建Qt Webkit(三)