Leetcode 169.Majority Element

Source: Internet
Author: User

Topic:

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: runtime:229 ms

public class Solution {    //Learn online method, each find two different, then in pairs Delete, the last remaining is the element public    int majorityelement (int[] num) {        int Count = 0;        int maj = 0;        for (int i = 0; i < num.length; i++) {            if (count = = 0) {                maj = Num[i];                count++;            } else{                if (maj = = Num[i]) {                    count + +;                    if (Count > Num.length/2)                        return maj;                } else{                    Count--;}}        }        Return maj;}    }

 

Summary: This method is what I see from the Internet, but also most people's practice, just started to do not think of this method, but also want to use the array to do, but that is too complex. This method is worth learning.

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.