“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
[B] [C] [D]
Given an array of integers, nums, each element appears exactly three times except for one element. Find and return the element that appears only once. Example 1:
Input: nums = [2,2,3,2Copy the code
Example 2:
Input: nums = [0,1,0,1,0,1,100] output: 100Copy the code
Tip:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums
In, except for an element only occursAt a timeOutside, every other element appears exactlyThree times
The answer to this question is as follows:
- We can use a data structure to record the value of each element and the number of occurrences of each element. We can use a data structure to record the number of occurrences of each element
- When an element occurs three times, we remove that element, and all we’re left with in the data structure is the value of the only element that occurs only once and the corresponding number of times
1
The next thing we need to think about is what kind of data structure to store the element value and the corresponding number of times
We could use Object to do this, but we’re going to be adding and deleting key values frequently, so using object is not very efficient
In JavaScript, there is a data structure called Map, which is an instance of Object. However, compared with Object, Map occupies less memory space and has better performance in addition and deletion operations.
The code is as follows:
var singleNumber = function(nums) { const map = new Map(); for(let i = 0; i<nums.length; i++){ if(map.has(nums[i])){ if(map.get(nums[i])===2) map.delete(nums[i]) else map.set(nums[i],2) } else map.set(nums[i],1) } let ret; map.forEach((val,key) => { ret = key; }) return ret; };Copy the code
At this point we are done with leetcode- Finger Offer II 004- a number that appears only once
If you have any questions or suggestions, please leave a comment!