LeetCode: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.

解法一:

moore voting algorithm

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        //moore voting algorithm
        int majority=0;
        int count=0;
        
        for(int i=0;i<nums.size();i++)
        {
            if(count==0)
            {
                majority=nums[i];
                count=1;
            }
            else 
            {
                if(nums[i]==majority)
                {
                    count++;
                }
                else
                {
                    count--;
                }
            }
        }
        return majority;
    }
};

 解法二:hashmap实现

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

 

posted @ 2015-08-13 20:56  尾巴草  阅读(124)  评论(0编辑  收藏  举报