leetcode编程记录3 #169 Majority Element
标签(空格分隔): leetcode
这次这道题是一道有着多种解法的题目,题目如下:
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.
题目理解与分析:
首先理解这道题目的要求,它要我们从一个给定的非空数组中找出数量超过⌊ n/2 ⌋次的一个主元数,由于题目中所给的数组总是存在这样一个数,所以方法十分多样,因为最近在学习分治的方法,所以我首先采用了分治的思想来解决这道题目。
可以将该问题一分为二来考虑,将给定的数组分成两个大约等长的子数组,那么所要求的主元数一定存在于这两个数组中的一个,并且数量也是在该数组中最多的一个数,所以通过将数组不断的一分为二,最后变为一个时返回该元素本身,最后通过比较两个数组中返回元素的数目大小就能选出数目超过⌊ n/2 ⌋的主元数来,c++代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
return divideAndConquer(nums, 0, nums.size() - 1);
}
int divideAndConquer(vector<int>& nums, int i, int j)
{
if (j - i == 0)
{
return nums[i];
}
int a = divideAndConquer(nums, i, i + (j - i) / 2);
int b = divideAndConquer(nums, i + (j - i) / 2 + 1, j);
if(a == b) return a;
if(count(nums.begin() + i, nums.begin() + j + 1, a) > count(nums.begin() + i, nums.begin() + j + 1 , b))
{
return a;
}
else
{
return b;
}
}
};
另一种方法则是扫描一遍数组,记录下来每次不同元素出现的次数,这可以通过构建一个哈希表来完成,代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
std::map<int, int> hashTable;
for (int i = 0; i < nums.size(); i++)
{
hashTable[nums[i]]++;
if (hashTable[nums[i]] > nums.size() / 2)
{
return nums[i];
}
}
}
};