LeetCode169 Majority Element

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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

题源:here;完整实现:here

思路:

两种方法,第一种非常简单:利用一个map记录下每个数字出现的次数,找出超过nums大小两倍的数;第二种方法利用了majority出现次数多于nums.size()/2的这个设定,在这个设定的前提下,当我们遍历完整个数后,majority至少后剩下一次,细节请看代码。

解法一:

	int majorityElement(vector<int>& nums) {
		unordered_map<int, int> m;
		for (auto i : nums) {
			m[i]++;
			if (m[i] * 2 > nums.size()) return i;
		}
		return -1;
	}

解法二:

	int majorityElement2(vector<int>& nums) {
		int candidate = nums[0], count = 1;
		for (decltype(nums.size()) i = 1; i < nums.size(); i++) {
			if (nums[i] == candidate) count++;
			else {
				count--;
				if (count == 0) candidate = nums[i], count = 1;
			}
		}
		return candidate;
	}

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88321398