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;
}
}

这篇博客介绍了如何使用双指针优化算法,避免使用哈希表来找到数组中的幸运数。首先对数组进行排序,然后通过两个指针从后向前遍历,检查元素是否等于其出现的次数,当找到符合条件的幸运数时返回其出现的次数。如果遍历结束未找到,则返回-1。这种方法提高了算法的效率,减少了内存使用。
276

被折叠的 条评论
为什么被折叠?



