题解 | #牛牛的数组匹配#
牛牛的数组匹配
https://www.nowcoder.com/practice/3d3406f4a7eb4346b025cc592be5b875
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int sumA = 0; //数组a的和 for (int i = 0; i < n ; i++) { sumA += sc.nextInt(); } //获取数组b int[] arrB = new int[m]; for (int j = 0; j < m; j++) { arrB[j] = sc.nextInt(); } //记录子数组起止下标以及跟sumA的差 int star = -1; int end = -1; int cha = 999; //循环各种子数组组合 for (int i = 0 ; i < m - 1; i++) { for (int j = i; j < m; j++) { int sumSub = 0; //求和 for (int k = i; k <= j; k++) { sumSub += arrB[k]; } if (Math.abs(sumA - sumSub) < cha) { star = i; end = j; cha = Math.abs(sumA - sumSub); } } } for (int i = star ; i <= end; i++) { System.out.print(arrB[i] + " "); } } }