1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public List<Integer> findLonely(int[] nums) { List<Integer> resultList = new ArrayList<>();
Map<Integer, Integer> numToCountMap = new HashMap<>(); for (int num : nums) { numToCountMap.put(num, numToCountMap.getOrDefault(num, 0) + 1); }
for (Map.Entry<Integer, Integer> entry : numToCountMap.entrySet()) { int num = entry.getKey(); int count = entry.getValue(); if (count == 1 && !numToCountMap.containsKey(num - 1) && !numToCountMap.containsKey(num + 1)) { resultList.add(num); } }
return resultList; } }
|
References
2150. Find All Lonely Numbers in the Array