Skip to content

Latest commit

 

History

History
124 lines (99 loc) · 2.55 KB

File metadata and controls

124 lines (99 loc) · 2.55 KB

中文文档

Description

Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.

 

Example 1:

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

Example 2:

Input: arr = [1,2]
Output: false

Example 3:

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

 

Constraints:

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

Solutions

Python3

class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        counter = Counter(arr)
        s = set()
        for num in counter.values():
            if num in s:
                return False
            s.add(num)
        return True

Java

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> counter = new HashMap<>();
        for (int e : arr) {
            counter.put(e, counter.getOrDefault(e, 0) + 1);
        }
        Set<Integer> s = new HashSet<>();
        for (int num : counter.values()) {
            if (s.contains(num)) {
                return false;
            }
            s.add(num);
        }
        return true;
    }
}

C++

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        unordered_map<int, int> counter;
        for (auto e : arr) {
            ++counter[e];
        }
        unordered_set<int> s;
        for (auto e : counter) {
            int num = e.second;
            if (s.count(num)) return false;
            s.insert(num);
        }
        return true;
    }
};

Go

func uniqueOccurrences(arr []int) bool {
	counter := make(map[int]int)
	for _, e := range arr {
		counter[e]++
	}
	s := make(map[int]bool)
	for _, num := range counter {
		if s[num] {
			return false
		}
		s[num] = true
	}
	return true
}

...