Given an integer array arr
, please help to count the occurrences of each number in the array.
Return true
if the occurrences of each number are unique, otherwise return false
.
Use a hash table to record the occurrences of each number, then use a Set
to handle the occurrences, and finally compare the length of the hash table with the length of the Set
. First, define a hash table, in this case, we use a regular object in JavaScript, but Map
object in Js
can also be used as a key-value hash table solution. After that, iterate through the array, if the key is undefined, set the value of this key in the hash table to 1
, otherwise increment the value. Then get all the keys and values from the object, use a Set
to deduplicate the values array, and then compare the length of the deduplicated array with the length of the keys array, and return the result.