Majority Element (array-binary SEARCH)

Source: Internet
Author: User

QUESTION

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.

First TRY

Each of the two different element is found, then the pair is deleted. The rest of the end must be what you ask for.

classSolution { Public:    intMajorityelement (vector<int> &num) {        intret; intNtimes =0;  for(inti =0; I < num.size (); i++){            if(Ntimes = =0) {ret=Num[i]; Ntimes++; }            Else if(ret = = Num[i]) ntimes++; Elsentimes--;//2 different number, delete}returnret; }};

result:accepted

Can be extended to ⌊n/k⌋, each k different element is deleted in pairs.

Majority Element (array-binary SEARCH)

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.