/**
* 自己的代码1
* 不排序,遍历两次,Runtime: 3 ms
*/
class Solution {
public int findLucky(int[] arr) {
int res = -1;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i : arr)
map.put(i, map.getOrDefault(i, 0) + 1);
for (int i : map.keySet())
if (i == map.get(i) && i > res)
res = i;
return res;
}
}
/**
* 自己的代码2
* 先排序,从大到小找,一旦找到就是最大的,能直接return
* Runtime: 1 ms, faster than 98.49%
* Memory Usage: 38.5 MB, less than 77.77%
*/
class Solution {
public int findLucky(int[] arr) {
Arrays.sort(arr);
for (int i = arr.length - 1; i >= 0; i--) {
int cnt = 1;
while (i > 0 && arr[i] == arr[i - 1]) {
i--;
cnt++;
}
if (cnt == arr[i]) // 从大到小找,找到的第一个符合条件的就是最大的lucky number
return cnt;
}
return -1; // 到这里才return,则没有找到符合条件的,直接返回-1
}
}
/**
* Discuss里的投机办法,因为题目说了arr.length<=500
* Runtime: 1 ms, faster than 98.49%
* Memory Usage: 38.8 MB, less than 28.07%
*/
class Solution {
public int findLucky(int[] arr) {
int[] map = new int[501];
for (int i : arr)
map[i]++;
for (int i = 500; i > 0; i--)
if (map[i] == i)
return i;
return -1;
}
}