您的位置:首页 > 其它

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 
⌊
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: