給定兩個數字列表(稱爲listA和listB),我需要編寫一個Java方法 ,它返回一個布爾值來指明 listA中的所有元素包含在listB中。檢查一個數組中的所有元素是否都包含在另一個數組中
我不能完全讓我的代碼工作,因爲它似乎總是返回false。
public static boolean containsAll(int[] listA, int[] listB)
{
boolean containsAll = true;
int ctr1 = 0, ctr2 = 0;
while(ctr1 < listA.length && containsAll)
{
ctr2 = 0;
while(ctr2<listB.length && containsAll)
{
if(listA[ctr1] != listB[ctr2])
containsAll = false;
ctr2++;
}
ctr1++;
}
return containsAll;
}
public static void testContainsAll()
{
Scanner input1 = new Scanner(System.in);
System.out.println("Enter size of first array");
int array1[] = new int[input1.nextInt()];
System.out.println("Enter number of ints required");
for(int i=0; i<array1.length; i++)
{
array1[i] = input1.nextInt();
}
Scanner input2 = new Scanner(System.in);
System.out.println("Enter size of second array");
int array2[] = new int[input2.nextInt()];
System.out.println("Enter number of ints required");
for(int i=0; i<array2.length; i++)
{
array2[i] = input2.nextInt();
}
boolean containsAll = containsAll(array1,array2);
if(containsAll == true)
System.out.print("listB contains all elements of listA");
else
System.out.print("listB doesn't contain all elements of listA");
}
您是否已經在調試器中逐步瞭解代碼?你發現了什麼? –
您可以簡單地將每個數組轉換爲HashSet並檢查它們的交集。 –
@JacobG。不簡單。 – shmosel