第 27 课
- [1748. 唯一元素的和](https://leetcode-cn.com/problems/sum-of-unique-elements/)
- [846. 一手顺子](https://leetcode-cn.com/problems/hand-of-straights/)
- 基础知识
1748. 唯一元素的和
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
d = {}
for x in nums:
d[x] = d.get(x, 0) + 1
return sum(k for k, v in d.items() if v == 1)
class Solution {
public int sumOfUnique(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
int ans = 0;
// for (int x : nums) {
// if (!map.containsKey(x)) {
// ans += x; // 先加上
// map.put(x, 1);
// } else if (map.get(x) == 1) {
// ans -= x; // 多个减一次
// map.put(x, 2);
// }
// }
for (int x : nums)
map.put(x, map.getOrDefault(x, 0) + 1);
// 1、迭代器 EntrySet
// Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
// while (it.hasNext()){
// Map.Entry<Integer, Integer> entry = it.next();
// if (entry.getValue() == 1) ans += entry.getKey();
// }
// 2、迭代器 KeySet
// Iterator<Integer> it = map.keySet().iterator();
// while (it.hasNext()){
// Integer key = it.next();
// if (map.get(key) == 1) ans += key;
// }
// 3、ForEach EntrySet
// for (Map.Entry<Integer, Integer> entry : map.entrySet()){
// if (entry.getValue() == 1) ans += entry.getKey();
// }
// 4、ForEach KeySet
for (Integer key : map.keySet())
if (map.get(key) == 1) ans += key;
// 5、Lambda 不可修改本地变量
// map.forEach((key, value) -> {if (value == 1) ans += key;});
return ans;
}
}
846. 一手顺子
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize: return False
hand.sort()
cnt = Counter(hand)
for x in hand:
if cnt[x] == 0: continue
for i in range(x, x + groupSize):
if cnt[i] == 0: return False
cnt[i] -= 1
return True
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) return false;
Arrays.sort(hand);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int x: hand)
map.put(x, map.getOrDefault(x, 0) + 1);
for (int x: hand){
if (map.get(x) == 0) continue;
for (int i = x; i < x + groupSize; i++){
if (map.getOrDefault(i, 0) == 0) return false;
map.put(i, map.get(i) - 1);
}
}
return true;
}
}
基础知识