LeetCode--169. Majority Element (Divide-and-Conquer)

来源:互联网 发布:硕士出国读博 知乎 编辑:程序博客网 时间:2024/06/07 01:48

Majority Element

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.

采用分治算法 (Divide-and-Conquer algorithms)
class Solution {public:    int majorityElement(vector<int>& nums) {        return Maj(nums, 0, nums.size() - 1);        }private:    int Maj(vector<int>& nums, int left, int right) {        if (left == right) {            return nums[left];        }        int mid = left + ((right - left) >> 1);        int leftmaj = Maj(nums, left, mid);        int rightmaj = Maj(nums, mid + 1, right);        if (leftmaj == rightmaj) {            return leftmaj;        }        return count(nums.begin() + left, nums.begin() + right + 1, leftmaj) > count(nums.begin() + left, nums.begin() + right + 1, rightmaj) ? leftmaj : rightmaj;    }};

阅读全文
0 0
原创粉丝点击