gpt4 book ai didi

java - 在java中找到第k个最小的数字

转载 作者:行者123 更新时间:2023-12-02 11:20:45 25 4
gpt4 key购买 nike

下面是查找数组中第 k 个最小数字的 java 代码。此代码适用于初级版本,未使用枢轴索引。

class Func {
int kthSmallest(int arr[], int smallestIndex, int size){
int smallest = arr[0];
int removeLocation=0;
for(int i=0; i<size; i++){
if(arr[i] < smallest){
smallest = arr[i];
removeLocation = i;
}
}
for(int i=removeLocation; i<size; i++){
arr[i] = arr[i+1];
}
if(smallestIndex == 1) {
return smallest;
} else return kthSmallest(arr, smallestIndex-1, size-1);
}
}

public class Test {
public static void main(String[] args){
Func test = new Func();
int number = test.kthSmallest(new int[]{3,1,2,4,5}, 2, 5);
System.out.println(number);
}
}

结果是

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

我找不到该错误出现的位置。

最佳答案

在第二个 for 循环中,您通过 i+1 修改访问更多超出范围的内容,如下所示

for(int i=removeLocation; i<size-1; i++){
arr[i] = arr[i+1];
}

输出

2

关于java - 在java中找到第k个最小的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49936655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com