• ✡ 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;
    }
  • 相关阅读:
    班课6
    lesson one
    班课5
    ES6之Proxy及Proxy内置方法
    ES6模板字符串
    ES6之Symbol
    ES6对象及ES6对象简单拓展
    ES6函数的拓展
    ES6数组及数组方法
    ES6字符串方法
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6118135.html
Copyright © 2020-2023  润新知