Preface explains

Algorithm learning, daily brush record.

Subject to connect

Unique number of occurrences

The subject content

Give you an integer array arr, ask you to help count the occurrence of each number in the array.

Returns true if each occurrence is unique; Otherwise return false.

Example 1:

Input: arr = [1,2,2,1,1,3]

Output: true,

Explanation: In this array, 1 occurs three times, 2 occurs twice, and 3 occurs only once. No two numbers occur the same number of times.

Example 2:

Input: arr = [1,2]

Output: false

Example 3:

Input: arr = [-3,0,1,-3,1,1, -3,10,0]

Output: true,

Tip:

1 <= arr.length <= 1000 -1000 <= arr[i] <= 1000

The analysis process

Define a set map, traverse array ARR once, use the key value of the set map will not repeat the feature to count the number of elements, the number of each element is saved in the set map.

Define a list, list, that holds the number of occurrences of elements in the collection map.

Iterate through the set map to obtain the number of occurrences of each element, and use the contains method of the list list to determine whether the number of occurrences of the following element is equal to the number of occurrences of the preceding element.

If the number of occurrences of the current element is not equal to the number of occurrences of other elements, the number of occurrences of the element is saved to the list list.

If the number of occurrences of one element is equal to the number of occurrences of other elements, then the number of occurrences of the element is not unique, and returns false.

If the map set is traversed, no element is proved to have the same number of occurrences, and the number is unique, and returns true.

To solve the code

Class Solution {public Boolean Occurrences(int[] arr) {class Solution {public Boolean occurrences (int[] arr) {class Solution {public Boolean occurrences (int[] arr) {class Solution {public Boolean occurrences (int[] arr) {new HashMap<>(); Arr for (int e: arr) {if (map.containsKey(e)) {int count = map.get(e); map.put(e, ++count); } else {// If there are no array elements in the set map, advance the set map, element occurrence is 1 map.put(e, 1); List<Integer> list = new ArrayList<>(); Entry<Integer, Integer> Entry: map.entryset ()) {int value = entry.getValue(); If (list. Contains (value)) {// If (list. Contains (value)) {return false; } else {// If the element does not appear as many times as other elements, advance the list list. Add (value); }} return true; }}Copy the code

Submit the results

It took 2ms to execute, beating 90.97% of users in time, 36.5MB in memory consumption, and beating 35.67% of users in space.

The original link

Original link: unique number of occurrences