#day31
In our continued use to beat coding issues, we’ve lined one more enjoyable subject on LeetCode: “Single Quantity II.” Not like its prior model, this query features a twist by requiring every merchandise within the array to look 3 times, aside from one distinctive merchandise.
Whereas earlier “Single Quantity” issues required us to establish the distinctive ingredient amongst duplicates, “Single Quantity II” prompted the expectations. As a substitute of showing twice, objects now seem 3 times, complicating the identification of a single ingredient.
Resolution Method
To repair this drawback, we are able to nonetheless use hashmaps. Nevertheless, now we have to change our method to suit the brand new limits. Right here’s how we are able to obtain it:
def singlenumber2(nums):
dictionary={}for i in nums:
if i not in dictionary:
dictionary[i]=1
else:
if dictionary[i]==1:
dictionary[i]+=1
else:
del dictionary[i]
return checklist(dictionary.keys())[0]
- Initialization: Begin with an empty dictionary to retailer the depend of every quantity.
- Iteration: For every quantity within the array:
- If the quantity just isn’t within the dictionary, add it with a depend of 1.
- If the quantity is already within the dictionary:
- If its depend is 1, improve the depend to 2.
- If its depend is already 2, take away it from the dictionary.
3. Consequence: After processing all numbers, the dictionary will comprise just one key, which is the distinctive quantity.