Leetcode majority elements

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.

Solution:

As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate are unknown and the counter is 0.

When we move the pointer forward to an element e:

    • If The counter is 0, we set the current candidate to e and we set the counter to 1.
    • If The counter is not 0, we increment or decrement the counter according to whether e are the current candidate.

When we do, the current candidate is the majority element, and if there is a majority.

public class Solution {public    int majorityelement (int[] num) {    int sum=0;    int result=0;    for (int i=0;i<num.length;i++) {    if (sum==0) {    result=num[i];    sum++;    }    else if (Result==num[i]) {    sum++;    if (SUM>NUM.LENGTH/2) {    return result;    }    }    else sum--;    }    return result;}    }

  

Leetcode majority elements

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.