LeetCode Majority Element
2015-09-05 12:26
323 查看
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.
题意:输出数组中出现次数大于n/2的数
思路:主要用java中的map
代码如下:
多数投票算法,用一个变量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;
}
}
⌊ 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;
}
}
相关文章推荐
- pat测试1015 德才论。运行超时 标库耗时过大,用cstdio
- 计算机网络学习笔记
- 系统虚拟内存的理解 转载自http://blog.csdn.net/do2jiang/article/details/4690967
- 挑战自我
- Docker在Ubuntu的部署实践
- C++ 打印输出指针
- 修改通过myeclipse启动的tomcat的VM参数
- [LeetCode] Paint Fence
- UC/OS II 任务管理(3)之初始化
- getline的bug
- 数论中若干定理
- 先用C#编程,再有C++优化
- dom4j 创建,解析xml
- 用PS求图片中面积
- Vim移动命令
- java bufferedreader 与inputstream的区别
- 【读书笔记】20150905Java编程那些事儿
- 倍数提高工作效率的Android Studio奇技
- gdb崩溃定位
- 小猴子下落(二叉树)