Vlad
Vlad

Reputation: 256

Find majority element from input

Can i find majority element only reading input w/o adding to an array? My code dont't work at big input, with large difference of numbers.

I find my mistake. There right code:

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;
    }

Upvotes: 2

Views: 406

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96266

Large input shouldn't cause any problems, you just assumed that's the problem when it failed on (a) large file(s?).

The code looks more-or-less OK, but IIRC you if the counter reaches zero, you have to pick (= set first to a new value) the next element, and not the previous one.

Upvotes: 1

Related Questions