[LeetCode]Majority Element
来源:互联网 发布:意大利 世界杯 知乎 编辑:程序博客网 时间:2024/06/06 16:55
题意: 找出一个数组中的主要元素,主要元素为出现次数大于[n/2]的元, 当然最笨的方法就是暴力,没式不知道时间行不行
思路1: 遍历数组,统计每个元素出现的次数,用HashMap统计每个元素出现的次数 时间复杂度O(N),空间复杂度 O(N)
代码1:
public class Solution { public int majorityElement(int[] num) { int majority = 0, currCount; int major = (int) Math.floor( num.length*1.0 / 2 ); if(num.length == 1) return num[0]; Map<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i = 0; i< num.length; ++i){ if(m.containsKey(num[i])){ currCount = m.get(num[i]) + 1; if(currCount > major) return num[i]; m.put(num[i], currCount); }else m.put(num[i],1); } return majority; }}
思路2:直接排序,然后找到中间的那个数就可以了,时间复杂度 O(N*log(N))
代码2:
public int majorityElement(int[] num) {//排序 int majority = 0, currCount; int major = (int) Math.floor( num.length*1.0 / 2 ); if(num.length == 1) return num[0]; Arrays.sort(num); return num[num.length/2]; }
代码3:
public int majorityElement(int[] num) {//摩尔投票算法 int majority = 0, currCounter = 0, candidate = 0; int minCounter = (int) Math.floor( num.length*1.0 / 2 ); if(num.length == 1) return num[0]; for(int i = 0; i < num.length; ++i){ if(currCounter == 0){ candidate = num[i]; currCounter ++; }else { if(candidate == num[i]){ currCounter ++; } else currCounter --; } if(currCounter > minCounter)return candidate; } return candidate; }
还有一种官方的解法:时间复杂度: O(n) — 位操作法: 我们需要32次迭代, 每一次计算所有n个数的第i位的1的个数。由于众数一定存在,那么或者1的个数 > 0的个数 或者反过来(但绝不会相同)。 众数的第i位一定是计数较多数字。
1 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- 买水果
- How to Re-Run the OS X Setup Assistant
- Java_socket程序学习06-彩票销售-第一阶段+3d+lot销售
- ListView混搭ProgressBar最佳更新方式
- 蓝桥杯 花朵数
- [LeetCode]Majority Element
- 欢迎使用CSDN-markdown编辑器
- Poj 2096 Collecting Bugs(概率(期望)+dp)
- JAVA学习笔记(五十八)- InetAddress类与URL
- Vivado实现纯逻辑开发——从最简单的开始
- 智能家居需求分析
- 在Linux主机上搭建SVN,用于同步提交修改,实现本地提交线上预览
- 新浪微博note
- Path Sum II--LeetCode