java - 编写一个程序,返回数组中大于 11 的前 3 个数字,然后返回你找到的数?
问题描述
编写一个程序,返回大于 11 的前 3 个数字。如果小于 3 个大于 11 的数字,则返回找到的数量。您将始终返回一个大小为 3 的数组。如果没有 3 个大于 11 的数字,则零将填充数组。我如何解决这个问题。这就是我开始我的代码的方式:
public class RayGetNums
{
//method go will return an array
//containing the first 3 numbers
//greater than 11
public static int[] go(int[] ray)
{
return null;
}
}
我在这个问题上使用的 Runner 是这样的:
class Runner
{
public static void main(String[] args)
{
RayGetNums rt = new RayGetNums();
System.out.println( rt.go( new int[]{-99,1,2,3,4,5,6,7,8,9,10,12345} ) );
System.out.println( rt.go( new int[]{10,9,8,7,6,5,4,3,2,1,-99} ) );
System.out.println( rt.go( new int[]{10,20,30,40,50,-11818,40,30,20,10} ) );
System.out.println( rt.go( new int[]{32767} ) );
System.out.println( rt.go( new int[]{255,255} ) );
System.out.println( rt.go( new int[]{9,10,-88,100,-555,1000} ) );
System.out.println( rt.go( new int[]{10,10,10,11,456} ) );
System.out.println( rt.go( new int[]{-111,1,2,3,9,11,20,30} ) );
System.out.println( rt.go( new int[]{9,8,7,6,5,4,3,2,0,-2,-989} ) );
System.out.println( rt.go( new int[]{12,15,18,21,23,1000} ) );
System.out.println( rt.go( new int[]{250,19,17,15,13,11,10,9,6,3,2,1,-455} ) );
System.out.println( rt.go( new int[]{9,10,-8,10000,-5000,1000} ) );
}
}
我需要我们这个跑步者的答案:
[12345, 0, 0]
[0, 0, 0]
[20, 30, 40]
[32767, 0, 0]
[255, 255, 0]
[100, 1000, 0]
[456, 0, 0]
[20, 30, 0]
[0, 0, 0]
[12, 15, 18]
[250, 19, 17]
[10000, 1000, 0]
谢谢
解决方案
使用循环将大于 11 的元素添加到数组并返回。
public static int[] go(int[] ray)
{
int[] res = new int[]{0,0,0};
int count = 0;
for (int i = 0; i < ray.length && count < 3; i++) {
if ( ray[i] > 11 ) {
res[count++] = ray[i];
}
}
return res;
}
推荐阅读
- raspberry-pi - OpenCV 无法在生产服务器上捕获帧(Nginx + uWSGI)
- python - 如何在 Flask-MonitoringDashboard 中记录自定义数据?
- node.js - 如何在sequelize中设置两个表的关联?
- python - 如何在 TradingView 中使用 python 请求生成警报?
- c++ - 为什么这个 HTTP 响应流会产生解析错误?
- python - UpdateView 不保存数据,在 url 中返回对象字段数据
- python - 根据python中的过滤列表检查列表
- r - 将 SQLServer 表直接传输到 R 中的 DuckDB
- github - 如何从 Github 的源代码文件中只获取一些行?
- python - Numpy 3D数组最大值和最小值