1. 程式人生 > >leetcode 169 Majority Element

leetcode 169 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.

找到這個陣列中出現次數超過n/2次的元素,假設這個元素一定是存在的。
一個簡單的方法就是排序後找中間的元素,程式碼如下:

class
Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size() / 2]; } };

還有一種方法就是分而治之,每次將這個陣列分為兩半分別去找兩邊的主元素,若兩邊的主元素不同則利用count方法比較出現次數,時間複雜度略優

class Solution {
public:
    int majorityElement(vector<int>
& nums) { return divideMajor(nums, 0, nums.size() - 1); } int divideMajor(vector<int>& nums, int begin, int end) { if (begin == end) { return nums[begin]; } int leftM = divideMajor(nums, begin, (begin + end) / 2); int rightM = divideMajor(nums, (begin + end) / 2
+ 1, end); if (leftM == rightM) { return leftM; } if (count(nums.begin() + begin, nums.begin() + end+1, leftM) < count(nums.begin() + begin, nums.begin() + end+1, rightM)) { return rightM; } else { return leftM; } } };