Logo

Kode$word

Single Number III

Single Number III

LeetCode Question 260

17 views
0
0

LeetCode Problem 260

Link of the Problem to try -: Link


Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

Example 1:

Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.

Example 2:

Input: nums = [-1,0]
Output: [-1,0]

Example 3:

Input: nums = [0,1]
Output: [1,0]

Constraints:

  1. 2 <= nums.length <= 3 * 104
  2. -231 <= nums[i] <= 231 - 1
  3. Each integer in nums will appear twice, only two integers will appear once.


Solution:

It is a very easy question if we only know about HashMap because it is clearly telling us about to create frequency and to return that number whose frequency is exactly 1 so that's why in this question not a very different or bug thing is there that we have to think about very much.


Code:

HashMap<Integer,Integer> mp = new HashMap<>();
int ans[] =new int[2];
for(int i=0;i<nums.length;i++){
mp.put(nums[i],mp.getOrDefault(nums[i],0)+1);
}

int co =0;
for(int a:mp.keySet()){
if(mp.get(a) == 1){
ans[co] = a;
co++;
}
}

return ans;