当前位置:网站首页>[leetcode daily question] install fence

[leetcode daily question] install fence

2022-04-23 15:26:00 Oysters brought the sea to Chicago

Install fence
difficulty : difficult
 Insert picture description here
 Insert picture description here

The code is as follows :

class Solution {
    
    int[] subtraction(int[] a, int[] b) {
     //  Vector subtraction 
        return new int[]{
    a[0] - b[0], a[1] - b[1]};
    }
    double cross(int[] a, int[] b) {
     //  Cross riding 
        return a[0] * b[1] - a[1] * b[0];
    }
    double getArea(int[] a, int[] b, int[] c) {
     //  vector  ab  To   vector  ac  The area swept in the process 
        return cross(subtraction(b, a), subtraction(c, a));
    }
    public int[][] outerTrees(int[][] trees) {
    
        Arrays.sort(trees, (a, b)->{
    
            return a[0] != b[0] ? a[0] - b[0] : a[1] - b[1];
        });
        int n = trees.length, tp = 0;
        int[] stk = new int[n + 10];
        boolean[] vis = new boolean[n + 10];
        stk[++tp] = 0; //  Do not mark the starting point 
        for (int i = 1; i < n; i++) {
    
            int[] c = trees[i];
            while (tp >= 2) {
    
                int[] a = trees[stk[tp - 1]], b = trees[stk[tp]];
                if (getArea(a, b, c) < 0) vis[stk[tp--]] = false;
                else break;
            }
            stk[++tp] = i;
            vis[i] = true;
        }
        int size = tp;
        for (int i = n - 1; i >= 0; i--) {
    
            if (vis[i]) continue;
            int[] c = trees[i];
            while (tp > size) {
    
                int[] a = trees[stk[tp - 1]], b = trees[stk[tp]];
                if (getArea(a, b, c) < 0) {
    
                    // vis[stk[tp--]] = false; //  Not necessary 
                    tp--;
                }
                else break;
            }
            stk[++tp] = i;
            // vis[i] = true; //  Not necessary 
        }
        int[][] ans = new int[tp - 1][2];
        for (int i = 1; i < tp; i++) ans[i - 1] = trees[stk[i]];
        return ans;
    }
}

 Insert picture description here

版权声明
本文为[Oysters brought the sea to Chicago]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231524468787.html