力扣:1394. 找出数组中的幸运数

这篇博客介绍了如何使用双指针优化算法,避免使用哈希表来找到数组中的幸运数。首先对数组进行排序,然后通过两个指针从后向前遍历,检查元素是否等于其出现的次数,当找到符合条件的幸运数时返回其出现的次数。如果遍历结束未找到,则返回-1。这种方法提高了算法的效率,减少了内存使用。
class Solution {
    public int findLucky(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : arr) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        int res = -1;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getKey().equals(entry.getValue())){
                res = Math.max(res, entry.getValue());
            }
        }
        return res;
    }
}

优化,不使用hash表,使用双指针

class Solution {
    public int findLucky(int[] arr) {
        Arrays.sort(arr);
        int index = arr.length - 1;
        while (index >= 0){
            int temp = arr[index];
            int count = 0;
            while (index >= 0 && arr[index] == temp){
                index--;
                count++;
            }
            if (temp == count){
                return count;
            }
        }
        return -1;
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值