169. Majority Element

来源:互联网 发布:目标软件游戏 编辑:程序博客网 时间:2024/05/29 03:36

题目描述:

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.

解题思路:

用一个pair来记录数组中的元素和出现的次数,然后筛选出其中出现次数超过一半的那个元素,即majority element。

代码:

class Solution {public:    int majorityElement(vector<int>& nums) {        list<pair<int, int> > L;        list<pair<int, int> >::iterator i;        for (int j = 0; j < nums.size(); j++) {            i = L.begin();    while (i != L.end() && nums[j] > (*i).first) {    i++;    }    if (i != L.end() && nums[j] == (*i).first) {    (*i).second++;    }    else    L.insert(i, pair<int, int>(nums[j], 1));        }        i = L.begin();        int majority;        int mid = nums.size()/2;        while (i != L.end()) {            if ((*i).second > mid) {                majority = (*i).first;            }            i++;        }        return majority;    }};

0 0
原创粉丝点击