LeetCode Algorithm 169. 多数元素
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 169. 多数元素
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
169. 多數元素
Ideas
這題對Python來說太沒意思了,一個計數器就搞完了。
那如果不用計數器怎么做呢,注意到多數元素的個數時大于n2\frac{n}{2}2n?的,所以如果給數組排個序,那么在中間位置的元素肯定就是多數元素。(C++實現)
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]總結
以上是生活随笔為你收集整理的LeetCode Algorithm 169. 多数元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020年第十一届蓝桥杯 - 省赛 -
- 下一篇: LeetCode Algorithm 2