Leetcode ☞ 169. Majority Element

本文介绍了一个简单的算法,用于从大小为n的数组中找到出现次数超过n/2的多数元素。该算法首先对数组进行排序,然后通过比较中间元素与其后的n/2位置的元素来确定多数元素。

169. Majority Element

My Submissions
Total Accepted: 96138  Total Submissions: 239623  Difficulty: Easy

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.








我的AC:

int comp(const int *a, const int *b){
    if (*a >= *b)
        return 1;
    else
        return -1;
}

int majorityElement(int* nums, int numsSize) {
    qsort(nums, numsSize, sizeof(int), comp);
    
    for (int i = 0; i < (numsSize + 1) / 2 ; i++){
        if(nums[i] == nums[i + numsSize / 2])
            return nums[i];
   }
}

分析:

1、∵majority元素一定是出现过[n/2]次以上的   ∴排序后跟其之后n/2位的数进行比较即可。

2、不论numsSize的奇偶, i < (numsSize + 1) / 2 的循环终止,都时满足的

【长度为9,数组下标0~8,循环最后一次是nums[4],nums[4 + 9/2]正好是末尾;

   长度为10,数组下标0~9,循环最后一次是nums[4],nums[4 + 10/2]正好是末尾。】










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值