Find All Lonely Numbers in the Array

medium hash map counting

Problem

You are given an integer array nums. A number x is lonely when it appears exactly once in the array and neither x − 1 nor x + 1 is present anywhere in the array. Return all lonely numbers in any order.

Inputnums = [10, 6, 5, 8]
Output[10, 8]
10 appears once and has no 9 or 11, so it is lonely. 8 appears once and has no 7 or 9, so it is lonely. 5 and 6 are neighbors of each other, so neither is lonely.

def find_lonely(nums):
    count = {}
    for x in nums:
        count[x] = count.get(x, 0) + 1
    ans = []
    for x in nums:
        if count[x] == 1 and (x - 1) not in count and (x + 1) not in count:
            ans.append(x)
    return ans
function findLonely(nums) {
  const count = new Map();
  for (const x of nums) count.set(x, (count.get(x) || 0) + 1);
  const ans = [];
  for (const x of nums) {
    if (count.get(x) === 1 && !count.has(x - 1) && !count.has(x + 1)) ans.push(x);
  }
  return ans;
}
class Solution {
    public int[] findLonely(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int x : nums) count.put(x, count.getOrDefault(x, 0) + 1);
        List<Integer> ans = new ArrayList<>();
        for (int x : nums) {
            if (count.get(x) == 1 && !count.containsKey(x - 1) && !count.containsKey(x + 1)) ans.add(x);
        }
        return ans.stream().mapToInt(Integer::intValue).toArray();
    }
}
vector<int> findLonely(vector<int>& nums) {
    unordered_map<int, int> count;
    for (int x : nums) count[x]++;
    vector<int> ans;
    for (int x : nums) {
        if (count[x] == 1 && !count.count(x - 1) && !count.count(x + 1)) ans.push_back(x);
    }
    return ans;
}
Time: O(n) Space: O(n)