题目描述
对于一个整数数列A[0], A[1], …, A[N-1]进行分组,要求每组1到2个数,并且同组之和不能大于w. 求最少可以分成多少组.
1 <= N <= 100000, 1 <= A[i] <= w <= 1000000000.
请实现下面Solution类中计算minPartition(A, w)的函数.
class Solution {
public:
int minPartition(vector A, int w) {
}
};
例1:当A = {2, 5, 4, 3}, w = 5, minPartition(A, w)返回3. 将2和3放一组,4和5各自单独作为一组,共3组.
例2:当A = {2, 5, 4, 3}, w = 7, minPartition(A, w)返回2. 将2和5放一组,3和4一组,共2组.
心路历程
先将A序列从小到大进行排序,然后从两端向中间遍历。每一次遍历末尾的元素都会被去掉,组数都会加1。不同的是如果最后一个数加上第一个数若没有超过w,那么第一个数也去掉。这样做的思想是,最大的数如果能够“带走”一个数的话,那带走最小的数是安全的。因为接下来最大的数能够匹配的最小数的范围会比这个数要大。
解决方案
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int minPartition(vector<int> A, int w) {
int len = A.size();
sort(A.begin(), A.end());
int result = 0;
int j = len - 1;
for (int i = 0; i <= j; j--) {
if (A[i] + A[j] <= w) i++;
result++;
}
return result;
}
};
int main() {
vector<int> A = { 2, 5, 4, 3 };
int w = 5;
Solution solution;
cout << solution.minPartition(A, w) << endl;
system("pause");
return 0;
}