给定一个数组(长度为n),找出“多数元素”(出现次数大于n/2),假定数组不为空且“多数元素”一定存在。

思路一:
将数组排序,则最中间的那个数一定是“多数元素”。

时间复杂度:O(n*lgn)

class Solution:def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""nums.sort()return nums[len(nums)//2]

思路二:
使用dict用来记录数组里每个数出现的次数。
空间复杂度:O(n),时间复杂度:O(n)

class Solution(object):def majorityElement(self, nums):count = {}for i in nums:if i in count:count[i] += 1else:count[i] = 1return max(count, key=count.get)
  • 相关知识点:
    get():返回指定键的值,如果值不在字典中则返回默认值。

10/100. Majority Element相关推荐

  1. 【LeetCode 169】Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  2. Majority Element(169) Majority Element II(229)

    寻找多数元素这一问题主要运用了:Majority Vote Alogrithm(最大投票算法) 1.Majority Element 1)description Given an array of s ...

  3. OJ 169 Majority Element

    题目要求:Given an array of size n, find the majority element. The majority element is the element that a ...

  4. Leetcode-169 Majority Element

    #169 Majority Element Given an array of size n, find the majority element. The majority element is t ...

  5. [LeetCode] Majority Element II

    Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ...

  6. Leetcode 169 Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  7. LeetCode 169 Majority Element(Majority Voting Algorithm)

    Majority Element Given an array of size n, find the majority element. The majority element is the el ...

  8. Majority Element:主元素

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  9. js实现随机选取[10,100)中的10个整数,存入一个数组,并排序。 另考虑(10,100]和[10,100]两种情况。...

    1.js实现随机选取[10,100)中的10个整数,存入一个数组,并排序. 1 <!DOCTYPE html> 2 <html lang="en"> 3 & ...

最新文章

  1. 更高效的PacBio长read纠错算法的研究
  2. JAVA用JNI方法调用C代码实现HelloWorld
  3. Request请求用Cookie记录SessionId
  4. java http 401_服务器返回HTTP响应代码:401,URL:https
  5. Math.Floor()和Math.Truncate()之间的区别
  6. 这样配置,让你的 IDEA 好用到飞起来!
  7. SpringBoot整合Security安全框架、控制权限
  8. 利用Python实现gif动图倒放
  9. HTML5前端知识分享:Vue入门
  10. .NETer,如何用.NET Core 3.0武装自己?这样学效率提高10倍!
  11. android 开源图表动画,Android 图表开发开源库MPAndroidChart-Go语言中文社区
  12. hive2 mysql_架构hive2mysql流程
  13. Spring多资源文件properties的配置
  14. python循环小甲鱼教程_python之 小甲鱼教程 Easygui 篇
  15. CSS Lint-线上CSS检测工具 让你的样式表更正确精简
  16. Python学习 5day__基础知识
  17. 中發白——企业软件公司的战略大三元
  18. Premiere 输出视频
  19. jquery点击按钮删除文本框的内容
  20. 趋高机器视觉之机械手臂的应用

热门文章

  1. 联想拯救者r720适合java么_联想拯救者哪个型号好 联想拯救者r720怎么样【详解】...
  2. simulink和psim仿真结果不同_CAE仿真分析规范是什么?涨知识啦!
  3. python函数调用语句_Python函数定义和函数调用
  4. iis php 数据库乱码,如何解决php插入数据乱码问题
  5. 商品领域ddd_DDD 领域驱动设计-商品建模之路
  6. linux搜索含多个字符串,使用grep搜索多个字符串
  7. java文件读写 outputstream_java IO文件读写例子(OutputStream,InputStream,Writer,Reader)...
  8. HTML5 Web Worker
  9. JVM插桩之三:javaagent介绍及javassist介绍
  10. 【vulnhub】靶机- [DC系列]DC9(附靶机))