题解 | #牛牛的数组匹配#
牛牛的数组匹配
https://www.nowcoder.com/practice/3d3406f4a7eb4346b025cc592be5b875
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] A = new int[n]; int[] B = new int[m]; for (int i = 0; i < n; i++) { A[i] = in.nextInt(); } for (int i = 0; i < m; i++) { B[i] = in.nextInt(); } int[] res = m1(A, B); for (int val : res) { System.out.print(val + " "); } } public static int[] m1(int[] A, int[] B) { int m = B.length; int sumA = Arrays.stream(A).sum(); int left = 0; int sumB = 0; int resLeft = 0; int resRight = 0; int diff = sumA; // 差值 for (int i = 0; i < m; i++) { sumB += B[i]; // 窗口内的数据,保证窗口中的和最小,和大了就left右移,和小了就i++ // left右移:右移到差值比前一个差值小为止 // sumB > sumA: left++; 直到 diff[left+1] > diff[left], + - // sumB < sumA: i++; // 包含当前元素: while (left < i && sumB > sumA) { // sumB > sumA // sumB < sumA; if (sumB - B[left] <= sumA) { // 不减B[left]:sumB > sumA // left右移:sumB < sumA; if (Math.abs(sumA - sumB) > Math.abs(sumA - sumB - B[left])) { sumB -= B[left]; left++; } break; } else { sumB -= B[left]; left++; } } int curDiff = Math.abs(sumA - sumB); if (curDiff < diff) { resLeft = left; resRight = i; diff = curDiff; } } int[] res = new int[resRight - resLeft + 1]; for (int i = resLeft; i <= resRight; i++) { res[i - resLeft] = B[i]; } return res; } }