华为机试:Directory删除

输入

5
8 6
10 8
6 0
20 8
2 6

输出

2 6

思路:没有用到算法,用HashMap来存 父目录:父目录下的所有子目录 即可。例如0:6

6:8、2 

8:10、20

用List存放所有的目录,有0、6、8、2、10、20

要删的目录是8,遍历Hashmap,只要存在key是8的,先将List中的8删掉,再读Haspmap对应的value在List中对应删掉如10、20删掉,

然后要删的目录10.20..(目的是把他们的子目录也删掉),继续遍历Hashmap......

当然这是本人解法并非最优,【数组标记】

public class Directory删除 {
	static List<Integer> res = new ArrayList();
	static Map<Integer, List<Integer>> map = new HashMap();

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		sc.nextLine();
		for (int i = 0; i < n; i++) {
			String[] s = sc.nextLine().split(" ");
			int a = Integer.parseInt(s[0]);
			int b = Integer.parseInt(s[1]);
			if (!map.containsKey(b)) {
				List l = new ArrayList<>();
				l.add(a);
				map.put(b, l);
				if (!res.contains(a)) {
					res.add(a);
				}
				if (!res.contains(b)) {
					res.add(b);
				}
			} else {
				List l = map.get(b);
				l.add(a);
				map.put(b, l);
				if (!res.contains(a)) {
					res.add(a);
				}
			}
		}
		int delete = sc.nextInt();
		cal(delete);
		Collections.sort(res);
		for (int i : res) {
			if (i == 0) {
				continue;
			}
			System.out.print(i + " ");
		}
	}

	static void cal(int delete) {
		for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
			if (delete == entry.getKey()) {
				if (res.contains(delete)) {
					for (int i = 0; i < res.size(); i++) {
						if (res.get(i) == delete) {
							res.remove(i);
						}
					}
				}
				List<Integer> temp = entry.getValue();
				for (int child : temp) {
					if (res.contains(child)) {
						for (int i = 0; i < res.size(); i++) {
							if (res.get(i) == child) {
								res.remove(i);
							}
						}
					}
					cal(child);
				}
			}
		}
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值