LeetCode LCP18.早餐组合

题目描述

小扣在秋日市集选择了一家早餐摊位,一维整型数组 staple 中记录了每种主食的价格,一维整型数组 drinks 中记录了每种饮料的价格。小扣的计划选择一份主食和一款饮料,且花费不超过 x 元。请返回小扣共有多少种购买方案。

注意:答案需要以 1e9 + 7 (1000000007) 为底取模,如:计算初始结果为:1000000008,请返回 1

思路:只想到暴力枚举,两个for

代码

class Solution {
    public int breakfastNumber(int[] staple, int[] drinks, int x) {
        int count = 0;
        for(int i = 0 ; i<staple.length; i++){
            for(int j = 0 ; j<drinks.length ;j ++)
            {
                if((staple[i] + drinks[j])<=x)
                   count++;
            }
        }
        return count;

    }
}

没通过 ,超时。。。。。。。

改进

想法是先处理下两个数组,把单品超过x的删除。

class Solution {
    public int breakfastNumber(int[] staple, int[] drinks, int x) {
        int count = 0;
        List<Integer> a = new ArrayList<>();
        List<Integer> b = new ArrayList<>();
        for(int i = 0 ; i<staple.length; i++){
            if(staple[i]<x)
               a.add(staple[i]);
        }
        for(int i = 0 ; i<drinks.length; i++){
            if(drinks[i]<x)
               b.add(drinks[i]);
        }

       
        for(int i = 0 ; i<a.size(); i++){
            for(int j = 0 ; j<b.size() ;j ++)
            {
                if((a.get(i) + b.get(j))<=x)
                   count++;
            }
        }
        return count;

    }
}

经过我的一方改进 ,还是超时。绷不住了。。。。

看了下各种答案也云里雾里,下次吧

 

题解

反思总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值