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 };

    这是官网给的解法提示。

  • 相关阅读:
    C&Pointer求解wc问题
    软件测试作业2
    第六周小组作业
    WordCount改进 小组项目
    WordCount
    我的“游戏”人生
    软件测试第6周小组作业
    软件测试第4周小组作业:WordCount优化
    软件测试第二周个人作业:WordCount
    MVC模式下基于SSH三大框架的java web项目excel表格的导出(不依赖另外的jar包)
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4786321.html
Copyright © 2011-2022 走看看