这里是Java的解决方案。记得先将int数组改为Integer数组。因为int数组不能用于 array.sort(comparator)
。
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class TwoDice {
public static void main (String args[]) {
int A1[] = {5}, B1[] = {1,1,6};
int A2[] = {2,3,1,1,2}, B2[] = {5,4,6};
int A3[] = {5,4,1,2,6,5}, B3[] = {2};
int A4[] = {1,2,3,4,3,2,1}, B4[] = {6};
int A5[] = {1,1,1}, B5[] = {2};
int A6[] = {5,4,4,2,6,5}, B6[] = {2};
int A7[] = {1}, B7[] = {2,2,2,2,2,2};
System.out.println(solution(A1,B1));
System.out.println(solution(A2,B2));
System.out.println(solution(A3,B3));
System.out.println(solution(A4,B4));
System.out.println(solution(A5,B5));
System.out.println(solution(A6,B6));
System.out.println(solution(A7,B7));
}
public static int solution(int []A, int[]B ) {
Integer []A_new = changeToInteger(A);
Integer []B_new = changeToInteger(B);
int sum_A = getSum(A_new);
int sum_B = getSum(B_new);
if (sum_A == sum_B) return 0;
if(sum_A < sum_B) {
int temp = sum_A;
sum_A = sum_B;
sum_B = temp;
Object temp_array = A_new;
A_new = B_new;
B_new = (Integer[]) temp_array;
}
Arrays.sort(A_new, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
Arrays.sort(B_new);
int nA = A_new.length;
int nB = B_new.length;
if(nA * 1 > nB * 6 ) return -1;
int count = 0;
int iA = 0, iB = 0;
int candidate_A, candidate_B;
while (sum_A > sum_B) {
if (iA < nA) candidate_A = A_new[iA]; else candidate_A = 1;
if (iB < nB) candidate_B = B_new[iB]; else candidate_B = 6;
if ((candidate_A == 1) && (candidate_B == 6) ) break;
count ++;
if ((candidate_A -1) > (6 - candidate_B)) {
iA++;
sum_A += (1 - candidate_A);
} else {
iB++;
sum_B += (6 - candidate_B);
}
}
return count;
}
public static int getSum(Integer []num) {
int sum = 0;
for(int i: num) {
sum += i;
}
return sum;
}
public static Integer[] changeToInteger(int []nums) {
IntStream stream = Arrays.stream(nums);
Stream<Integer> integerStream = stream.boxed();
Integer[] integers = integerStream.toArray(Integer[]::new);
return integers;
}
}