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;
    }
  • 相关阅读:
    java:第三章
    java:第一章
    java:第二章
    复制a.jpg到b.jpg
    安卓事件大全
    安卓事件
    read输入流与writer输出流的对比
    第五章:循环结构
    第三章:选择结构(一)
    第二章:变量,数据类型和运算符
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6118135.html
Copyright © 2011-2022 走看看