這個是計數題,數一遍 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 keyC#
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; } }