奇安信0514

84 阅读1分钟

1. 反色黑白

思路:直接模拟,用状态数组存当前格子黑白情况

public class qax2 {
    public static void main(String[] args) {
        int[][] rects = new int[][]{{0,0,1,1}, {4,4,0,0}, {0,0,1,1}};
        System.out.println(getWhiteCounts(rects));
    }
    public static int getWhiteCounts (int[][] rects) {
        // write code here
        boolean[][] grid = new boolean[100][100];
        int count = 10000;
        for (int[] rect : rects){
            int x1 = rect[0] < rect[2] ? rect[0] : rect[2];
            int y1 = rect[1] < rect[3] ? rect[1] : rect[3];
            int x2 = rect[2] + rect[0] -x1, y2 = rect[3] + rect[1] -y1;
            for (int i = x1; i < x2; i++){
                for (int j = y1; j < y2; j++){
                    grid[i][j] = !grid[i][j];
                }
            }
        }
        for (int i = 0; i < 100; i++){
            for (int j = 0; j < 100; j++){
                if (grid[i][j])
                    count--;
            }
        }
        return count;
    }
}

2. 最长坚持时间

五个人五排最长时间,n部手机

贪心输出:50 优化后:循环里每次time++,而不是time += minTime,就过了100

public int maxTime (int[] batteries) {
    // write code here
    int time = 0;
    int n = batteries.length;
    PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->(b-a));
    for (int bat : pq){
        pq.offer(bat);
    }
    int a = 0, b = 0, c = 0, d = 0, e = 0;
    while (true){
        a = pq.peek();
        pq.poll();
        b = pq.peek();
        pq.poll();
        c = pq.peek();
        pq.poll();
        d = pq.peek();
        pq.poll();
        e = pq.peek();
        pq.poll();
        if (a== 0 || b == 0 || c== 0 || d == 0 || e == 0)
            break;
        time++;
        a--;
        b--;
        c--;
        d--;
        e--;
        pq.offer(a);
        pq.offer(b);
        pq.offer(b);
        pq.offer(b);
        pq.offer(b);
    }
    return time;