有 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
示例代码:
class Solution(object):
def halfQuestions(self, questions):
"""
:type questions: List[int]
:rtype: int
"""
list_count = []
set_n = set(questions)
for i in set_n:
list_count.append(questions.count(i))
list_count.sort(reverse=True)
for i in range(len(list_count)):
if sum(list_count[:i+1]) >= len(questions)/2:
return len(list_count[:i+1])
示例代码2:【用字典的形式比集合的形式效率高一点】
class Solution(object):
def halfQuestions(self, questions):
"""
:type questions: List[int]
:rtype: int
"""
dict1 = {}
num = len(questions) // 2
res = 0
for question in questions:
if question in dict1:
dict1[question] += 1
else:
dict1[question] = 1
sort_dict1 = sorted(dict1.items(), key=lambda item:item[1], reverse=True)
for item in sort_dict1:
if num > 0:
res += 1
num -= item[1]
if num <= 0:
return res
贪心算法,对questions按出现频率降序排列,频数累计超过一半questions长度时,就可以返回结果;
示例代码3:
class Solution(object):
def halfQuestions(self, questions):
"""
:type questions: List[int]
:rtype: int
"""
dict1 = {}
num = len(questions) // 2
res = 0
for question in questions:
if question in dict1:
dict1[question] += 1
else:
dict1[question] = 1
sort_dict1 = sorted(dict1.values(), reverse=True)
for item in sort_dict1:
if num > 0:
res += 1
num -= item
if num <= 0:
return res
示例代码4:
class Solution(object):
def halfQuestions(self, questions):
"""
:type questions: List[int]
:rtype: int
"""
num = len(questions) // 2
count = collections.Counter(questions)
temp = list(count.values())
temp.sort(reverse=True)
res = 0
for i, n in enumerate(temp):
res += n
if res >= num:
return i+1