贪心算法
- 问题描述
- 已知有一些孩子和一些糖果,每个孩子都有一个对糖果对需求,用g表示,每个糖果有响应对大小,用s表示。当某个糖果的大小s,大于等于某个孩子对糖果对需求g时,说明该孩子可以被这个糖果所满足,那么使用这些糖果,最多可以满足多少孩子?
public static int findContentChildren(int [] children,int [] candies){
sort(children);
sort(candies);
int child = 0;
int candy = 0;
while(candy < candies.length && child < children.length){
if(candies[candy] >= children[child]){
child ++;
}
candy ++;
}
return child;
}
public static int [] sort(int [] array){
quick_sort(array,0,array.length - 1);
for (int i : array) {
System.out.println("i "+i);
}
return array;
}
static void quick_sort(int s[], int l, int r)
{
if (l < r && l >= 0 && r < s.length)
{
//Swap(s[l], s[(l + r) / 2]); //将中间的这个数和第一个数交换 参见注1
int i = l, j = r, x = s[l];
while (i < j)
{
while(i < j && s[j] >= x) // 从右向左找第一个小于x的数
j--;
if(i < j)
s[i++] = s[j];
while(i < j && s[i] < x) // 从左向右找第一个大于等于x的数
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s, l, i - 1); // 递归调用
quick_sort(s, i + 1, r);
}
}