#Majority element

19 messages · Page 1 of 1 (latest)

halcyon fractalBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

strong orchid
#

What is a majority element? An element can't be a majority (besides the case when it's the only element).
Do you mean a largest element, based on a well-defined comparison function?

north hearth
#

no

strong orchid
#

Okay, but that's still not a majority element, but a value that the majority of elements have.

#

Well, all you need to do is to check if at least 50% of the entries are that certain value. I don't understand your problem here

north hearth
#

i mean if this n/2 thingy doens't exist

idle basalt
#

Count the unique elements, create an array with that number, all elements initialized to zero, go through the original array incrementing the frequency array accordingly, check which index is geq n/2, return the element you mapped to that index.

#

There's certainly a far better way, but that's what I thought of.

timid prairie
#

Just count the occurrences of each bing_shrug

#

This is easier in the general case if you can use something like a hash table but that's not needed

strong orchid
north hearth
#


int majorityElement(int* nums, int numsSize){
    long size = numsSize / 2;
    if (numsSize > 50000 || numsSize <0){
        return 0;
    }
    if (size == 0){
        return nums[0];
    }
    for(int i = 0;i<numsSize; i++){
        long count = 0;
        for (int j = 0;j < numsSize; j++){
            if (nums[i] == nums[j]){
                count++;
            }
        }
        if (count > size){
            return nums[i];
        }
    }
    return 0;
}
``` this code here
#

what does this error mean?

#

w

#

!solved

halcyon fractalBOT
#

Thank you and let us know if you have any more questions!

#

[SOLVED] Majority element