/**
* A: 4, 1, 6, 2, 2, 8, 9, 5, 3, 2, 9, 8, 4, 6
* B: 6, 1, 2, 9, 8, 2
* where B contains elements which are in A in consecutive locations but may be
* in any order. Find their starting and ending indexes in A. (Be careful of
* duplicate numbers).
*
* answer is (1,6)
*
*
*/
public class ArrayContain {
public HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
public void reset(int[] keys) {
for(int i=0; i<keys.length; i++){
if(map.containsKey(keys[i])){
int current = map.get(keys[i]);
map.put(keys[i], current+1);
}else{
map.put(keys[i], 1);
}
}
}
public int find(int[] a, int[] keys) {
assert (true);
int i = 0;
int j = keys.length;
while (true) {
if (i == a.length) {
return -1;
}
if (j == 0) {
return i-1;
}
if (isKey(a[i]) && canDo(a[i])) {
doit(a[i]);
j--;
} else if (j != keys.length) {
reset(keys);
j = keys.length;
}
i++;
}
}
private boolean isKey(int key) {
return map.containsKey(key);
}
private boolean canDo(int key) {
if (isKey(key)) {
return map.get(key) > 0 ? true : false;
}
return false;
}
private void doit(int key) {
int current = map.get(key);
map.put(key, current - 1);
}
/**
* @param args
*/
public static void main(String[] args) {
int[] a = {4, 1, 6, 2, 2, 8, 9, 5, 3, 2, 9, 8, 4, 6};
int[] keys = {6, 1, 2, 9, 8, 2};
ArrayContain ac = new ArrayContain();
ac.reset(keys);
int x = ac.find(a, keys);
if(x == -1){
System.out.println("can not find");
}else{
System.out.println(x-keys.length+1 + " , " + x);
}
}
}
数组包含
最新推荐文章于 2024-05-21 17:02:20 发布