zoukankan      html  css  js  c++  java
  • ✡ leetcode 169. Majority Element 求出现次数最多的数 --------- java

    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.

    给定一个数组,求其中权制最大的元素,(该元素出现超过了一半次数)。

    直观想法,HashMap,很慢

    public class Solution {
        public int majorityElement(int[] nums) {
            Map map = new HashMap<Integer, Integer>();
            int len = nums.length;
            if (len == 1){
                return nums[0];
            }
            for (int num : nums){
                if (map.containsKey(num)){
                    int count = (int) map.get(num);
                    if ((count + 1) > len / 2){
                        return num;
                    } else {
                        map.put(num, count + 1);
                    }
                } else {
                    map.put(num, 1);
                }
            }
            return -1;
        }
    }

    discuss上面看到了这道题非常完善的总结:

    1、排序sort

    public int majorityElement1(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }

    2、HashMap

    3、Moore’s voting algorithm(最佳算法)

    很巧妙,时间O(n)  ,空间O(1),就是记录当前元素以及当前元素的“胜出”数量(比其他元素多几个)。

    public int majorityElement3(int[] nums) {
        int count=0, ret = 0;
        for (int num: nums) {
            if (count==0)
                ret = num;
            if (num!=ret)
                count--;
            else
                count++;
        }
        return ret;
    }

     

    4、位运算  Bit manipulation 

    通过记录每一位上的数字来得出的结果,相比之下,还是第三种算法更好。

    public int majorityElement(int[] nums) {
        int[] bit = new int[32];
        for (int num: nums)
            for (int i=0; i<32; i++) 
                if ((num>>(31-i) & 1) == 1)
                    bit[i]++;
        int ret=0;
        for (int i=0; i<32; i++) {
            bit[i]=bit[i]>nums.length/2?1:0;
            ret += bit[i]*(1<<(31-i));
        }
        return ret;
    }
  • 相关阅读:
    大学生自学网
    如何保证主从复制数据一致性
    CDN
    后端 线上 服务监控 与 报警 方案2
    利用 Gearman 实现系统错误报警功能
    增量部署和全量部署
    后端线上服务监控与报警方案
    简析TCP的三次握手与四次分手
    301 和 302 对 SEO 的影响
    Linux 查看负载
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6118135.html
Copyright © 2011-2022 走看看