![](/img/trans.png)
[英]How to find continuous sub-array whose sum is equal to a particular number in O(n) time complexity
[英]returning a sub-array of size n, assume the size of n is between 1 and bestTime.length, and return with the lowest sub arrays
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;
}
构建您的bestTime
数组的 IntStream,对它们进行排序,使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.