Majority Number
Posted YuriFLAG
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Majority Number相关的知识,希望对你有一定的参考价值。
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
1 public class Solution { 2 /** 3 * @param nums: a list of integers 4 * @return: find a majority number 5 */ 6 public int majorityNumber(ArrayList<Integer> nums) { 7 int count = 0, candidate = -1; 8 for (int i = 0; i < nums.size(); i++) { 9 if (count == 0) { 10 candidate = nums.get(i); 11 count = 1; 12 } else if (candidate == nums.get(i)) { 13 count++; 14 } else { 15 count--; 16 } 17 } 18 return candidate; 19 } 20 }
以上是关于Majority Number的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 169. Majority Element
LeetCode 229 Majority Element II(主要元素II)(Array)(Boyer–Moore majority vote algorithm)