2012-08-29 47 views
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; 
    } 
+2

你称之为多数元素是什么?此代码似乎计算输入中出现第一个元素的次数。 – Qnan

+1

无论输入数量多少,您的代码都应该可以工作。 “不工作”是什么意思? –

+0

当我输入更多的100 000个号码时,它会给出错误的答案。 – Vlad

回答

1

大输入不会引起任何问题,你只是认为这就是问题所在,当它失败了(一)大文件(S?)。

代码看起来更多或更少OK,但IIRC你如果计数器达到零,你必须选择(=设定first到一个新的值)下一个元素,而不是之前的一个。