Skip to content

2150. Find All Lonely Numbers in the Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<int> findLonely(vector<int>& nums) {
    vector<int> ans;
    unordered_map<int, int> count;

    for (const int num : nums)
      ++count[num];

    for (const auto& [num, freq] : count)
      if (freq == 1 && !count.contains(num - 1) && !count.contains(num + 1))
        ans.push_back(num);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public List<Integer> findLonely(int[] nums) {
    List<Integer> ans = new ArrayList<>();
    Map<Integer, Integer> count = new HashMap<>();

    for (final int num : nums)
      count.merge(num, 1, Integer::sum);

    for (final int num : count.keySet())
      if (count.get(num) == 1 && !count.containsKey(num - 1) && !count.containsKey(num + 1))
        ans.add(num);

    return ans;
  }
}
1
2
3
4
5
6
7
class Solution:
  def findLonely(self, nums: list[int]) -> list[int]:
    count = collections.Counter(nums)
    return [num for num, freq in count.items()
            if freq == 1 and
            count[num - 1] == 0 and
            count[num + 1] == 0]