码迷,mamicode.com
首页 > 其他好文 > 详细

Majority Element

时间:2015-06-22 12:17:32      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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.

Code:

解法一

int majorityElement(vector<int>& nums) {
        //方法参见剑指Offer
      int result = nums[0];
      int times = 1;
      
      for (int i = 1; i < nums.size(); i++)
      {
          if (times == 0)
          {
              result = nums[i];
              times = 1;
          }
          else if (result == nums[i])
          {
              times++;
          }
          else 
          {
              times--;
          }
      }
      return result;
    }

解法二:hash表

 1 int majorityElement(vector<int>& nums) {
 2         //方法参见剑指Offer
 3         unordered_map<int,int>m;
 4         int n = nums.size();
 5         for ( int i = 0; i < n; ++i )
 6         {
 7             if ( !m.count(nums[i]) )
 8                 m[nums[i]] = 1;
 9             else
10             {
11                 ++m[nums[i]];
12             }
13             if ( m[nums[i]] > n/2 )
14                 return nums[i];
15         }
16     }

 

Majority Element

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4593008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!