用java判断两个数组是否有相同的部分和public static boolean haveEqualSums(int[] input1, int[] input2) {
时间: 2024-06-06 21:10:54 浏览: 73
public static boolean haveEqualSums(int[] input1, int[] input2) {
int sum1 = 0, sum2 = 0;
for (int i = 0; i < input1.length; i++) {
sum1 += input1[i];
}
for (int i = 0; i < input2.length; i++) {
sum2 += input2[i];
}
if (sum1 == sum2) {
return true;
}
for (int i = 0; i < input1.length; i++) {
for (int j = 0; j < input2.length; j++) {
if (input1[i] == input2[j]) {
int temp1 = sum1 - input1[i] + input2[j];
int temp2 = sum2 - input2[j] + input1[i];
if (temp1 == temp2) {
return true;
}
}
}
}
return false;
}
相关问题
在java中用递归写一个判断前几项是否有和相同的代码 public static boolean haveEqualSums(int[] input1, int[] input2) {
public static boolean haveEqualSums(int[] input1, int[] input2) {
// 如果输入长度不一致,直接返回false
if (input1.length != input2.length) {
return false;
}
// 调用递归函数判断前i项和是否相等
return haveEqualSumsHelper(input1, input2, 0, 0, 0);
}
private static boolean haveEqualSumsHelper(int[] input1, int[] input2, int i, int sum1, int sum2) {
// 如果已经遍历到数组末尾,判断两个和是否相等
if (i == input1.length) {
return sum1 == sum2;
}
// 递归调用,分别将当前元素加入到两个和中,判断后续部分是否有相等的和
return haveEqualSumsHelper(input1, input2, i+1, sum1+input1[i], sum2) ||
haveEqualSumsHelper(input1, input2, i+1, sum1, sum2+input2[i]);
}
public static boolean haveEqualSums(int[] input1, int[] input2) { 用Java的递归写
public static boolean haveEqualSums(int[] input1, int[] input2) {
return checkEqualSums(input1, 0, input1.length - 1, input2, 0, input2.length - 1);
}
private static boolean checkEqualSums(int[] input1, int start1, int end1, int[] input2, int start2, int end2) {
if (start1 > end1 && start2 > end2) { // both arrays are empty
return true;
}
if (start1 > end1 || start2 > end2) { // one array is empty while the other is not
return false;
}
int sum1 = 0;
for (int i = start1; i <= end1; i++) {
sum1 += input1[i];
}
int sum2 = 0;
for (int i = start2; i <= end2; i++) {
sum2 += input2[i];
}
if (sum1 != sum2) {
return false;
}
// recursively check subsets
for (int i = start1; i <= end1; i++) {
for (int j = start2; j <= end2; j++) {
if (input1[i] == input2[j]) {
if (checkEqualSums(input1, start1, i - 1, input2, start2, j - 1)
&& checkEqualSums(input1, i + 1, end1, input2, j + 1, end2)) {
return true;
}
}
}
}
return false;
}
阅读全文