169. Majority Element && 229. Majority Element II

Source: Internet
Author: User

169. Majority Element

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.  

Hide TagsArray Divide and conquer Bit manipulationHide Similar Problems(M) Majority Element IIMore Readings:https://en.wikipedia.org/wiki/boyer%e2%80%93moore_majority_vote_algorithm
 Public classSolution { Public intMajorityelement (int[] num) {    intMajor = Num[0]; intCount = 1; //The majority number has enough counts to cover all other numbers     for(inti = 1; i < num.length; ++i) {if(count = = 0) {        ++count; Major=Num[i]; } Else if(Major = =Num[i]) {        ++count; } Else--count; }    returnMajor; }}

229. Majority Element II

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!

Hide Tags

ArrayHide Similar Problems(E) Majority Element
 Public classSolution { PublicList<integer> Majorityelement (int[] nums) {List<Integer> results =NewArraylist<>(); if(Nums = =NULL|| Nums.length = = 0)      returnresults; intN1 = Nums[0]; intN2 = Nums[0]; intcount1 = 0;//Count keeps a "relative" count of current number    intCount2 = 0; intLen =nums.length;  for(inti = 0; i < Len; ++i) {if(Nums[i] = =N1)++Count1; Else if(Nums[i] = =n2)++Count2; Else if(Count1 = = 0) {N1=Nums[i]; Count1= 1; } Else if(Count2 = = 0) {n2=Nums[i]; Count2= 1; } Else {        //zeros were check beforehand to make sure counts won ' t go negative--Count1; --Count2; }} count1= 0; Count2= 0;  for(inti = 0; i < Len; i++) {      if(Nums[i] = =N1)++Count1; Else if(Nums[i] = =n2)++Count2; }    if(Count1 > LEN/3) Results.add (N1); if(Count2 > LEN/3) Results.add (N2); returnresults; }}

169. Majority Element && 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.