majority-element-ii 主元素II

给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。

majority-element-ii

样例

例1:

输入: [99,2,99,2,99,3,3], 
输出: 99.

例2:

输入: [1, 2, 1, 2, 1, 3, 3], 
输出: 1.
思路1
使用 map 存储每个元素的个数
遍历 map 如果个数大于1/3 返回key 即可

思路2摩尔投票法

在任何数组中,出现次数大于该数组长度 1/3 的值只能有一个。
遍历数组找出出现次数最多的哪两个数,然后在遍历数组算出个数
最后比较个数,返回个数大的元素值

public class Solution {
    /*
     * @param nums: a list of integers
     * @return: The majority number that occurs more than 1/3
     */
    public int majorityNumber(List<Integer> nums) {
        // write your code here
        Map<Integer, Double> map = new HashMap<>();
        for (Integer num : nums) {
            map.put(num, map.getOrDefault(num, 0.0) + 1);
        }
        for (Integer key : map.keySet()) {
            if (map.get(key) / nums.size() > 1.0 / 3) {
                return key;
            }
        }
        return -1;
    }
}


public class Solution {
   
    /**
     * @param nums: A list of integers
     * @return: The majority number that occurs more than 1/3
     */
    public int majorityNumber(List<Integer> nums) {
        // write your code
        if (nums == null || nums.size() == 0) {
            return -1;
        }

        int num1 = 0;
        int num2 = 0;
        int count1 = 0;
        int count2 = 0;
        for (Integer num : nums) {

            if (count1 == 0) {
                num1 = num;
                count1++;
            } else if (num1 == num) {
                count1++;
            } else if (count2 == 0) {
                num2 = num;
                count2++;
            } else if (num2 == num) {
                count2++;
            } else {
                count1--;
                count2--;
            }
        }

        count1 = 0;
        count2 = 0;
        for (Integer num : nums) {
            if (num == num1) {
                count1++;
            }
            if (num == num2) {
                count2++;
            }
        }

        return count1 > count2 ? num1 : num2;

    }
}

GitHub https://github.com/xingfu0809/Java-LintCode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值