简体   繁体   English

使用这种方法没有得到预期的答案?

[英]Not getting expected answer using this approach?

I am solving a question on LeetCode, Here is the Link我正在解决关于 LeetCode 的问题, 这是链接

I got the solution but I wanted to know what wrong I am doing here, There are some testCases below or you can visit the link.我得到了解决方案,但我想知道我在这里做错了什么,下面有一些测试用例,或者您可以访问链接。 A helping attempt is always appreciated from my side.从我的角度来看,帮助尝试总是很受欢迎。

class Solution {
public:
    static bool comparator(vector<int>&a,vector<int>&b){
        return a[1]>b[1];
    }
    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
        
        sort(boxTypes.begin(),boxTypes.end(),comparator);
        int sum=0;

        for(int i =0;i<boxTypes.size();i++){
           
            if(truckSize>boxTypes[i][0]){
                sum+=boxTypes[i][0] * boxTypes[i][1];
                truckSize= truckSize - boxTypes[i][0];
                
            }else{
                sum += truckSize * boxTypes[i][1];
                
            }
            
        }
        return sum;
    }
};

TestCases:测试用例:

 [[1,3],[2,2],[3,1]]

 4
 
 [[5,10],[2,5],[4,7],[3,9]] 

10

Expected:预期的:

8                                        
91                                        

OutPut: OutPut:

8
101

You need to add a break in the else statement.您需要在 else 语句中添加一个break If truckSize <= boxTypes[i][0] , we just load truckSize boxes and it will no longer accept any boxes (which means we need to break the for loop and return the result).如果truckSize <= boxTypes[i][0] ,我们只加载truckSize盒子,它将不再接受任何盒子(这意味着我们需要打破 for 循环并返回结果)。 Otherwise, it will continue the for loop, and try to load the following boxes.否则,它将继续 for 循环,并尝试加载以下框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM