1 import java.math.BigDecimal; 2 import java.util.*; 3 4 /** 5 * @name: Exchange 6 * @description: 问题:存在两个序列,相互交换两个序列中的一个元素后,两序列的和相等 7 * 思路:1.分别求出两个序列的和 8 * 2.判断是否存在满足(第一个序列和-2*遍历元素值 == 第二个序列和-2*遍历元素值)条件的项 9 * 3.如果存在2中的项,则交换该两项即可完成 10 * 11 * @version: v1.0 12 * @create: 2021-01-30 09:33 13 **/ 14 15 public class Exchange { 16 17 public static void main(String[] args) { 18 19 Map<Integer,Integer> ones = new HashMap<>(); 20 Map<Integer,Integer> twos = new HashMap<>(); 21 22 Scanner scanner = new Scanner(System.in); 23 System.out.println("Input the number of fisrt values"); 24 int oneNum = scanner.nextInt(); 25 System.out.println("Input the number of values"); 26 for(int i=0;i<oneNum;i++){ 27 ones.put(i, scanner.nextInt()); 28 } 29 30 System.out.println("Input the number of second values"); 31 int secondNum = scanner.nextInt(); 32 System.out.println("Input the number of values"); 33 for(int i=0;i<secondNum;i++){ 34 twos.put(i, scanner.nextInt()); 35 } 36 37 Integer sunOne = ones.values().stream().reduce(Integer::sum).get(); 38 System.out.println("the fisrt list sum:" + sunOne); 39 40 Integer sunTwo = twos.values().stream().reduce(Integer::sum).get(); 41 System.out.println("the fisrt second sum:" + sunTwo); 42 43 boolean isExit = false; 44 Set<Map.Entry<Integer, Integer>> oneEntries = ones.entrySet(); 45 Set<Map.Entry<Integer, Integer>> twoEntries = twos.entrySet(); 46 47 for(Map.Entry<Integer, Integer> oneSet : oneEntries){ 48 for(Map.Entry<Integer, Integer> twoSet : twoEntries){ 49 if (sunOne - 2 * oneSet.getValue() == sunTwo - 2 * twoSet.getValue()) { 50 System.out.println("exit:" + oneSet.getValue() + " " + twoSet.getValue()); 51 isExit = true; 52 Integer tmp = twoSet.getValue(); 53 twoSet.setValue(oneSet.getValue()); 54 oneSet.setValue(tmp); 55 break; 56 } 57 } 58 if (isExit) { 59 break; 60 } 61 } 62 63 ones.values().forEach(System.out::print); 64 System.out.println(); 65 Integer sunOne1 = ones.values().stream().reduce(Integer::sum).get(); 66 System.out.println("the fisrt list sum:" + sunOne1); 67 68 69 twos.values().forEach(System.out::print); 70 System.out.println(); 71 Integer sunTwo1 = twos.values().stream().reduce(Integer::sum).get(); 72 System.out.println("the second list sum:" + sunTwo1); 73 74 if (isExit) { 75 System.out.println("yes"); 76 }else { 77 System.out.println("no"); 78 } 79 } 80 }View Code