"Leetcode" Majority Element

Source: Internet
Author: User

Test instructions

Given an array of size n, find the majority element. The majority element is the element, which appears more than? N/2? Times.

Assume that the array was non-empty and the majority element always exist in the array.


Ideas:

Find the number of occurrences greater than N/2 in the array.

In C + +, map is particularly handy for this number of statistics, and Python is of course used in dictionaries.


Code:

C++

Class Solution{public:    int majorityelement (vector<int> &num) {        Vector<int>::iterator it = Num.begin ();        int n = num.size ();        map<int,int> count;        for (; it! = Num.end (); it++)        {            //Why is there no need to determine the existence of a key here? Initialize to 0            if (++count[*it] > N/2)            {                return *it;            }}        } because    it does not exist;

Python:

Class solution:    # @param num, a list of integers    # @return An integer    def majorityelement (self, num):        coun t = Dict ([])        flag = len (num)/2 for        item in num:            if item in count:                count[item] = Count[item] + 1            else:< C9/>count[item] = 1                            if Count[item] > flag:                return item

"Leetcode" Majority Element

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.