Re: [閒聊] 每日LeetCode已回收
1207. Unique Number of Occurrences
給予一個整數陣列,若該整數的每個數字出現次數都不重複返回true,否則false。
Example:
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.
Input: arr = [1,2]
Output: false
思路:
1.用HashMap統計每個數字的出現次數
2.用Set檢查出現次數是否重複
JavaCode:
----------------------------------------
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : arr) {
map.put(n, map.getOrDefault(n, 0) + 1 );
}
Set<Integer> set = new HashSet<>();
for (int frequency : map.values()) {
if (set.contains(frequency)) {
return false;
}
set.add(frequency);
}
return true;
}
}
----------------------------------------
--
https://i.imgur.com/CBMFmWk.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.231.9.105 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1669771228.A.49D.html
→
11/30 14:05,
3年前
, 1F
11/30 14:05, 1F
討論串 (同標題文章)
完整討論串 (本文為第 122 之 719 篇):