Skip to content
本页目录

0169-多数元素

https://leetcode.cn/problems/majority-element

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于⌊ n/2 ⌋的元素。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例1:

输入:[3,2,3]
输出:3

示例2:

输入:[2,2,1,1,1,2,2]
输出:2

进阶:

  • 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

思路1: 字典

字典 Dictionary 数字的个数,最后判断 大于 n/2

csharp
public class Solution {
    public int MajorityElement(int[] nums) {
    	Dictionary<int,int> dict = new Dictionary<int,int>();
    	for(int i=0; i<nums.Length; i++){
            int key = nums[i];
    		if(dict.ContainsKey(key)){
    			dict[key]++;
    		}
    		else{
    			dict.Add(key,1);
    		}
    	}
    	//检查个数,注意是返回 key , 原来的值,而不是个数
    	foreach(int key in dict.Keys){
            //Console.WriteLine("key:{0},value:{1}",key,dict[key]);
    		if(dict[key] > (nums.Length / 2)){
    			return key;
    		}
    	}
    	return -1;
    }
}

思路2 : 时间复杂度O(n),空间复杂度 O(1)

TODO : Boyer-Moore 投票算法

Released under the MIT License.