1207. Unique Number of Occurrences
leetcode easy
#array#csharp#easy#hash-table#leetcode
Task
Дан массив целых чисел arr. Верните true, если количество вхождений каждого значения в массиве уникально, или false в противном случае.
Пример:
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.
C# solution
matched/originalusing System;
using System.Collections.Generic;
public class Solution {
public bool UniqueOccurrences(int[] arr) {
Dictionary<int, int> freq = new Dictionary<int, int>();
foreach (int num in arr) {
if (freq.ContainsKey(num)) {
freq[num]++;
} else {
freq[num] = 1;
}
}
HashSet<int> freqSet = new HashSet<int>(freq.Values);
return freq.Count == freqSet.Count;
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool UniqueOccurrences(vector<int>& arr) {
unordered_map<int, int> freq = new unordered_map<int, int>();
foreach (int num in arr) {
if (freq.count(num)) {
freq[num]++;
} else {
freq[num] = 1;
}
}
HashSet<int> freqSet = new HashSet<int>(freq.Values);
return freq.size() == freqSet.size();
}
}Java solution
matched/originalclass Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
Set<Integer> freqSet = new HashSet<>(freq.values());
return freq.size() == freqSet.size();
}
}JavaScript solution
matched/originalvar uniqueOccurrences = function(arr) {
let freq = new Map();
for (let num of arr) {
freq.set(num, (freq.get(num) || 0) + 1);
}
let freqSet = new Set(freq.values());
return freq.size === freqSet.size;
};Python solution
matched/originalclass Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
return len(freq) == len(set(freq.values()))Go solution
matched/originalfunc uniqueOccurrences(arr []int) bool {
freq := make(map[int]int)
for _, num := range arr {
freq[num]++
}
freqSet := make(map[int]struct{})
for _, count := range freq {
freqSet[count] = struct{}{}
}
return len(freq) == len(freqSet)
}Explanation
Algorithm
1⃣Сохраните частоты элементов массива arr в хэш-таблице freq.
2⃣Итерируйтесь по хэш-таблице freq и вставьте частоты всех уникальных элементов массива arr в хэш-набор freqSet.
3⃣Верните true, если размер хэш-набора freqSet равен размеру хэш-таблицы freq, иначе верните false.
😎