Majority Element

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     }

 

你可能感兴趣的:(element)