华为笔试-矩阵相邻
这个题首先需要一个原始矩阵的“数字到索引的反查表,即给出1要查出下标(0, 0);
//存储索引的自定义结构 private static class Index { private int x; private int y; Index(int x, int y) { this.x = x; this.y = y; } } //定义并初始化反查表,共25行,省略 private static HashMap<Integer, Index> map = new HashMap<Integer, Index>() { { put(1, new Index(0, 0)); put(2, new Index(0, 1)); ...省略23行... } };
判断两个索引之间是否相连的函数
private static boolean link(Index i1, Index i2) { return i1.x == i2.x + 1 && i1.y == i2.y || i1.x == i2.x - 1 && i1.y == i2.y || i1.x == i2.x && i1.y == i2.y - 1 || i1.x == i2.x && i1.y == i2.y + 1; }
解题函数,一个未连接数字集合unLinked,一个已连接数字集合linked,循环条件是只要unLinked非空,如果某一次循环,没有发现unLinked中有数字可以和linked中的任一数字相连,直接返回0
private static int solve(int[] nums) { HashSet<Integer> unLinked = new HashSet<>(); for (int i = 1; i < nums.length; i++) { unLinked.add(nums[i]); } HashSet<Integer> linked = new HashSet<>(); linked.add(nums[0]); while (!unLinked.isEmpty()) { HashSet<Integer> tmp = new HashSet<>(); for (Integer i : unLinked) { for (Integer j : linked) { if (link(map.get(i), map.get(j))){ tmp.add(i); } } } if (tmp.isEmpty()) { return 0; } for (Integer i: tmp){ unLinked.remove(i); linked.add(i); } } return 1; }
可惜大部分时间用来想第三题剩下那50%了,差那么5分钟,没写完这题。
#华为##笔试题目##笔经#