|
| 1 | +## 1207. 独一无二的出现次数 |
| 2 | +> https://leetcode-cn.com/problems/unique-number-of-occurrences/ |
| 3 | +
|
| 4 | + |
| 5 | +### Java |
| 6 | +```java |
| 7 | +/* |
| 8 | + * @Author: Goog Tech |
| 9 | + * @Date: 2020-08-16 10:23:22 |
| 10 | + * @LastEditTime: 2020-08-16 10:38:07 |
| 11 | + * @Description: https://leetcode-cn.com/problems/unique-number-of-occurrences/ |
| 12 | + * @FilePath: \leetcode-googtech\#102. Binary Tree Level Order Traversal\1207.独一无二的出现次数.java |
| 13 | + * @WebSite: https://algorithm.show/ |
| 14 | + */ |
| 15 | + |
| 16 | +/* |
| 17 | + * @lc app=leetcode.cn id=1207 lang=java |
| 18 | + * |
| 19 | + * [1207] 独一无二的出现次数 |
| 20 | + */ |
| 21 | + |
| 22 | +// @lc code=start |
| 23 | +class Solution { |
| 24 | + public boolean uniqueOccurrences(int[] arr) { |
| 25 | + // 使用 Map 集合记录每个数值及其出现的次数 |
| 26 | + Map<Integer, Integer> countMap = new HashMap<>(); |
| 27 | + // 记录每个数字出现的次数,数值作为键,其出现的次数作为值 |
| 28 | + for(int num : arr) { |
| 29 | + // getDefault: 不存在则返回0,否则返回键num对应的值并加一 |
| 30 | + countMap.put(num, countMap.getOrDefault(num, 0) + 1); |
| 31 | + } |
| 32 | + // 使用 Set 集合判断 Map 中键所对应的值是否右重复 |
| 33 | + Set<Integer> set = new HashSet<>(); |
| 34 | + // 判断value是否有重复值 |
| 35 | + for(Integer value : countMap.values()) { |
| 36 | + // 若value值已存在,add方法则会返回false |
| 37 | + if(!set.add(value)) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + } |
| 41 | + return true; |
| 42 | + } |
| 43 | +} |
| 44 | +// @lc code=end |
| 45 | +``` |
| 46 | + |
| 47 | +### Python |
| 48 | +```python |
| 49 | +''' |
| 50 | +Author: Goog Tech |
| 51 | +Date: 2020-08-16 10:33:02 |
| 52 | +LastEditTime: 2020-08-16 10:38:35 |
| 53 | +Description: https://leetcode-cn.com/problems/unique-number-of-occurrences/ |
| 54 | +FilePath: \leetcode-googtech\#102. Binary Tree Level Order Traversal\1207.独一无二的出现次数.py |
| 55 | +WebSite: https://algorithm.show/ |
| 56 | +''' |
| 57 | + |
| 58 | +# |
| 59 | +# @lc app=leetcode.cn id=1207 lang=python |
| 60 | +# |
| 61 | +# [1207] 独一无二的出现次数 |
| 62 | +# |
| 63 | + |
| 64 | +# @lc code=start |
| 65 | +class Solution(object): |
| 66 | + def uniqueOccurrences(self, arr): |
| 67 | + """ |
| 68 | + :type arr: List[int] |
| 69 | + :rtype: bool |
| 70 | + """ |
| 71 | + # 统计每个数值出现的次数 |
| 72 | + eleCounts = collections.Counter(arr) |
| 73 | + # 将统计结果去重,然后与原统计结果相比较 |
| 74 | + return len(set(eleCounts.values())) == len(eleCounts) |
| 75 | + |
| 76 | +# @lc code=end |
| 77 | +``` |
0 commit comments