小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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测试程序源码

posted on 2015-08-15 20:47  Coding菌  阅读(98)  评论(0编辑  收藏  举报