0

int我正在尝试从's数组中获取至少 5 个最小值。我的附加代码有效,但它跳过了几个值!

public static void main(String[] args) {
    int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
    int min = 0;
    int index = 0;
    String output = "";
    for (int x = 0; x < 5; x++){
        min = array[x];
        index++;
        for(int i = index, limit = array.length; i < limit; ++i){
            if(array[i] <= min){
                min = array[i];
                index = i + 1;
                break;
            }
        }
        output += index + "\t";               
    }
    System.out.println(output);
}
4

3 回答 3

10
Arrays.sort(array);
return Arrays.copyOfRange(array, 0, 5);

如果你不想改变传入的数组(即你想让它不排序),首先添加这一行:

int[] array = Arrays.copyOf(array);
于 2012-12-14T02:33:15.920 回答
4

也许您可以使用 Arrays.sort() 对数组进行排序,然后取前五个值:

Arrays.sort(array);

现在包含最低的 5 个值array[0]array[4]

于 2012-12-14T02:33:27.680 回答
1

如果您只想获得 5 个最小值,我同意 Bohemian's Answer。如果你想显示数组的位置,比如1,2,4,7,10,你的demo跳过2,试试我的测试...

public static void main(String[] args) {
    int getNum = 5;
    int step = 0;
    String output = "";
    int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
    int arrayClone[] = array.clone();
    Arrays.sort(array);
    int arrayResult[] = Arrays.copyOfRange(array, 0, getNum); //the arrayResult is what you want minimum values

    ploop:for (int i:arrayResult) {
        int index = 1;
        for (int j :arrayClone) {
            if(j==i){
                step++;
                output += index + "\t"; 
                if (step>=getNum) {
                    break ploop;
                }                    
            }
            index++;
        }
    }  

    System.out.println(output);        
}
于 2012-12-14T10:20:29.917 回答