LeetCode21|主要元素

时间:2022-07-23
本文章向大家介绍LeetCode21|主要元素,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

数组中占比超过一半的元素称之为主要元素。

给定一个整数数组,找到它的主要元素。

若没有,返回-1。

2,示例

输入:[1,2,5,9,5,9,5,5,5]
输出:5

3,题解思路

键值对集合HashMap的使用

4,题解程序

 
import java.util.HashMap;
import java.util.Map;

public class MajorityElementTest {
    public static void main(String[] args) {
        int[] array = {1, 2, 5, 9, 5, 9, 5, 5, 5};
        int majorityElement = majorityElement(array);
        System.out.println("majorityElement = " + majorityElement);
    }

    public static int majorityElement(int[] nums) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int length = nums.length;
        HashMap<Integer, Integer> hashMap = new HashMap<>(length);
        for (Integer num : nums
        ) {
            if (hashMap.containsKey(num)) {
                hashMap.put(num, hashMap.get(num) + 1);
            } else {
                hashMap.put(num, 1);
            }
        }
        return hashMap.entrySet().stream().filter(entry -> entry.getValue() > length / 2).findFirst().map(Map.Entry::getKey).orElse(-1);
    }
}

5,总结

这道题采用键值对集合的进行解决还是很常见的一种思路,算法题一直是自己喜欢的题,但是上学的时候自己javaAPI都不是很熟悉的我自然而然不会做这样的题,现在看现在的博客账号都开通好几年了,但是文章却一直没有发过,一直在吸收技术的路上,没有时间去输出,自从去年10月份时觉得有必要输出一些自己的东西了,才慢慢做到了今天,写这类题主要是为了磨平曾经自己缺少的技术,毕竟会总比不会要好一些,但是作用不是很大,主要看自己是否喜欢来了