Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 587. Erect the Fence

Rain Hu

587. Erect the Rence


一、題目

You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden. You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Return the coordinates of trees that are exactly located on the fence perimeter.

Example 1:

Example 2:

Constraints:


二、分析

illustration

三、解題

1. Math

bool biggerSlope(vector<int>& a, vector<int>& b, vector<int>& c) {
    // slope of ab compares with slope of ac
    return (b[1]-a[1])*(c[0]-a[0]) < (b[0]-a[0])*(c[1]-a[1]);
}
vector<vector<int>> outerTrees(vector<vector<int>>& trees) {
    int n = trees.size();
    vector<vector<int>> res;
    sort(trees.begin(), trees.end());

    for (int i = 0; i < n; i++) {
        while (res.size() > 1 && biggerSlope(res[res.size()-2], res.back(), trees[i]))
            res.pop_back();
        res.push_back(trees[i]);
    }
    if (res.size() == n) return res;

    for (int i = n-2; i >= 0; i--) {
        while (res.size() > 1 && biggerSlope(res[res.size()-2], res.back(), trees[i]))
            res.pop_back();
        res.push_back(trees[i]);           
    }
    res.pop_back();
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 337. House Robber III
Next
[LeetCode] 322. Coin Change