链表-主元素 III-中等

描述
给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的1/k。
数组中只有唯一的主元素
您在真实的面试中是否遇到过这个题?  
样例
给出数组 [3,1,2,3,2,3,3,4,4,4] ,和 k = 3,返回 3
挑战

要求时间复杂度为O(n),空间复杂度为O(k)

题目链接

分析

        使用哈希表,将值大于数组元素个数的1/k的key返回。

程序


class Solution {
public:
    /**
     * @param nums: A list of integers
     * @param k: An integer
     * @return: The majority number
     */
    int majorityNumber(vector<int> &nums, int k) {
        // write your code here
        unordered_map<int, int> results;
        for(int i = 0; i < nums.size(); i++){
            ++results[nums[i]];
        }
        for(auto i = results.begin(); i != results.end(); i++){
            //cout << "i->first: " << i->first << " i->second: " << i->second;
            //cout << endl;
            if(i->second > (nums.size()/k))
                return i->first ;
        }
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/80940249