iHandy笔试

我去,我心态炸了,iHandy笔试写完最后一题,还剩不到两分钟,然后提交上去后。。

import javafx.util.Pair;
这个工具包居然不在jdk里,导不进去,我记得LeetCode可以导进去的,然后。。。
附上iHandy第二题代码,求大佬指正有没有可以优化的地方,个人感觉写的有点冗余。
    public static int [] getSorted(int [][] colors) {
        if (colors == null || colors.length == 0) {
            return new int[0];
        }
        HashMap<Integer, Pair<Integer, Integer>> map = new HashMap<>();
        int m = colors.length;
        int n = colors[0].length;
        boolean [][] visited = new boolean[m][n];
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (visited[i][j]) {
                    continue;
                }
                int s = dfs(colors, visited, i, j, colors[i][j]);
                if (!map.containsKey(colors[i][j])) {
                    map.put(colors[i][j], new Pair<>(s, s));
                } else {
                    Pair<Integer, Integer> p = map.get(colors[i][j]);
                    map.put(colors[i][j], new Pair<>(p.getKey() + s, s > p.getValue() ? s : p.getValue()));
                }
            }
        }
        int [][] res = new int[map.size()][3];
        int index = 0;
        for (int i : map.keySet()) {
            res[index][0] = i;
            res[index][1] = map.get(i).getKey();
            res[index][2] = map.get(i).getValue();
            index++;
        }
        Arrays.sort(res, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) {
                if (o1[1] == o2[1]) {
                    return o2[2] - o1[2];
                } else {
                    return o2[1] - o1[1];
                }
            }
        });
        int [] result = new int[res.length];
        for (int i = 0; i < res.length; ++i) {
            result[i] = res[i][0];
        }
        return result;
    }

    public static int dfs(int [][]colors, boolean [][]visited, int i, int j, int target) {
        if (i < 0 || j < 0 || i >= colors.length || j >= colors[0].length || visited[i][j]) {
            return 0;
        }
        if (colors[i][j] == target) {
            visited[i][j] = true;
            return 1 + dfs(colors, visited, i + 1, j, target)
                    + dfs(colors, visited, i - 1, j, target)
                    + dfs(colors, visited, i, j + 1, target)
                    + dfs(colors, visited, i, j - 1, target);
        }
        return 0;
    }


#iHandy##题解#
全部评论
我直接建了个类
点赞 回复
分享
发布于 2019-09-09 17:14
我剩下50秒,提交写了dfs的版本,得了80。。有点错没改
点赞 回复
分享
发布于 2019-09-09 17:34
百信银行
校招火热招聘中
官网直投

相关推荐

点赞 2 评论
分享
牛客网
牛客企业服务