LeetCode--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.

题目描述:给出一个size为n的数组,找出其中出现次数最多的元素,且该元素出现次数多于⌊ n/2 ⌋次 。

题目中还给定假设数组非空且一定存在一个多数元素。

题目分析:用哈希表为出现过的元素做映射,对应的键值value记录出现的次数,最后遍历哈希表,找出次数最多的元素。

代码如下:

public class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
        for(int i : nums){
            if(!h.containsKey(i)){
                h.put(i, 1);
            }
            else{
                h.put(i, h.get(i)+1);
            }
        }
        
        int max = -1;
        int k = -1;
        for(Map.Entry<Integer, Integer> entry: h.entrySet()){
            if(max<entry.getValue()){
                max = entry.getValue();
                k = entry.getKey();
            }
        }
        return k;
    }
}

 解法二:应为数组中多数元素出现的次数至少为⌊ n/2 ⌋ ,则可以有一个巧妙的方法。每次搜索到有不同元素时,则一次将这一对不同元素删除,则最后剩下的必定是出现次数最多的元素。代码如下:

public class Solution {
    public int majorityElement(int[] nums) {
        int currentnum = 0;
        int count = 0;
        for(int i=0; i<nums.length; i++){
            if(count==0){ //说明至今还未遇到相同元素
                currentnum = nums[i];
                count = 1;
            }
            else{
                if(currentnum==nums[i]) //如果跟当前标记元素相同,则相同个数加1
                    count++;
                else //如果跟当前标记元素不同,则将一对都删除(前一个元素通过count--删除,后一个元素通过i++删除)
                    count--;
            }
        }
        return currentnum;
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4514928.html