LeetCode Majority Element

来源:互联网 发布:office办公软件 编辑:程序博客网 时间:2024/06/01 19:59

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.

方法一 :分治

从中间分为两个子问题,分别对数组的左半部分和右半部分求解出现次数最多的数,分别得到lm和rm,如果lm == rm,则其就是出现次数最多的数,否则,lm和rm均是答案候选,比较二者在数组中的出现次数,多的就是我们要求的答案。代码如下:

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

注意

  • 注释(1)处如果不用引用参数传递会超时
  • 注释(2)处count为c++ STL中algorithm头文件中的函数,作用为计数
0 0