Majority Element【找主元素】

xiaoxiao2021-02-28  42

PROBLEM

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.

SOLVE

总结:Java方法更巧妙,C++需要掌握map的用法,Python list的sort函数。

c++:

class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int, int> counts; int n = nums.size(); for (int i = 0; i < n; i++) if (++counts[nums[i]] > n / 2) return nums[i]; } };

unordered_mapmap类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序,

存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。

所以使用时map的key需要定义operator<。而unordered_map需要定义hash_value函数并且重载operator==。但是很多系统内置的数据类型都自带这些,

那么如果是自定义类型,那么就需要自己重载operator<或者hash_value()了。

结论:如果需要内部元素自动排序,使用map,不需要排序使用unordered_map

Java:

class Solution {     public int majorityElement(int[] nums) {         int count = 0;         Integer candidate = null;         for (int num : nums) {             if (count == 0)                 candidate = num;             count += (num == candidate) ? 1 : -1;         }         return candidate;     } }

相对来说这个方法更巧妙,称之为:Boyer-Moore Voting Algorithm需要掌握。

Python:

class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ return sorted(num)[len(num)/2]
转载请注明原文地址: https://www.6miu.com/read-2627254.html

最新回复(0)