這裏大多數occurence元素是簡單的程序來找到它最常出現的數組元素:發現陣列
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
int a[] = {1,2,3,4,4,4,5};
int n = sizeof(a)/sizeof(int);
int max = 0;
int result = 0;
int *b = new int[n];
for (int i = 0; i < n; i++) {
b[a[i]] = (b[a[i]] || 0) + 1;
if (b[a[i]] > max) {
max = b[a[i]];
result = a[i];
}
}
cout << result << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
但它不工作;它打印1
。爲什麼?
你能保證數組總是按照你的例子排序嗎?或者,你能保證給定元素的所有出現都是連續的嗎?如果是這樣,存在O(1)額外存儲的更簡單,更快的算法。 – 2010-09-26 15:25:51