检查是否存在满足条件的数字组合
题目信息
输入一组数字,数字之间用空格隔开,判断输入的数字是否可以满足A=B+2C,每个元素最多只可用一次。若有满足的数字组合,依次输出A、B、C三个数字,之间用空格隔开;若无满足条件的组合,输出0。
例如:输入 2 3 5 7 输出 7 3 2
编码
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; public class CheckNumCouple { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input; while ((input = br.readLine()) != null) { String[] numArrStr = input.split(" "); checkNumsCouple(numArrStr); } } /** * 检查是否存在满足条件的数字组合 * @param arrs 数组 */ public static void checkNumsCouple(String[] arrs) { // 将字符数组转换为Integer数组 Integer[] arr = new Integer[arrs.length]; for (int i=0; i<arrs.length; i++) { arr[i] = Integer.valueOf(arrs[i]); } // 让数组降序排列 // 通过下面的循环,此处排序可以不要 Arrays.sort(arr, new Comparator<Integer>(){ public int compare(Integer o1, Integer o2) { return o2 - o1; } }); // 定义标识,是否有满足条件数字组合 // 0 无;1或其它值 有 int index = 0; // 循环数组,让等式相等且3个元素的位置不相等 for (int i=0; i<arr.length; i++) { for (int j=0; j<arr.length; j++) { for (int k=0; k<arr.length; k++) { if ((arr[i] == arr[j] + 2*arr[k]) && (i!=j && i!=k && j!=k)) { index++; System.out.println(arr[i] + " " + arr[j] + " " + arr[k]); } } } } // 无满足条件的数字 if (index == 0) { System.out.println(0); } } }
上面代码
输入 2 3 4 5 7
输出 7 3 2
输入 2 4 0
输出 4 0 2
输入 1 2 3
输出 0