"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.

Ideas:

Finds a number in an array that has more than half occurrences. Sorting, hashing and other methods do not mention, considering the complexity of O (n), there is a legendary Moore voting algorithm available. In fact, it is also very simple, the initial selection of the first element, in turn compared to it and other elements, if equal to the number of votes plus one, or minus one, when its vote is 0 o'clock, replace the voting object is the current element, continue to execute, the result can be obtained (the existence of such a number in the array, otherwise, Depends on the order in which the elements are placed).

C++:

1 classSolution {2  Public:3     intMajorityelement (vector<int> &num) {4         5         intLen =num.size ();6         if(len = =0)7             return 0;8         9         intCNT =0, ret = num[0];Ten          for(inti =0; i < Len; i++) One         { A             if(CNT = =0) -             { -RET =Num[i]; thecnt++; -             } -             Else -             { +                 if(Num[i] = =ret) -cnt++; +                 Else Acnt--; at             } -         } -         returnret; -     } -};

Python:

1 classSolution:2     #@param {integer[]} nums3     #@return {integer}4     defmajorityelement (Self, nums):5RET, CNT =0, 06         7          forValinchNums:8             ifCNT = =0:9RET =ValTenCNT = 1 One             Else: A                 ifRET = =Val: -CNT = cnt + 1 -                 Else: theCNT = cnt-1 -         returnret -         

"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.