小美想知道,能不能通过重排
将会有
第一行一个整数。表示询问次数。
对于每一个询问:
第一行输入两个整数。
第二行输入个整数
。
第三行输入个整数
。
行,每行输出一个字符串,如果能通过重排满足条件则输出"Yes"(不含引号),否则输出"No"。
2 5 3 -1 -2 3 4 5 -1 3 4 2 5 5 6 -1 -2 3 4 5 -1 3 4 2 5
No Yes
对于第一个用例,无论怎么重排都不满足条件。
对于第二个用例,将数组重排为[5,3,-2,4,-1]时满足条件。
import java.util.*; /* 基本思路: 1、因只需要判断存在性,故可直接寻找边界条件 2、对a、b进行排序 3、当(a[n-i-1] + b[i])不在[1,m]中时,即可判定No 4、遍历完后,一定存在至少一种重排方法,所以可判定为Yes */ public class Main { public static Integer[] sort(Integer[] nums){ Arrays.sort(nums, new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2){ return o1 - o2; } }); return nums; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = in.nextInt(); for(int i = 0; i < q; i++){ int n = in.nextInt(); int m = in.nextInt(); Integer[] a = new Integer[n]; Integer[] b = new Integer[n]; for(int j = 0; j < n; j++){ a[j] = in.nextInt(); } for(int j = 0; j < n; j++){ b[j] = in.nextInt(); } a = sort(a); b = sort(b); int d; for(d = 0; d < n; d++){ int value = a[n-d-1] + b[d]; if(value < 1 || value > m){ System.out.println("No"); break; } } if(d == n){ System.out.println("Yes"); } } } }