【发布时间】:2021-07-10 04:14:28
【问题描述】:
我正在处理一个初学者问题,该问题检查一个数组是否是另一个数组的子集,但我遇到了一个特殊情况,下面是案例示例:a = [1,2,3],b = [1,1],其中@987654323 @ 包含1,b 仅包含1,但b 不是a 的子集,因为b 包含1s 中的两个。
如何修改我的代码以使其检查这种特殊情况?
下面是sn-p的代码:
// True if one array is the subset of another array
public boolean checkSubset(int[] arr1, int[] arr2) {
// A counter to remember how many
// times the same element is found
int cnt = 0;
// If one of the array is empty, for empty set
if (arr1.length == 0 || arr2.length == 0) {
return true;
}
// Compare elements in two arrays
for (int i = 0; i < arr1.length; ++i) {
for (int j = 0; i < arr2.length; ++j) {
if (arr1[i] == arr2[j]) {
++cnt;
break;
}
}
}
// cnt would equal to the length of arr1 or arr2
// if one array is the subset of the other one
return (cnt == arr1.length || cnt == arr2.length);
}
【问题讨论】: