【发布时间】:2014-06-02 07:47:29
【问题描述】:
我对这个问题有一点小问题。所有电话的所有答案都检查了,除了一个,我没有得到。
contains({1, 2, 1, 2, 3}, {1, 2, 3}) 在应该为真时返回假。
提示:
编写一个名为 contains 的静态方法,它接受两个整数数组 a1 和 a2 作为参数,并返回一个布尔值,指示 a2 的元素序列是否出现在 a1 中(对于是的,否则为假)。 a2 中的元素序列可以出现在a1 中的任何位置,但必须以相同的顺序连续出现。例如,如果名为 list1 和 list2 的变量存储以下值:
int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
int[] list2 = {1, 2, 1};
那么 contains(list1, list2) 的调用应该返回 true,因为 list2 的值序列 {1, 2, 1} 包含在 list1 中,从索引 5 开始。如果 list2 存储了值 {2, 1, 2},则调用 contains(list1, list2) 将返回 false,因为 list1 不包含该值序列。任何两个具有相同元素的列表都被认为是相互包含的,因此诸如 contains(list1, list1) 之类的调用应该返回 true。
您可以假设传递给您的方法的两个数组的长度都至少为 1。您不能使用任何字符串来帮助您解决这个问题,也不能使用产生字符串的方法,例如 Arrays.toString。
代码:
public static boolean contains(int[] first, int[] second) {
int secondCount = 0; // Indicates where to start on second array
if (first.length < second.length) { // If second array is longer than first
return false;
}
for (int i=0; i<first.length; i++) { // goes through each element in first array
if (first[i] == second[secondCount]) { // If elements match
secondCount++; // increment by one and move onto next elem on second
if (secondCount == second.length) { // If complete match
return true;
}
} else { // resets count
secondCount = 0;
}
}
return false;
}
【问题讨论】: