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:
- How many majority elements could it possibly?
- 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