leetcode -- Majority Element

来源:互联网 发布:邪恶漫画知子伯母全集 编辑:程序博客网 时间:2024/06/05 17:12

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.

在数组不为空的前提下返回出数组中出现超过n/2次的数组元素,简单直接的做法是直接通过两层for循环计算元素的次数,当次数达到n/2时返回当前的元素,算法时间复杂度为O(n^2),空间复杂度为O(1);另一种做法是通过投票算法(投票算法适用于选出数组中出现的次数大于等于数组长度一半的元素)算法时间复杂度为O(n),空间复杂度为O(1)

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

0 0
原创粉丝点击