LeetCode-in-Java

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:

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:

Hence, the lonely numbers in nums are [1, 5].

Note that [5, 1] may also be returned.

Constraints:

Solution

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Solution {
    public List<Integer> findLonely(int[] nums) {
        List<Integer> ans = new ArrayList<>();
        HashMap<Integer, Integer> m = new HashMap<>();
        for (int i : nums) {
            m.put(i, m.getOrDefault(i, 0) + 1);
        }
        for (int i : nums) {
            if (m.get(i) == 1 && !m.containsKey(i - 1) && !m.containsKey(i + 1)) {
                ans.add(i);
            }
        }
        return ans;
    }
}