五、[LeetCode OJ]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.
问题来源:Majority Element【问题分析】
问题的意思非常简单,给出一个数组,寻找出数组中出现次数超过数组大小1/2的数(前提是给出的数组一定会有这个数)。 这里列举两种方法来解决这个问题: 方法1:利用map<int,int>构造一个容器,第一个int对应的是数组中的元素,第二个元素是该元素出现的次数,返回次数超过n/2的数。 方法2:分而治之算法,把数组一分为二,找出左边子数组出现次数最多的数在父数组中出现的次数、右边子数组出现次数最多的数在父数组出现的次数,比较左右两边哪个数在父数组中出现次数最多,返回该数。return count(nums.begin()+left,nums.begin()+right+1,LeftNum)>count(nums.begin()+left,nums.begin()+right+1,RightNum)?LeftNum:RightNum;利用递归找出子数组出现最多的数。【源代码】
1、map方法:class Solution { public: int majorityElement(vector<int>& nums) { map<int,int> hash; for (int i = 0; i < nums.size(); i++) { if (++hash[nums[i]] > nums.size() / 2) { return nums[i]; } } } }; 2、分而治之方法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 LeftNum=majority(nums,left,mid); int RightNum=majority(nums,mid+1,right); if (LeftNum==RightNum) return LeftNum; return count(nums.begin()+left,nums.begin()+right+1,LeftNum)>count(nums.begin()+left,nums.begin()+right+1,RightNum)?LeftNum:RightNum; } };