zoukankan      html  css  js  c++  java
  • 每日一练leetcode

    找出数组中的幸运数

    在整数数组中,如果一个整数的出现频次和它的数值大小相等,我们就称这个整数为「幸运数」。

    给你一个整数数组 arr,请你从中找出并返回一个幸运数。

    如果数组中存在多个幸运数,只需返回 最大 的那个。
    如果数组中不含幸运数,则返回 -1 。
     

     解法:HahsMap

    将数组中的数存储完整,然后遍历map表

    class Solution {
        public int findLucky(int[] arr) {
            if(arr.length == 0){
                return -1;
            }
            Map<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int i : arr){
                map.put(i,map.getOrDefault(i,0)+1);
            }
            int ans = -1;
            for(Map.Entry<Integer,Integer> entry:map.entrySet()){
                int key = entry.getKey();
                int value = entry.getValue();
                if(key == value){
                    ans = Math.max(ans, key);
                }
            }
            return ans;
    
        }
    }
    

      此题中有两个值得注意的点:

    1)map.getOrDefault(i,0)此函数要不的到i的值即get(i),要不返回0

    2)for(Map.Entry<Integer,Integer> entry:map.entrySet());此方法为遍历map的一种形式<key,vaule>遍历

    3)entry.getKey();entry.getValue()

  • 相关阅读:
    mmap和MappedByteBuffer
    Linux命令之TOP
    Linux命令之ss
    MySql Cluster
    HttpClient配置
    注释驱动的 Spring cache 缓存介绍
    Spring AOP 实现原理与 CGLIB 应用
    AspectJ本质剖析
    B树
    imagick-3.1.0RC2 安装错误
  • 原文地址:https://www.cnblogs.com/nenu/p/15246463.html
Copyright © 2011-2022 走看看