997. Find the Town Judge https://leetcode.com/problems/find-the-town-judge/
public int findJudge(int N, int[][] trust) { if(N == 1 && (trust == null || trust.length == 0)) return 1; int[] check = new int[N+1]; for(int[] tru:trust){ check[tru[1]]++; check[tru[0]]--; } for(int i=0; i <= N; i++) if(check[i] == N-1) return i; return -1; }
1042. Flower Planting With No Adjacent https://leetcode.com/problems/flower-planting-with-no-adjacent/
public int[] gardenNoAdj(int N, int[][] paths) { ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for(int i=0;i<N;i++) graph.add(new ArrayList<>()); for(int[] path:paths){ int x = path[0]-1, y=path[1]-1; graph.get(x).add(y); graph.get(y).add(x); } //try color one by one int[] color = new int[N]; for (int i = 0; i < N; i++) { color[i] = getColor(graph, color, i); } return color; } private int getColor(ArrayList<ArrayList<Integer>> graph, int[] color, int i) { // count which color is used boolean[] flower = new boolean[4+1]; for (int j : graph.get(i)) { if (color[j] != -1) { flower[color[j]] = true; } } // use a color that has not been used for (int x = 1; x <= 4; x++) { if (!flower[x]) { return x; } } return 0; }
原文:https://www.cnblogs.com/zhangzx/p/11750375.html