当前位置:网站首页>[leetcode] most elements [169]
[leetcode] most elements [169]
2022-07-02 22:52:00 【When camellia flowers bloom.】
problem : Given a size of n Array of nums, Return most of the elements ( Most elements refer to the number of occurrences in an array Greater than n/2 The elements of )
You can assume that the array is not empty , And there are always many elements in a given array
Example 1
Input : nums = [3,2,3]
Output : 3
Example 2
Input : nums = [2,2,1,1,1,2,2]
Output : 2
Python3 Problem solving
# solution 1
def majorityElement(nums):
length = len(nums) / 2
set_nums = set(nums)
for i in set_nums:
if nums.count(i) > length:
return i
# solution 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
Knowledge points involved :
[Python] set() function https://blog.csdn.net/Hudas/article/details/122882024
[Python] count() Method https://blog.csdn.net/Hudas/article/details/122941544
边栏推荐
- 影视随摘
- 【微服务|Sentinel】重写sentinel的接口BlockExceptionHandler
- 世界环境日 | 周大福用心服务推动减碳环保
- Phpcms realizes the direct Alipay payment function of orders
- Go 4 modes Singleton
- Based on asp Net (used mobile phone sales management system) +asp Net+c # language +vs2010+ database can be used for course design and post design learning
- #include errors detected. Please update your includePath.
- Graphic view frame
- Oracle-游标
- 附加:【登录信息存储】与【登录状态校验】;(包括:总结了到目前为止,有关【登录信息存储】与【登录状态校验】的所有内容;)
猜你喜欢
Performance optimization - rigorous mode
uniapp微信登录返显用户名和头像
小鹏P7出事故,安全气囊未弹出,这正常吗?
PMP项目整合管理
Phpcms realizes the direct Alipay payment function of orders
任务和特权级保护
【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)
Baidu AI Cloud - create a face recognition application
[LeetCode] 多数元素【169】
[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
随机推荐
Jerry's modification does not require long press the boot function [chapter]
杰理之、产线装配环节【篇】
SimpleITK使用——3. 常见操作
[LeetCode] 回文数【9】
PHP implements querying the data matching the date of birth according to the entered age
大一学习分享
UE4 UI adaptive screen
php优化foreach中的sql查询
SimpleITK使用——4. 奇怪的问题
Go condition variable
傑理之修改不需要長按開機功能【篇】
wait解决僵尸进程
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
牛客网:最大子矩阵
'when to use const char * and when to use const char []' - when to use const char * and when to use const char []
《乔布斯传》英文原著重点词汇笔记(十一)【 chapter nine】
Solve the error of changing the selected file when uploading excel file. Net:: err_ UPLOAD_ FILE_ CHANGED
Go four singleton modes
Get off work on time! Episode 6 of Excel Collection - how to split and count document amounts
Wait to solve the zombie process