数组包含

/**
 * 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);
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值