当前位置: 首页 > news >正文

LeetCode -- Majority Element

Majority Element


Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.


You may assume that the array is non-empty and the majority element always exist in the array.


Credits:
Special thanks to @ts for adding this problem and creating all test cases.


找出出现次数大于数组1/2 长度次的数字。


思路:

本题解法很多:

1.排序后判断第n/2个元素与首元素是否相等

2.哈希表

3.每次移除两个不等的元素

...


第3种方法最快,在实际应用中,哪种方式的时间复杂度都是可以接受的,这里的实现使用了第二种,即借助哈希表来完成统计。


实现代码:





public class Solution {
    public int MajorityElement(int[] nums) {
        if(nums.Length == 0){
    		return 0;
    	}
    	
    	var hash = new Dictionary<int, int>();
    	var max = 1;
    	var maxKey = nums[0];
    	for(var i = 0;i < nums.Length; i++){
    		if(hash.ContainsKey(nums[i])){
    			hash[nums[i]] ++;
    			if(max < hash[nums[i]]){
    				max = hash[nums[i]];
    				maxKey = nums[i];
    			}
    		}
    		else{
    			hash.Add(nums[i],1);
    		}
    	}
    	
    	return maxKey;
    }
}


相关文章:

  • LeetCode -- Max Points on a Line
  • ArcGIS Server Java ADF 案例教程 17
  • LeetCode -- Maximal Square
  • ArcGIS Server Java ADF 案例教程 18
  • LeetCode -- Summary Ranges
  • ArcGIS Server Java ADF 案例教程 19
  • ArcGIS Server Java ADF 案例教程 20
  • LeetCode -- Unique Paths
  • 警惕手机流氓软件的流行
  • LeetCode -- Combination Sum II
  • 学习百度、腾讯如何把产品做到极致(转载)
  • LeetCode -- Edit Distance
  • Leetcode -- Find Minimum in Rotated Sorted Array
  • SQL2005CLR函数扩展-树的结构
  • LeetCode -- Longest Consecutive Sequence
  • AWS实战 - 利用IAM对S3做访问控制
  • CSS中外联样式表代表的含义
  • Fabric架构演变之路
  • HomeBrew常规使用教程
  • Less 日常用法
  • passportjs 源码分析
  • PHP的Ev教程三(Periodic watcher)
  • Python十分钟制作属于你自己的个性logo
  • QQ浏览器x5内核的兼容性问题
  • SpiderData 2019年2月25日 DApp数据排行榜
  • spring-boot List转Page
  • TCP拥塞控制
  • 初识 webpack
  • 初探 Vue 生命周期和钩子函数
  • 关于Java中分层中遇到的一些问题
  • 批量截取pdf文件
  • 如何将自己的网站分享到QQ空间,微信,微博等等
  • 如何正确配置 Ubuntu 14.04 服务器?
  • 实现菜单下拉伸展折叠效果demo
  • 为什么要用IPython/Jupyter?
  • 问:在指定的JSON数据中(最外层是数组)根据指定条件拿到匹配到的结果
  • 一个JAVA程序员成长之路分享
  • 一些基于React、Vue、Node.js、MongoDB技术栈的实践项目
  • [地铁译]使用SSD缓存应用数据——Moneta项目: 低成本优化的下一代EVCache ...
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • 关于Kubernetes Dashboard漏洞CVE-2018-18264的修复公告
  • 新海诚画集[秒速5センチメートル:樱花抄·春]
  • ​【C语言】长篇详解,字符系列篇3-----strstr,strtok,strerror字符串函数的使用【图文详解​】
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • #pragam once 和 #ifndef 预编译头
  • #vue3 实现前端下载excel文件模板功能
  • #我与Java虚拟机的故事#连载01:人在JVM,身不由己
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (5)STL算法之复制
  • (6)STL算法之转换
  • (python)数据结构---字典
  • (编程语言界的丐帮 C#).NET MD5 HASH 哈希 加密 与JAVA 互通
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (四)linux文件内容查看
  • (转) Android中ViewStub组件使用