有 N 位扣友参加了微软与力扣举办了「以扣会友」线下活动。主办方提供了 2*N 道题目,整型数组 questions 中每个数字对应了每道题目所涉及的知识点类型。
若每位扣友选择不同的一题,请返回被选的 N 道题目至少包含多少种知识点类型。
这篇博客的算法能够解决所有的测试用例的输出
但是在Leetcode 36/39 测试用例会被判定超时 但是IDEA是0ms运行的
碍于时间有限 只能将算法保存
算法很简单:计数+排序
import java.util.Scanner;
public class HalfQuestions {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input N");
int N = in.nextInt();
int[]a = new int[2*N];
for (int i = 0; i<a.length ; i++) {
a[i] = in.nextInt();
}
in.close();
// long startTime = System.currentTimeMillis();
System.out.println(halfQuestions(a));
// long endTime = System.currentTimeMillis(); //获取结束时间
// System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间
}
public static int halfQuestions(int[] a){
int[] count = new int[a.length];
// for (int i = 0; i <a.length ; i++)
// System.out.println(count[i]);
// System.out.println("===============");
for (int i = 0; i < a.length; i++) {
if (count[i] != -1) {
count[i] = 1;
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
count[i]++;
count[j] = -1;
}
}
}
}
// for (int i = 0; i <a.length ; i++)
// System.out.print(count[i]+" ");
// System.out.println("=================");
for (int i = 0; i <a.length ; i++) {
for (int j = i+1; j < a.length; j++) {
if(count[j] > count[i]){
int temp = count[i];
count[i] = count[j];
count[j] = temp;
}
}
}
// for (int i = 0; i <a.length ; i++)
// System.out.print(count[i]+" ");
// System.out.println();
int sum = a.length/2;
int flag = 0;
for (int i = 0; i < a.length; i++) {
flag += count[i];
if(flag >= sum){
flag = i+1;
break;}
}
return flag;
}
}
结果显然都是正确的:
超时的是这个BT测试用例:
现在是深夜 等我明天想到优化方法再更新。