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.
Input: nums =[10,6,5,8]Output: [10,8]Explanation:
-10is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.-8is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.-5is 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.
Input: nums =[1,3,5,3]Output: [1,5]Explanation:
-1is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.-5is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.-3is 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.
We count the frequency of each number in the array. A number is lonely if it appears exactly once and neither its immediate neighbors (x-1, x+1) appear in the array.
classSolution {
public List<Integer>findLonely(int[] nums) {
Map<Integer, Integer> cnt =new HashMap<>();
for (int x : nums) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
List<Integer> ans =new ArrayList<>();
for (int x : cnt.keySet()) {
if (cnt.get(x) == 1 &&!cnt.containsKey(x-1) &&!cnt.containsKey(x+1)) ans.add(x);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funfindLonely(nums: IntArray): List<Int> {
val cnt = mutableMapOf<Int, Int>()
for (x in nums) cnt[x] = cnt.getOrDefault(x, 0) + 1val ans = mutableListOf<Int>()
for ((x, c) in cnt) {
if (c ==1&& cnt.getOrDefault(x-1, 0) ==0&& cnt.getOrDefault(x+1, 0) ==0) ans.add(x)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deffindLonely(self, nums: list[int]) -> list[int]:
from collections import Counter
cnt = Counter(nums)
ans = []
for x in cnt:
if cnt[x] ==1and cnt[x-1] ==0and cnt[x+1] ==0:
ans.append(x)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::collections::HashMap;
impl Solution {
pubfnfind_lonely(nums: Vec<i32>) -> Vec<i32> {
letmut cnt = HashMap::new();
for&x in&nums { *cnt.entry(x).or_insert(0) +=1; }
letmut ans =vec![];
for (&x, &c) in&cnt {
if c ==1&&!cnt.contains_key(&(x-1)) &&!cnt.contains_key(&(x+1)) {
ans.push(x);
}
}
ans
}
}