LeetCode(169)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.

分析

给定一个整数序列,求出其中出现次数大于 floor(n/2) 的元素,并返回。

这是一个很简单的题目,首先将序列排序,得到一个有序排列,然后依次遍历,统计重复元素的出现次数,返回次数大于一半的元素即可。

AC代码

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        //题目假设输入数组非空,且出现次数大于[n/2]的元素存在
        int len = nums.size() , count = len/2;

        sort(nums.begin(), nums.end());

        if (len == 1)
            return nums[0];
        int tmp = 1;
        for (int i = 0; i < len-1; i++)
        {
            if (nums[i + 1] == nums[i])
            {
                ++tmp;
                if (tmp > count)
                    return nums[i];
            }
            else{
                tmp = 1;
            }//if
        }//for
        return -1;
    }
};

GitHub测试程序源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值