刷题169. Majority Element

一、题目说明

题目169. Majority Element,给定n个数的数组,返回出现次数超过半数的元素。

二、我的解答

这个题目用一个map,遍历一遍数组,计数每个元素出现的次数。

class Solution{
	public:
		int majorityElement(vector& nums){
			unordered_map ump;
			int maxNum = 0;
			int maxCount = 0;
			for(int i=0;i

性能如下:

Runtime: 28 ms, faster than 32.81% of C++ online submissions for Majority Element.
Memory Usage: 11.2 MB, less than 15.15% of C++ online submissions for Majority Element.

三、优化措施

上面用的是unordered_map,改用map实现:

Runtime: 20 ms, faster than 82.58% of C++ online submissions for Majority Element.
Memory Usage: 11.2 MB, less than 39.39% of C++ online submissions for Majority Element.

通过超过半数,实现:

class Solution{
	public:
		int majorityElement(vector& nums){
			map ump;
			int half = (nums.size()+1)/2;
			for(int i=0;i=half){
					return nums[i];
				}
			}
			return -1;
		} 
};

性能如下:

Runtime: 24 ms, faster than 54.42% of C++ online submissions for Majority Element.
Memory Usage: 11.1 MB, less than 63.64% of C++ online submissions for Majority Element.

你可能感兴趣的:(刷题169. Majority Element)