当前位置:网站首页>Leetcode169-多数元素详解
Leetcode169-多数元素详解
2022-07-25 23:55:00 【白羊by】
往期博客:
目录
题目
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
出现次数大于n/2,表明该元素个数占整个数组的一半以上
示例
示例1
输入:nums = [3,2,3] 输出:3
示例2
输入:nums = [2,2,1,1,1,2,2] 输出:2
解析
排序法
既然多数元素占一半以上,那么将整个数组排序后,处于数组中间的元素即为多数元素

哈希表
从头到尾遍历整个数组,记录每个数字出现的次数,key为元素,value为出现的次数,value最大的元素为多数元素

代码
排序法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort() # 排序
half = len(nums) // 2
return nums[half]哈西表
class Solution:
def majorityElement(self, nums: List[int]) -> int:
mapping = {}
for num in nums:
if num not in mapping:
mapping[num] = 0
mapping[num] = mapping.get(num)+1
half = len(nums) // 2
for key in mapping.keys():
if mapping[key] > half:
return key
return -1边栏推荐
- What is parity? How to use C language?
- What is the difference between'1 and'b1 when assigning values
- R语言安装教程 | 图文介绍超详细
- ArcGIS cuts TIF images (grid data) according to the vector range, merges shp files in batches, cuts vectors in the region according to the vector range, outputs the geographic coordinate system, conve
- Exercise (1) create a set C1 to store the elements "one", "two", "three"“
- VSCode格式化Json文件
- 【英雄哥七月集训】第 24天: 线性树
- Get the data of Mafeng Hotel
- 静态代理+动态代理
- SIGIR‘22 推荐系统论文之图网络篇
猜你喜欢

C - readonly and const keywords

赋值时'1和'b1有什么区别

行为型模式之观察者模式

S4/hana mm & SD EDI Nast based integrated configuration (orders, ordrsp, desadv, invoice)

S4/HANA ME21N创建PO 输出控制消息按钮丢失解决方法(切换EDI 输出模式BRF+至NAST模式)

获取马蜂窝酒店数据

ArcGIS cuts TIF images (grid data) according to the vector range, merges shp files in batches, cuts vectors in the region according to the vector range, outputs the geographic coordinate system, conve

Ten threats to open API ecosystem

ABAP 代码中读取会计科目的字段状态(隐藏、可选、必输)

Zhiniu stock -- 09
随机推荐
Write a select drop-down list
From which dimensions can we judge the quality of code? How to have the ability to write high-quality code?
SQLZOO——Nobel Quiz
S4/hana ME21N create Po output control message button missing solution (switch EDI output mode brf+ to Nast mode)
回溯——77. 组合
Firewall command simple operation
Call nailing API and report an error: the signature sent by the robot is expired; Solution: please keep the signature generation time and sending time within timestampms
Yolov3 trains its own data set
Exercise (1) create a set C1 to store the elements "one", "two", "three"“
MySQL的DDL、DML和DQL的基本语法
Part 66: monocular 3D reconstruction point cloud
Imitating the magnifying glass effect of JD products -- JS Foundation
Nacos offline service times error errcode: 500
如何用yolov5 做个闯红灯监控的智能交通系统(1)
抽丝剥茧C语言(高阶)程序环境和预处理
[testing technology automated testing pytest] basic summary of pytest
Read the field status of account in ABAP code (hidden, optional, required)
Shardingsphere data slicing
Scroll case: return to top with animation
SAP Message No. VG202 IDoc E1EDK18 中付款条款已经转移:检查数据