地址:
力扣https://leetcode-cn.com/problems/WqXACV/
题目:
有 N 位扣友参加了微软与力扣举办了「以扣会友」线下活动。主办方提供了 2*N 道题目,整型数组 questions 中每个数字对应了每道题目所涉及的知识点类型。
若每位扣友选择不同的一题,请返回被选的 N 道题目至少包含多少种知识点类型。
示例 1:
输入:questions = [2,1,6,2] 输出:1 解释:有 2 位扣友在 4 道题目中选择 2 题。 |
示例 2:
输入:questions = [1,5,1,3,4,5,2,5,3,3,8,6] 输出:2 解释:有 6 位扣友在 12 道题目中选择题目,需要选择 6 题。 |
提示:
questions.length == 2*n 2 <= questions.length <= 10^5 1 <= questions[i] <= 1000 |
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/WqXACV
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
简化题目就是选6题,看最少包含集中题型
如果告诉你每种题型总共有几个,是不是很容易后续求解
那么我们就用计数数组的技巧将所有题型做个统计,然后再对计数数组进行降序排列
最后依次选题即可
计数数组可以参考:
排序算法之计数排序
方法一、计数数组
int cmp(const void *a, const void *b)
{
return *(int *)b - *(int *)a;
}
int halfQuestions(int* questions, int questionsSize){
int i;
int nums = questionsSize/2;
int types = 0;
int min = questions[0];
int max = questions[0];
for(i=0; i<questionsSize; i++)
{
if(min > questions[i])
min = questions[i];
if(max < questions[i])
max = questions[i];
}
int countLen = max - min + 1;
int offset = 0 - min;
int *countArray = (int *)malloc(sizeof(int) * countLen);
// init coutArray to zero
for(i=0; i<countLen; i++)
{
countArray[i] = 0;
}
for(i=0; i<questionsSize; i++)
{
countArray[questions[i]+offset]++;
}
qsort(countArray, countLen, sizeof(int), cmp);
// debug
// for(i=0; i<countLen; i++)
// {
// printf("countArray[%d]=%d\n", i, countArray[i]);
// }
i=0;
while(nums)
{
if(nums <= countArray[i])
{
types++;
break;
}
else
{
nums -= countArray[i];
types++;
}
i++;
}
return types;
}