LCP 18. 早餐组合

LCP 18. 早餐组合

  第一次写的情况,超时。

public class Solution {
    public int BreakfastNumber(int[] staple, int[] drinks, int x) {
        Array.Sort(staple);
        Array.Sort(drinks);

        // 最后结果
        int res = 0;

        // 同样价格的主食个数
        int count = 0;

        // 当前的主食价格
        int temp = staple[0];

        // 当前主食能搭配的饮料个数
        int drinkNum = 0;

        // 最高价格的主食搭配的饮料数量
        foreach(int i in drinks){
            if(temp + i <= x){
                drinkNum++;
            }else{
                break;
            }
        }

        foreach(int i in staple){
            if(i == temp){
                // 如果主食价格相同则同样价格主食数加一
                count++;
            }else{
                // 如果主食价格变低,则重新计算搭配饮料数
                res += (count * drinkNum);

                count = 1;
                temp = i;
                drinkNum = 0;

                foreach(int j in drinks){
                    if(temp + j <= x){
                        drinkNum++;
                    }else{
                        break;
                    }
                }
            }
        }

        // 最后一种主食的搭配饮料数没有加入结果
        res += (count * drinkNum);

        return res % (1000000007);
    }
}

 题解中的双指针方法。

public class Solution {
    public int BreakfastNumber(int[] staple, int[] drinks, int x) {
        Array.Sort(staple);
        Array.Sort(drinks);

        // 看题解学到的双指针
        int res = 0;
        int stapleLength = staple.Length;
        int drinksLength = drinks.Length;

        int i = 0;
        int j = drinksLength - 1;

        while(i < stapleLength && j >= 0){
            if(staple[i] + drinks[j] <= x){
                res = (res + j + 1) % (1000000007);
                i++;
            }else{
                j--;
            }
        }

        return res;
    }
}

第一种方法最差的时间复杂度为O(mn),过于暴力。超时是正常现象。还是要善用双指针,学好数学啊。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值