給一個大小為 n 的陣列,找出出現次數超過 n/2 的元素。(可以預期這個元素一定存在)
這個是計數題,數一遍 n 並且統計出現次數,就能找到 majority element。
Python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
import collections
counter = collections.Counter(nums)
n = len(nums)
for key in counter:
if counter[key] >= n/2:
return key
public class Solution {
public int MajorityElement(int[] nums) {
var counter = new Dictionary();
int halfN = nums.Length/2 + (nums.Length%2==1 ? 1: 0);
foreach(var num in nums)
{
counter[num] = 1 + (counter.ContainsKey(num) ? counter[num]: 0);
if(counter[num] >= halfN)
{
return num;
}
}
return 0;
}
}