【Divide and Conquer】169. Majority Element(easy)

#Week_1#

#From LeetCode#

Description:


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.

Analysis:


这一题是在分治类型底下的一道easy题目,但是读了题目之后,我第一感觉想到的就是直接扫描存下各个数的计数,然后再找到那个计数超过n/2的majority element。

如果先直接扫描后寻找majority element,则时间复杂度为O(n),总的来说还是比较快的,题目没有给出n的规模,不过还可以继续在这个方法的基础上剪一下支。

在扫描的时候直接判断元素的计数是否大于n/2,如果是则直接得到了,这样就更快了。

题目类型是分治,我觉得这个题目用分治太过大材小用了,有点麻烦。

不过看到了discussion里面有各种方法的解答,感觉很不错,里面也有分治的思想,大家可以参考参考。

链接:https://leetcode.com/problems/majority-element/discuss/

Code:


 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         map<int, int> countOfNum;
 5         int size = nums.size();
 6         for (int i = 0; i < size; i++) {
 7             if (++countOfNum[nums[i]] > (size / 2)) return nums[i];
 8         }
 9     }
10 };

run time:23ms

原文地址:https://www.cnblogs.com/iamxiaoyubei/p/7496346.html