3 回答
TA贡献1796条经验 获得超4个赞
这段代码解决了问题:
int[] key = new int[]{3, 8, 6};
int[] target = new int[]{3, 6, 8, 8, 6, 3, 8, 6, 2, 4};
for (int i = 0; i < target.length; i++) {
int j = 0;
for (j = 0; j < key.length && (i + j) < target.length; j++) {
if (target[i + j] != key[j]) {
break;
}
}
if (j == key.length && j != 0) {
System.out.print("{");
for (j = 0; j < key.length; j++) {
System.out.print(i + j);
if (j != key.length - 1) {
System.out.print(", ");
}
}
System.out.println("}");
}
}
TA贡献1876条经验 获得超6个赞
HashMap<Integer, Integer> maps = new HashMap<>();
IntStream.range(0, target.length).forEach(i -> {
maps.put(target[i], i);
});
Arrays.stream(src).forEach(i -> {
System.out.println(maps.get(i));
});
首先计算索引,它喜欢group by,但只选择最后一个。最后我们可以很容易地从这个Hash 中得到索引。
TA贡献1773条经验 获得超3个赞
您应该遍历“目标”数组中的所有元素,并在“键”数组中的当前匹配模式之后保留一些索引,我们将此索引称为“keyIndex”。每次“目标”数组中的元素等于“键”数组中“keyIndex”位置的元素时,您增加 keyIndex(当前匹配模式更大)并添加到一些数据结构(我选择列表) 来自“目标”数组的索引,其中元素相等。如果元素不相等,您应该重置“keyIdnex”(当前匹配模式的长度为零)并清除列表。
我相信这应该对你有好处:
public static List<Integer> findPattern(int[] key , int[] target){
List<Integer> result = new ArrayList<Integer>(); //This list hold the indexes of the patter
int keyIndex = 0; //The index to follow after the "key" array
for(int i = 0 ; i < target.length; i++){
if(target[i] == key[keyIndex]){ //This "key" element is equal to the element from the "target"
result.add(i); //Add the index in which the elements are equal.
keyIndex++; //The currently match pattern is larger, increment "keyIndex"
if(result.size() == key.length) //The all pattern is checked and match, return the list which store the indexes
return result;
}else{ //The pattern is not match anymore, reset all the data
keyIndex = 0;
i--;
result.clear();
}
}
return null; //The pattern from "key" not found in "target" ,return null
}
添加回答
举报