Friday, January 29, 2016

Majority Number

Majority Number


Find a majority of number which is occurring more than half of numbers in an array. We are allowed to read the array only once.
Example: array is {1, 2, 3, 1, 1, 1}
o/p: 1
Sol:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int FindMajority(int[] a)
    {
        int count, major;      
        count=0;
        major=a[0];    
        for(int i=0; i<a.length; i++){
            if(count==0){
                major=a[i];
                count=1;
            }
            else if(a[i] == major){
                count++;
            }
            else{
                count--;
            }
        }      
        return major;
}

No comments:

Post a Comment