LeetCode Majority Element
来源:互联网 发布:人工智能涨停 编辑:程序博客网 时间:2024/06/09 14:30
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.
题意:输出数组中出现次数大于n/2的数
思路:主要用java中的map
代码如下:
class Solution { public int majorityElement(int[] nums) { Map<Integer, Integer> hm = new HashMap<Integer, Integer>(); int len = nums.length; for (int i = 0; i < len; i++) { if (hm.containsKey(nums[i])) { int val = hm.get(nums[i]); hm.put(nums[i], val + 1); } else { hm.put(nums[i], 1); } } int res = 0; for (Map.Entry<Integer, Integer> v : hm.entrySet()) { if (v.getValue() > len / 2) { res = v.getKey(); } } return res; }}
多数投票算法,用一个变量cand表示当前候选者,另一个变量count表示计数(初始化为0),如果count=0,则count=1,cand = nums[i],否则如果nums[i] =cand,count++,否则count--
代码如下
public class Solution { public int majorityElement(int[] nums) { int count = 0; int cand = -1; int len = nums.length; for (int i = 0; i < len; i++) { if (count == 0) { count = 1; cand = nums[i]; continue; } if (cand == nums[i]) count++; else count--; } return cand; }}
0 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
- yii1.1.14
- getline的bug
- 数论中若干定理
- Docker在Ubuntu的部署实践
- UC/OS II 任务管理(4)之任务创建
- LeetCode Majority Element
- poj 3155 Hard Life 【最大密度子图】 【0-1分数规划 + 最小割】
- Attribute Unavailable: First baseline layout attribute on iOS versions prior to 8.0
- 计算机网络学习笔记
- 一行代码实现呼出热键
- pat测试1015 德才论。运行超时 标库耗时过大,用cstdio
- 防御机制
- 写在工作两个月的感悟
- Error generating final archive: Debug Certificate expired on