229. Majority Element II

Source: Internet
Author: User

Given an integer array of size n, find all elements this appear more than times ? n/3 ? . The algorithm should run in linear time and in O (1) space.

Hint:

    1. How many majority elements could it possibly?
    2. Do you have a better hint? Suggest it!

This question is about Moore's voting law. Specifically, you can refer to Grandyang's explanation. The code is as follows

 Publicilist<int> Majorityelement (int[] nums) {        intm =0; intn =0; intCM =0; intCN =0; foreach(varNuminchnums) {            if(m = = num) cm++; Else if(n = = num) cn++; Else if(cm = =0) {cm=1; M=num; }            Else if(cn==0) {cn=1; N=num; }            Else{cm--; CN--; }} cm=0; CN=0; foreach(varNuminchnums) {            if(m = = num) cm++; Else if(n = = num) cn++; }        varres =Newlist<int>(); if(cm > Nums. Count ()/3) Res.        ADD (m); if(CN > Nums. Count ()/3) Res.        ADD (n); returnRes; }

Note several corner case

[0,0,0], this requires the second cycle of the time must be if else, if not, will return [0,0].

[0,1] It is also important to note that the last cm CN is to be greater than or greater than equals. Otherwise this output is going to work [0,1]

229. Majority Element II

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.