[leetcode]Majority Element

原题

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

思路

This problem is required to get the majority element appeard. As it appears more than [n/2] times. So we can compare two elements, if they do not have the same value, we can delete them. And at last, the only left element must be the one we want to get.  The time complexity is O(n)

代码

int majorityElement(int* nums, int numsSize) {
    int element = 0;
    int count = 0;
 
    for(int i = 0; i < numsSize; i++)
    {
        if(count == 0)
        {
           element = nums[i];
           count++;
        }else
        {
            if(element == nums[i])
            {
                count++;
            }else
            {
                count--;
            }
       }
    }
    return element;
}

运行结果

42 / 42 test cases passed.
Status:

Accepted

Runtime:  8 ms
Submitted:  10 minutes ago

猜你喜欢

转载自blog.csdn.net/u011960402/article/details/47659797