Leetcode LCS 02. 完成一半题目 第一次算法

有 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测试用例:

 

现在是深夜 等我明天想到优化方法再更新。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值