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
原创粉丝点击