作者:左程雲
鏈接:https://www.nowcoder.com/discuss/410116?type=0&order=0&pos=21&page=1
來源:牛客網
import java.util.Arrays;
import java.util.Comparator;
public class Code01_KthMinPair {
public static class Pair {
public int x;
public int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static class PairComparator implements Comparator<Pair> {
@Override
public int compare(Pair arg0, Pair arg1) {
return arg0.x != arg1.x ? arg0.x - arg1.x : arg0.y - arg1.y;
}
}
// O(N^2)的複雜度,你肯定過不了
public static int[] kthMinPair1(int[] arr, int k) {
int N = arr.length;
if (k > N * N) {
return null;
}
Pair[] pairs = new Pair[N * N];
int index = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
pairs[index++] = new Pair(arr[i], arr[j]);
}
}
Arrays.sort(pairs, new PairComparator());
return new int[] { pairs[k - 1].x, pairs[k - 1].y };
}
作者:左程雲
鏈接:https://www.nowcoder.com/discuss/410116?type=0&order=0&pos=21&page=1
來源:牛客網
public static int[] kthMinPair2(int[] arr, int k) {
int N = arr.length;
if (k > N * N) {
return null;
}
Arrays.sort(arr);
int fristIndex = (k - 1) / N;
int fristNum = arr[fristIndex];
int fristNumLeftIndex = fristIndex;
while (fristNumLeftIndex >= 0) {
if (arr[fristNumLeftIndex] == fristNum) {
fristNumLeftIndex--;
} else {
break;
}
}
fristNumLeftIndex++;
int fristNumRightIndex = fristIndex;
while (fristNumRightIndex < N) {
if (arr[fristNumRightIndex] == fristNum) {
fristNumRightIndex++;
} else {
break;
}
}
fristNumRightIndex--;
int restTh = k - (fristNumLeftIndex * N);
return new int[] { fristNum, arr[(restTh - 1) / (fristNumRightIndex - fristNumLeftIndex + 1)] };
}