[LeetCode] Find All Lonely Numbers in the Array

2150. Find All Lonely Numbers in the Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> findLonely(vector<int>& nums) {
unordered_map<int, int> freq;
for(auto& n : nums) freq[n]++;
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
if(freq[nums[i]] > 1) continue;
if(freq.count(nums[i] - 1)) continue;
if(freq.count(nums[i] + 1)) continue;
res.push_back(nums[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/29/PS/LeetCode/find-all-lonely-numbers-in-the-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.