首页 > 解决方案 > 返回一个大小为 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;
}

标签: javaarraysjunit

解决方案


构建数组的 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;
}

推荐阅读