题目地址:
https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket/
给定 n n n个苹果的重量数组 A A A和一个重量上限,问不超过重量上限的情况下最多能放多少个苹果。
从小到大依次放即可。代码如下:
class Solution {
public:
int maxNumberOfApples(vector<int>& weight) {
int res = 0, x = 5000;
sort(weight.begin(), weight.end());
for (int y : weight)
if (x >= y) {
x -= y;
res++;
} else break;
return res;
}
};
时间复杂度 O ( n log n ) O(n\log n) O(nlogn),空间 O ( 1 ) O(1) O(1)。