当前位置:网站首页>[LeetCode] 多数元素【169】
[LeetCode] 多数元素【169】
2022-07-02 22:06:00 【山茶花开时。】
问题: 给定一个大小为n的数组nums,返回其中的多数元素(多数元素是指在数组中出现次数大于n/2的元素)
你可以假设数组是非空的,并且给定的数组总是存在多数元素
示例1
输入: nums = [3,2,3]
输出: 3
示例2
输入: nums = [2,2,1,1,1,2,2]
输出: 2
Python3解题
# 解法1
def majorityElement(nums):
length = len(nums) / 2
set_nums = set(nums)
for i in set_nums:
if nums.count(i) > length:
return i
# 解法2
import collections
def majorityElement(nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
majorityElement([3,2,3]) # 3
majorityElement([2,2,1,1,1,2,2]) # 2
涉及知识点:
[Python] set()函数https://blog.csdn.net/Hudas/article/details/122882024
[Python] count()方法https://blog.csdn.net/Hudas/article/details/122941544
边栏推荐
- [shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
- Task and privilege level protection
- Market Research - current market situation and future development trend of aircraft wireless intercom system
- Perceptron model and Application
- Basic concepts of image and deep understanding of yuv/rgb
- [QT] QT multithreading development - four methods to realize multithreading design
- Service visibility and observability
- SimpleITK使用——4. 奇怪的问题
- New feature of go1.18: trylock, which has been tossed n times
- Share how to make professional hand drawn electronic maps
猜你喜欢
scrcpy这款软件解决了和同事分享手机屏幕的问题| 社区征文
Reading experience of just because
百度智能云-创建人脸识别应用
phpcms实现订单直接支付宝支付功能
New feature of go1.18: introduce new netip Network Library
Sql service intercepts string
电商系统微服务架构
`${}`的用法
Objects and object variables
[shutter] shutter gesture interaction (small ball following the movement of fingers)
随机推荐
NC24325 [USACO 2012 Mar S]Flowerpot
Socket socket c/s end process
《乔布斯传》英文原著重点词汇笔记(十)【 chapter eight】
服务器响应状态码
Market Research - current situation and future development trend of anterior cruciate ligament (ACL) reconstruction Market
SimpleITK使用——4. 奇怪的问题
Technological Entrepreneurship: failure is not success, but reflection is
scrcpy这款软件解决了和同事分享手机屏幕的问题| 社区征文
Unity3d learning notes 4 - create mesh advanced interface
PHP wechat red packet grabbing algorithm
U++ learning notes - relaxation
PHP optimizes SQL queries in foreach
'when to use const char * and when to use const char []' - when to use const char * and when to use const char []
Regular expression (2)
Dynamic memory allocation (malloc calloc realloc free)
Build your own website (22)
Market Research - current market situation and future development trend of night vision goggles for pilots
Methods of adding styles to native JS
phpcms实现订单直接支付宝支付功能
Simpleitk use - 4 Strange question