本文主要是介绍LeetCode: 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),所以我将使用分治法来解题。
分治法的思想就是先把这个问题分为和原问题类型相同的规模比较小的子问题,递归地解决子问题然后将各子问题的解合并从而得到原问题的解。
这道题中我们需要求出数组中的主元素,这个元素是确定存在的且出现超过 n/2 次。我们可以先把这个数组均分为A、B两个数组,然后在找A、B的主元素的时候又分别把A、B均分为两个更小的数组,一直找下去,得到前一半的主元素majorEle_A,后一半的主元素majorEle_B。如果majorEle_A与majorEle_B是同一个元素,则它就是主元素,否则就看哪个出现的次数多。
这种算法的时间复杂度为 T(n) = T(n/2) + 2n = O(n log n)
代码:
class Solution {
public:int majorityElement(vector<int>& nums) {if (nums.size() == 1) return nums[0];vector<int> A(nums.begin(), nums.begin() + nums.size() / 2);vector<int> B(nums.begin() + nums.size() / 2, nums.end());int majorEle_A = majorityElement(A);int majorEle_B = majorityElement(B);if (majorEle_A == majorEle_B) {return majorEle_A;} else {return count(nums.begin(), nums.end(), majorEle_A) > count(nums.begin(), nums.end(), majorEle_B) ? majorEle_A : majorEle_B;}}
};
其他解法:
分治法在本题中并不是最优解法。提交后我看到LeetCode上的推荐解法,除了分治法外还有以下几种。(破折号后面为时间复杂度)
1、Brute force solution. —— O(n^2)
2、Hash table. —— O(n)
3、Sorting. —— O(nlogn)
4、Randomization. ——最好情况下为O(n)
5、Moore voting algorithm. ——O(n)
6、Bit manipulation. ——O(n)
这篇关于LeetCode: Majority Element的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!