Using HashMap
Intuition\n Describe your first thoughts on how to solve this problem. \nThe given code aims to find all the "lonely" numbers in the given integer array nums. A
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code aims to find all the "lonely" numbers in the given integer array nums. A number is considered lonely if it appears only once in the array and neither of its adjacent numbers (i.e., x + 1 and x - 1) is present in the array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet and Map Initialization:\n\nInitialize an empty HashSet named set to store unique elements from the input array.\nInitialize an empty HashMap named map to count the occurrences of each number in the array.\nCount Occurrences:\n\nIterate through the input array nums and populate the set with unique elements and the map with counts of each element.\nFind Lonely Numbers:\n\nIterate through the map entries and check if the count of a number is equal to 1.\nFor each number with a count of 1, check if it is lonely by verifying that neither x + 1 nor x - 1 is present in the set. If it is lonely, add it to the result list.\nReturn Result:\n\nReturn the list of lonely numbers.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\n    public List<Integer> findLonely(int[] nums) {\n        List<Integer> res=new ArrayList<>();\n        Set<Integer> set=new HashSet<>();\n        for(int i:nums){\n            set.add(i);\n        }\n        Map<Integer,Integer> map=new HashMap<>();\n        for(int i:nums){\n            map.put(i,map.getOrDefault(i,0)+1);\n        }\n        for(Map.Entry<Integer,Integer> entry:map.entrySet()){\n            if(entry.getValue()==1){\n                if(check(entry.getKey(),set)){\n                    res.add(entry.getKey());\n                }\n            }\n        }\n        return res;\n    }\n    public boolean check(int n,Set<Integer> set){\n        return (!set.contains(n+1) && !set.contains(n-1));\n    }\n}\n```
['Java']