简单分治案例

    xiaoxiao2021-03-25  56

    题目:

    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.

    题解:

    将数组二分,然后进行递归,递归到一就是当前的众数,再合并,比较两个众数取次数多的往上并,中间用到计数函数count。

    代码:

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

    转载请注明原文地址: https://ju.6miu.com/read-40904.html

    最新回复(0)