169. Majority Element

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的元素

方法一

使用哈希方法,这种方法最容易,即记录出每个元素出现的次数


public static int majorityElement(int[] nums) {
        int result = 0;
        Map< Integer, Integer> count = new HashMap<>();
        for(int num:nums)
        {
            if(!count.containsKey(num))
                count.put(num, 1);
            else
                count.put(num, count.get(num) + 1);
            if(count.get(num) > nums.length/2) //这个地方可以单独遍历一边,
                result = num;                    //但由于map中元素都不相同,所以可以直接在for内部
        }
        
        return result;
    }

最初设计算法的时候,得到了计数的map后,我又遍历了map找到其中符合要求的元素,实际上没有必要;

方法二

第二种方法的思路也比较简单,利用的思路是大于n/2 减去其他数字出现的次数>0


    public static int majorityElement(int[] nums) {
        int result = nums[0];
        int count = 1;
        for(int i = 1; i < nums.length; i++)
        {
            if(nums[i] == result)
                count++;
            else 
            {
                count--;
                if(count == 0)
                {
                    result = nums[i];
                    count = 1;
                }
            }
        }
        
        return result;
    }

原文地址:https://www.cnblogs.com/wxshi/p/7680114.html