当前位置:网站首页>[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
边栏推荐
- Jatpack------LiveData
- 对象与对象变量
- 大一学习分享
- 数学建模——图与网络模型及方法(一)
- 《乔布斯传》英文原著重点词汇笔记(十)【 chapter eight】
- Additional: [login information storage] and [login status verification]; (including: summarizing all the contents of [login information storage] and [login status verification] so far;)
- Source code analysis - lightweight asynchronous crawler framework Ruia
- Storage unit conversion
- 傑理之修改不需要長按開機功能【篇】
- [LeetCode] 多数元素【169】
猜你喜欢
Utilisation de simpletk - 4. Question étrange
UE4 游戏架构 学习笔记
[LeetCode] 数组中的第K个最大元素【215】
百度智能云-创建人脸识别应用
建立自己的网站(22)
加油站[问题分析->问题转换->贪心]
【板栗糖GIS】arcscene—如何做出有高度的高程图
Perceptron model and Application
Additional: [login information storage] and [login status verification]; (including: summarizing all the contents of [login information storage] and [login status verification] so far;)
牛客网:龙与地下城游戏
随机推荐
Golang的学习路线
I admire that someone explained such an obscure subject as advanced mathematics so easily
Dahua cloud native load balancing article - the passenger flow of small restaurants has increased
Wait to solve the zombie process
Rails 3 activerecord: sort by association count - rails 3 activerecord: order by count on Association
Oracle-PL/SQL编程
PHP wechat red packet grabbing algorithm
Golang interview finishing three resumes how to write
JS solution for obtaining the width and height of hidden elements whose display is none
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
全面解析分享购商业模式逻辑?分享购是如何赋能企业
Simpleitk use - 4 Strange question
UE4 game architecture learning notes
电商系统微服务架构
Storage unit conversion
Source code analysis - lightweight asynchronous crawler framework Ruia
钟薛高回应产品1小时不化:含固体成分 融化不能变成水
SimpleITK使用——4. 奇怪的問題
Comprehensively analyze the logic of the shared purchase business model? How sharing purchase empowers Enterprises
分享 10 个 JS 闭包面试题(图解),进来看看你能答对多少