有 N
位扣友参加了微软与力扣举办了「以扣会友」线下活动。主办方提供了 2*N
道题目,整型数组 questions
中每个数字对应了每道题目所涉及的知识点类型。
若每位扣友选择不同的一题,请返回被选的 N
道题目至少包含多少种知识点类型。
示例 1:
输入:questions = [2,1,6,2]
输出:1
解释:有 2 位扣友在 4 道题目中选择 2 题。
可选择完成知识点类型为 2 的题目时,此时仅一种知识点类型
因此至少包含 1 种知识点类型。
示例 2:
输入:questions = [1,5,1,3,4,5,2,5,3,3,8,6]
输出:2
解释:有 6 位扣友在 12 道题目中选择题目,需要选择 6 题。
选择完成知识点类型为 3、5 的题目,因此至少包含 2 种知识点类型。
提示:
questions.length
== 2*n- 2 <=
questions.length
<= 10^5 - 1 <=
questions[i]
<= 1000
思路
主要思路就是用字典先存储每个知识点对应的题目数(建立知识点->题目数
的映射),然后按照题目数从大到小排序,并从头开始取即可,直到所有人都有题目做。
这里有一个问题,就是需要对字典按照value值排序:
map_order = sorted(map.items(), key=lambda x: x[1], reverse=True)
这里返回的map_order
是排好序的列表,里面每个键值对变成了二元组(以示例2为例):
[(5, 3), (3, 3), (1, 2), (4, 1), (2, 1), (8, 1), (6, 1)]
所以下面调用value
的时候需要这么写(调用第point
个元组的第二个元素,就是原来字典中第point
个键值对的value
):
map_order[point][1]
代码
class Solution(object):
def halfQuestions(self, questions):
"""
:type questions: List[int]
:rtype: int
"""
map = {}
questions_num = len(questions)
people_num = questions_num/2
for i in range(questions_num):
if questions[i] in map:
value = map[questions[i]]
value += 1
map[questions[i]] = value
else:
map.update({questions[i]: 1})
map_order = sorted(map.items(), key=lambda x: x[1], reverse=True)
point = 0
result = 0
while people_num > 0:
if map_order[point][1] <= people_num:
people_num -= map_order[point][1]
result += 1
point += 1
else:
people_num = 0
result += 1
break
return result