Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Majority Element #59

Open
kokocan12 opened this issue Jul 6, 2022 · 0 comments
Open

Majority Element #59

kokocan12 opened this issue Jul 6, 2022 · 0 comments

Comments

@kokocan12
Copy link
Owner

Problem

When an array is given, each element of array is integer, find majority element of array.
An element of array appear more than n/2 times, then that is majority element.

Solution

If we can use extra memory for saving count.
But majority element appears more than a half of length times, we don't need to use extra memory.

/**
 * [2,2,1,1,1,2,2] n=7
 *  Pick 2, 2(1) majority element is 2.
 *  Pick 2, 2(2) majority element is 2.
 *  Pick 1, 2(2) 1(1) majority element is 2.
 *  Pick 1, 2(2) 1(2) there is no majority element.
 *  Pick 1, 1(3) 2(2) majority element is 1.
 *  Pick 2, 1(3) 2(3) there is no majority element.
 *  Pick 2, 2(4) 1(3) majority element is 2.
 *  Can not find majority element without hash map when iterate once?
 *
 *  [1,2,3,2,2,2,3,3,3,2,2]
 *  Pick 1, res=1 count=1
 *  Pick 2, res=1 count=0
 *  Pick 3, res=3 count=1
 *  Pick 2, res=3 count=0
 *  Pick 2, res=2 count=1
 *  Pick 2, res=2 count=2
 *  Pick 3, res=2 count=1
 *  Pick 3, res=2 count=0
 *  Pick 3, res=3 count=1
 *  Pick 2, res=3 count=0
 *  Pick 2, res=2 count=1
 */

const majorityElement = function(nums) {
    let res = 0;
    let count = 0;
    
    for(num of nums) {
        if(count === 0) res = num;
        
        if(res === num) count+=1;
        else count-=1;
    }
    
    return res;
};
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant