LeetCode Algorithm 169. 多数元素
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 169. 多数元素
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
169. 多數(shù)元素
Ideas
這題對Python來說太沒意思了,一個(gè)計(jì)數(shù)器就搞完了。
那如果不用計(jì)數(shù)器怎么做呢,注意到多數(shù)元素的個(gè)數(shù)時(shí)大于n2\frac{n}{2}2n?的,所以如果給數(shù)組排個(gè)序,那么在中間位置的元素肯定就是多數(shù)元素。(C++實(shí)現(xiàn))
Code
C++
class Solution { public:int majorityElement(vector<int>& nums) {sort(nums.begin(), nums.end());return nums[nums.size() / 2];} };Python
class Solution:def majorityElement(self, nums: List[int]) -> int:counter = Counter(nums)return counter.most_common(1)[0][0]總結(jié)
以上是生活随笔為你收集整理的LeetCode Algorithm 169. 多数元素的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020年第十一届蓝桥杯 - 省赛 -
- 下一篇: LeetCode Algorithm 2