zoukankan      html  css  js  c++  java
  • [LeetCode]Majority Element

    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.

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    最简单的方法就是排序,然后中间的那个数字就是我们需要的结果,两行搞定,时间复杂度就是排序的最优值O(nlogn)。

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

    利用Hash Table可以实现O(n)的时间复杂度。

     1 class Solution {
     2 public:
     3     int majorityElement(vector<int>& nums) {
     4         unordered_map<int,int> showed;
     5         for(int i=0;i<nums.size();i++)
     6         {
     7             if(showed.find(nums[i])==showed.end())
     8             {
     9                 showed[nums[i]]=1;
    10             }
    11             else
    12             {
    13                 showed[nums[i]]++;
    14             }
    15         }
    16         unordered_map<int,int>::iterator iter;
    17         for(iter=showed.begin();iter!=showed.end();iter++)
    18         {
    19             if(iter->second>nums.size()/2)
    20             {
    21                 return iter->first;
    22             }
    23         }
    24     }
    25 };

    还有一种比较巧的方法,moore voting算法,时间复杂度也是O(n)。

     1 class Solution {
     2 public:
     3     int majorityElement(vector<int>& nums) {
     4         int result;
     5         int count=0;
     6         for(int i=0;i<nums.size();i++)
     7         {
     8             if(count==0)
     9             {
    10                 result=nums[i];
    11                 count=1;
    12             }
    13             else
    14             {
    15                 if(nums[i]==result) count++;
    16                 else count--;
    17             }
    18         }
    19         return result;
    20     }
    21 };

    这是官网给的解法提示。

  • 相关阅读:
    清明节实现所有网页变灰色
    点击按钮,复制文本
    Matlab笔记
    spring框架中配置mysql8.0需要注意的地方(转载)
    移动吉比特H2-2光猫超级用户与密码
    JS关闭chorme页面
    MATLAB利用solve函数解多元一次方程组
    微信聊天记录导出为csv,并生成词云图
    fmt.Sprintf(格式化输出)
    iris,context源码分析
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4786321.html
Copyright © 2011-2022 走看看