java分饼干算法代码
时间: 2023-09-19 14:12:13 浏览: 59
以下是一个简单的 Java 分饼干算法代码示例:
```
import java.util.Arrays;
public class DistributeCookies {
public static int findContentChildren(int[] children, int[] cookies) {
Arrays.sort(children);
Arrays.sort(cookies);
int child = 0;
for (int cookie = 0; child < children.length && cookie < cookies.length; cookie++) {
if (cookies[cookie] >= children[child]) {
child++;
}
}
return child;
}
public static void main(String[] args) {
int[] children = {1, 2, 3};
int[] cookies = {1, 1};
System.out.println(findContentChildren(children, cookies));
}
}
```
该算法的思路:首先将孩子数组和饼干数组排序,然后从饼干数组的第一个元素开始遍历,如果当前饼干能够满足当前孩子的需求,则将孩子指针向后移动一位。最后返回满足需求的孩子个数即可。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)