modify code

master
algorithmzuo 3 years ago
parent b5b88d45f3
commit 5fb9b050d3

@ -93,6 +93,29 @@ public class Code03_HappyLimitLessGap {
return ans; return ans;
} }
// 正式方法
// 排序 + 窗口
public static int lessGap3(int[] a, int[] b, long k) {
int n = a.length;
int[][] f = new int[n][2];
for (int i = 0; i < n; i++) {
f[i][0] = a[i];
f[i][1] = b[i];
}
Arrays.sort(f, (x, y) -> x[1] - y[1]);
int ans = Integer.MAX_VALUE;
for (int l = 0, r = 0, happy = 0; l < n; l++) {
while (r < n && happy < k) {
happy += f[r++][0];
}
if (happy >= k) {
ans = Math.min(ans, f[r - 1][1] - f[l][1]);
}
happy -= f[l][0];
}
return ans == Integer.MAX_VALUE ? -1 : ans;
}
// 为了验证 // 为了验证
public static int[] randomArray(int n, int v) { public static int[] randomArray(int n, int v) {
int[] arr = new int[n]; int[] arr = new int[n];
@ -115,7 +138,8 @@ public class Code03_HappyLimitLessGap {
int k = (int) (Math.random() * n * V) + 1; int k = (int) (Math.random() * n * V) + 1;
int ans1 = lessGap1(a, b, k); int ans1 = lessGap1(a, b, k);
int ans2 = lessGap2(a, b, k); int ans2 = lessGap2(a, b, k);
if (ans1 != ans2) { int ans3 = lessGap3(a, b, k);
if (ans1 != ans2 || ans1 != ans3) {
System.out.println("出错了!"); System.out.println("出错了!");
} }
} }

Loading…
Cancel
Save