Majority Element
2015-07-14 13:43
330 查看
题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
Simple but nlog(n) time complexity
Linear Time Majority Vote Algorithm 很高级的样子
reference:http://www.programcreek.com/2014/02/leetcode-majority-element-java/
http://www.cs.utexas.edu/~moore/best-ideas/mjrty/
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.
Simple but nlog(n) time complexity
public int majorityElement(int[] num) { if (num.length == 1) { return num[0]; } Arrays.sort(num); return num[num.length / 2]; }
Linear Time Majority Vote Algorithm 很高级的样子
public int majorityElement(int[] nums) { int candidate= 0, count = 0; for(int i = 0; i<nums.length; i++ ) { if(count == 0){ candidate= nums[ i ]; count = 1; }else if(candidate == nums[i]){ count++; }else{ count--; } } return candidate; }
reference:http://www.programcreek.com/2014/02/leetcode-majority-element-java/
http://www.cs.utexas.edu/~moore/best-ideas/mjrty/
相关文章推荐
- GRE写作必备句型
- Thinking in Java 第七章 多态 第八章:接口与内部类 第九章:异常处理
- Inline Assemble Code - A problem relevant to register usage
- BZOJ 1013 [JSOI2008]球形空间产生器sphere
- LeetCode - Binary Search Tree Iterator
- tinyMCE粘贴word/html时去掉文本里的样式
- 大话设计模式(十一 三层架构,分层开发)
- VC 使用OnCtlColor函数来改变控件颜色
- SQL Server Profiler:使用方法和指标说明
- web基础知识
- H5+ 分享到微信、朋友圈代码示例
- phpmyadmin修改文件上传大小限制
- 傻啵似的学、、、、(简单文件权限)
- NYOJ 6 喷水装置(一)
- codeforces 520B Two Buttons BFS
- Navicat:excel数据导入mysql数据库
- 第二篇:opencv纠错,R6010-abort() has been called
- C++ 11新特性:移动构造函数和移动赋值操作符
- 跑步
- display:flex 多栏多列布局