leetcode刷题(15)——169.多数元素

一、题目

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:
输入: [3,2,3]
输出: 3

示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2

二、思路即代码实现

方法一:利用哈希表

利用哈希表统计数组中各元素出现的次数,键存储数组元素,值存储该元素出现的次数。最后返回出现次数大于 n / 2 的值对应的键。

代码如下:

class Solution {
    public int majorityElement(int[] nums) {
        int mElement = 0;
        Map<Integer, Integer> countMap = new HashMap<>();
        for(Integer n : nums){
            if(countMap.containsKey(n)){
                countMap.put(n, countMap.get(n) + 1);
            }else{
                countMap.put(n, 1);
            }
        }
        for(Integer key : countMap.keySet()){
            if(countMap.get(key) > nums.length / 2){
                mElement = key;
            }
        }
        return mElement;
    }
}

方法二:排序

多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

也就是说,数组中有超过一半的元素是多数元素,那么,对数组进行排序后,数组中间的位置(即 n / 2 处)一定是多数元素。

注意: 看清题目中对多数元素的定义(写给自己)。

代码如下:

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}
发布了56 篇原创文章 · 获赞 0 · 访问量 922

猜你喜欢

转载自blog.csdn.net/weixin_45594025/article/details/105017453