测试样例
样例1:
输入:
n = 9, max = 34, array = [6, 6, 6, 8, 8, 8, 5, 5, 1]
输出:[8, 5]
样例2:
输入:
n = 9, max = 37, array = [9, 9, 9, 9, 6, 6, 6, 6, 13]
输出:[6, 9]
样例3:
输入:
n = 9, max = 40, array = [1, 11, 13, 12, 7, 8, 11, 5, 6]
输出:[0, 0]
思路:
数据解构选择:
1.**先面值映射:由于牌面值的大小规则是 A > K > Q > J > 10 > 9 > ... > 2,可以采用undered_map<int,int>**进行【A牌面最大,但是值最小,没注意是入坑了~~】
# 牌面值的映射
card_value = {
1: 14, # A
13: 13, # K
12: 12, # Q
11: 11, # J
10: 10, # 10
9: 9, # 9
8: 8, # 8
7: 7, # 7
6: 6, # 6
5: 5, # 5
4: 4, # 4
3: 3, # 3
2: 2 # 2
}
2.牌的计数:我们可以使用一个 std::unordered_map<int, int> 来统计每种牌面值的出现次数
算法步骤:
1.统计每种面值的数量:遍历数组array,统计每种面值出现次数;
2.寻找合适“葫芦”:
- 遍历map统计面值次数value超过3的值key,记作a
- 找到满足3的了,再去找两个不同牌面并且次数2的,记作b;
- 计算sum=a+b,满足sum小于指定最大值,记录组合,更新
ok,写了:
def solution(n, max, array):
# 统计每种牌面值的出现次数
count = {}
for card in array:
if card in count:
count[card] += 1
else:
count[card] = 1
# 生成可能的“葫芦”组合
max_a = 0
max_b = 0
for a in count: # a在这里相当牌面
if count[a] >= 3:
for b in count:
if b != a and count[b] >= 2:
# 检查五张牌的牌面值之和是否超过 max
if a * 3 + b * 2 <= max:
# 更新最大“葫芦”组合
if a > max_a or (a == max_a and b > max_b):
max_a = a
max_b = b
# 返回结果
if max_a == 0:
return [0, 0]
else:
return [max_a, max_b]
**注意:**上面代码是错误的!!其实我第一次写连映射map都没想到,A面值在计数时候是1,但是在a,b比较是按最大进行比较。然后我去找大佬的博客看:CSDN转接大佬博客
AC代码:
```python
from collections import defaultdict
def solution(n, max_sum, array):
# 统计每种牌面值的出现次数
count = defaultdict(int)
for card in array:
adjusted_card = card if card != 1 else 14
count[adjusted_card] += 1
# 生成可能的“葫芦”组合
max_a = 0
max_b = 0
current_sum = 0
for a in count:
if count[a] >= 3:
for b in count:
if a != b and count[b] >= 2:
sum_value = calculate_sum(a if a != 14 else 1, b if b != 14 else 1)
if sum_value <= max_sum:
if a > max_a or (a == max_a and b > max_b):
max_a = a
max_b = b
current_sum = sum_value
# 返回结果
if current_sum > 0:
return [max_a if max_a != 14 else 1, max_b if max_b != 14 else 1]
else:
return [0, 0]
def calculate_sum(num1, num2):
return num1 * 3 + num2 * 2
# 测试用例
result1 = solution(9, 34, [6, 6, 6, 8, 8, 8, 5, 5, 1])
print(result1 == [8, 5])
result2 = solution(9, 37, [9, 9, 9, 9, 6, 6, 6, 6, 13])
print(result2 == [6, 9])
result3 = solution(9, 40, [1, 11, 13, 12, 7, 8, 11, 5, 6])
print(result3 == [0, 0])
```
大佬代码:还好再把map,里面key,value拿到代码里
# 寻找符合条件的“葫芦”
num3 = 0
num2 = 0
current_sum = 0
for key, value in count.items():
if value >= 3:
for other_key, other_value in count.items():
if other_key != key and other_value >= 2:
sum_value = calculate_sum(key if key != 14 else 1, other_key if other_key != 14 else 1)
if sum_value <= max_sum:
if key > num3 or (key == num3 and other_key > num2):
num3 = key
num2 = other_key
current_sum = sum_value
**py语法补充:**defaultdict->count = defaultdict(int)
计数器:当你需要统计某个元素出现的次数时,可以使用
defaultdict(int)。分组:当你需要将数据分组时,可以使用
defaultdict(list)。缓存:当你需要缓存计算结果时,可以使用
defaultdict(lambda: some_default_value)。
每天刷刷,码农夸夸~~