(Leetcode 169) Majority Element

Source: Internet
Author: User

Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .

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

Topic:

Give an array to find the number of people in the array, the number of occurrences is greater than the sum of the number of occurrences of all other numbers.

Suppose the array is not empty and the majority must exist

Idea: Method 1:hashmap

By iterating through the array, each number of the array is counted by HashMap to count the number of occurrences, and if a number exceeds half, the number is the majority.

The complexity of time space is O (n)

Method 2:moore Voting algorithm

In the case of a majority, each time two different numbers are thrown away, the number remains the same, and the final number must be the majority.

    • Throw away a number and a non-majority, the number is the same
    • Throw away two non-majority, and the number is the same

Time complexity O (n), Spatial complexity O (1)

Code:
classSolution { Public:    //Hash_map Method    intMajorityElement1 (vector<int> &num) {        intn =num.size (); if(n==1)returnnum[0]; Map<int,int>m;  for(vector<int>::iterator It=num.begin (); It!=num.end (); it++) {m[*it]+=1; if(M[*it] > Floor (n/2))                return*it; }    }    //Moore Voting algorithm    intMajorityElement2 (vector<int> &num) {        intn=num.size (); if(n==1)returnnum[0]; intCount=0; intx;  for(intI=0; i<n;i++){            if(count==0) {x=Num[i]; Count=1; }            Else if(x==Num[i])++count; Else--count; }        returnx;};

(Leetcode 169) 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.