算法分析与设计:leetcode169.Majority Element

专门选择了分治算法的题目,首先选了两道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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

最开始想法是用映射把数字和它的个数联系起来,于是有了个最简单的版本:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int, int> nodes;
        int n = nums.size();
        for (int i = 0; i < n; ++i) {
            nodes[nums[i]]++;
            if (nodes[nums[i]] > n / 2) {
                return nums[i];
            }
        }
    }
};

效率不高,只打败了20%的代码。同时这也没有用到分治的思想,于是思考分治算法。
最开始思路不太清晰,参考了一下别人的提示,有点豁然开朗。把数组对半分成2个子数组,再找到子数组的众数,再拿左右子众数的个数来比较,递归返回个数更多的那个众数。当数组只有一个数时,返回它本身。

class Solution {
private:
    int majority(vector<int>& nums, int left, int right) {
        if (left == right) return nums[left];
        int mid = left + (right - left) / 2;
        int lMajor = majority(nums, left, mid);
        int rMajor = majority(nums, mid + 1, right);
        if (lMajor == rMajor) return lMajor;
           return count(nums.begin() + left, nums.begin() + right + 1, lMajor) 
           > count(nums.begin() + left, nums.begin() + right + 1, rMajor) 
           ? lMajor : rMajor;
    }
public:
    int majorityElement(vector<int>& nums) {
        return majority(nums, 0, nums.size() - 1);
    }

};

但这个也只是打败60%左右的代码。因此我去看了一些其他算法,的确分治算法在此不是最优的。

你可能感兴趣的:(C++,算法)