java - 返回一个大小为 n 的子数组,假设 n 的大小在 1 和 bestTime.length 之间,并返回最小的子数组
问题描述
int[] bestTime = {50, 73, 72, 75, 71, 56, 61, 60, 62, 68, 70, 50, 70};
假设如果 n = 6,预期回报 = {50, 50, 56, 60, 61, 62}
这是我到目前为止所拥有的,我知道有很多错误。任何建议都非常感谢。
public static int[] bestRun(int n) {
int[] best = bestTime[0];
for(int i = 0; i <= bestTime.length; i++ ) {
if(bestTime[i] <= best) {
best = bestTime[i];
best++;
} return best;
}
if(best.length == n) {
return best;
}
return null;
}
解决方案
构建数组的 IntStream bestTime
,对它们进行排序,限制使用n
,转换为数组并返回:
public static int[] bestRun(int n) {
return IntStream.of(bestTime).sorted().limit(n).toArray();
}
您也可以使用经典的 for 循环来完成任务。但是你需要自己实现排序。像下面这样的东西应该给你一个如何实现的:
static int[] bestTime = {50, 73, 72, 75, 71, 56, 61, 60, 62, 68, 70, 50, 70};
public static void main(String args[]) throws IOException{
int[] best = bestRun(6);
System.out.println(Arrays.toString(best));
}
public static int[] bestRun(int n) {
//copy your bestTime array
int[] copy = new int[bestTime.length];
for(int i = 0; i < copy.length; i++){
copy[i] = bestTime[i];
}
//sort copy
for (int i = 0; i < copy.length; i++) {
for (int j = i+1; j < copy.length; j++) {
int temp = 0;
if(copy[i] > copy[j]) {
temp = copy[i];
copy[i] = copy[j];
copy[j] = temp;
}
}
}
//fill your result array
int[] result = new int[n];
for(int i = 0; i < n; i++){
result[i] = copy[i];
}
return result;
}
推荐阅读
- wordpress - 在 woocommerce 产品的 quickedit 函数中添加我的自定义输入字段
- excel - 在 IF 语法 VBA 中包含 #N/A 值
- android - 使用 viewModel 和 livedata 在 2 个活动之间传递数据
- plugins - 更新dokuwiki的tagentry插件后如何修复兼容性警告
- node.js - 任何人都可以帮助解决这个问题吗?即使我在 Index.html 中包含了 vendor,js 文件
- c# - 我想在同一个数据网格上使用两个可观察的集合
- html - 获取指定屏幕尺寸的 ui 设计后如何计算不同屏幕尺寸的边距/填充
- javascript - 执行 expo init 命令时出现以下错误
- android - Android Studio 3.3.2 的 BLE 应用程序问题
- ios - ios swift大tableview单元格数据每秒更新一次