Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/2150.html
2150. Find All Lonely Numbers in the Array (Medium)
You are given an integer array nums
. A number x
is lonely when it appears only once, and no adjacent numbers (i.e. x + 1
and x  1)
appear in the array.
Return all lonely numbers in nums
. You may return the answer in any order.
Example 1:
Input: nums = [10,6,5,8] Output: [10,8] Explanation:  10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.  8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.  5 is not a lonely number since 6 appears in nums and vice versa. Hence, the lonely numbers in nums are [10, 8]. Note that [8, 10] may also be returned.
Example 2:
Input: nums = [1,3,5,3] Output: [1,5] Explanation:  1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.  5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.  3 is not a lonely number since it appears twice. Hence, the lonely numbers in nums are [1, 5]. Note that [5, 1] may also be returned.
Constraints:
1 <= nums.length <= 10^{5}
0 <= nums[i] <= 10^{6}
Similar Questions:
Solution 1. Hash Map

// OJ: https://leetcode.com/problems/findalllonelynumbersinthearray/ // Time: O(N) // Space: O(U) where U is the number of unique elements in `A` class Solution { public: vector<int> findLonely(vector<int>& A) { unordered_map<int, int> m; for (int n : A) m[n]++; vector<int> ans; for (int n : A) { if (m[n] == 1 && m.count(n + 1) == 0 && m.count(n  1) == 0) { ans.push_back(n); } } return ans; } };

// Todo

class Solution: def findLonely(self, nums: List[int]) > List[int]: counter = Counter(nums) ans = [] for num, cnt in counter.items(): if cnt == 1 and counter[num  1] == 0 and counter[num + 1] == 0: ans.append(num) return ans ############ # 2150. Find All Lonely Numbers in the Array # https://leetcode.com/problems/findalllonelynumbersinthearray/ class Solution: def findLonely(self, nums: List[int]) > List[int]: counter = Counter(nums) res = [] for x in counter.keys(): if counter[x] == 1 and x  1 not in counter and x + 1 not in counter: res.append(x) return res
Discuss
https://leetcode.com/problems/findalllonelynumbersinthearray/discuss/1711230/C%2B%2BHashMapO(N)