2
我可以找到多數元素只讀輸入沒有添加到數組嗎? 我的代碼不會在很大的輸入,數字差異很大。從輸入中找到多數元素
我發現我的錯誤。有正確的代碼:
int n = Integer.parseInt(bin.readLine()); // read number of data
int h = 0; //input data
int count = 1; //counter
int lf = 0; // last top counting
int first = 0; // top counter num
for (int x = 0; x < n; x++) {
lf = h;
h = Integer.parseInt(bin.readLine());//read input number
if (x == 0) {
first = h;
}
if (h == first) {
count++;
} else {
count--;
}
if (count == 0) {
first = lf;
count = 1;
}
你稱之爲多數元素是什麼?此代碼似乎計算輸入中出現第一個元素的次數。 – Qnan
無論輸入數量多少,您的代碼都應該可以工作。 「不工作」是什麼意思? –
當我輸入更多的100 000個號碼時,它會給出錯誤的答案。 – Vlad