当前位置:网站首页>[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
边栏推荐
- [QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
- Pointer and string
- [shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
- 杰理之充电拔出,无法触摸开机【篇】
- 数学建模——图与网络模型及方法(一)
- Market Research - current situation and future development trend of anti-counterfeiting label market
- Build your own website (22)
- Unity3d learning notes 4 - create mesh advanced interface
- 任务和特权级保护
- Try to get property'num for PHP database data reading_ rows' of non-object?
猜你喜欢

Build your own website (22)

kubernetes 使用主机名将 pod 分配在指定节点上

Ransack combined condition search implementation

附加:【登录信息存储】与【登录状态校验】;(包括:总结了到目前为止,有关【登录信息存储】与【登录状态校验】的所有内容;)

Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?

Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
![[shutter] shutter gesture interaction (small ball following the movement of fingers)](/img/5a/a8dad8a0943645c980cc4fe7cb55d4.gif)
[shutter] shutter gesture interaction (small ball following the movement of fingers)

Oracle cursor

电商系统微服务架构

UE4 游戏架构 学习笔记
随机推荐
#include errors detected. Please update your includePath.
An overview of the development of affective computing and understanding research
LxC terminal login method
PHP optimizes SQL queries in foreach
Market Research - current situation and future development trend of carob chocolate market
App page sharing password rails implementation
#include errors detected. Please update your includePath.
【外刊】睡眠与减肥
百度智能云-创建人脸识别应用
Try to get property'num for PHP database data reading_ rows' of non-object?
《乔布斯传》英文原著重点词汇笔记(九)【 chapter seven】
Methods of adding styles to native JS
JS solution for obtaining the width and height of hidden elements whose display is none
Struct, bit segment, enumeration, union
Oracle PL / SQL programming
What is the'function'keyword used in some bash scripts- What is the 'function' keyword used in some bash scripts?
SimpleITK使用——4. 奇怪的问题
PMP项目整合管理
Attack and defense world PWN question: Echo
佩服,竟然有人把高等数学这么晦涩难懂的科目,讲解得如此通俗易懂