image.png

    1. class Solution {
    2. public int[][] outerTrees(int[][] trees) {
    3. int n = trees.length;
    4. if (n < 4) {
    5. return trees;
    6. }
    7. /* 按照 x 大小进行排序,如果 x 相同,则按照 y 的大小进行排序 */
    8. Arrays.sort(trees, (a, b) -> {
    9. if (a[0] == b[0]) {
    10. return a[1] - b[1];
    11. }
    12. return a[0] - b[0];
    13. });
    14. List<Integer> list = new ArrayList<>();
    15. boolean[] used = new boolean[n];
    16. /* list[0] 需要入栈两次,不进行标记 */
    17. list.add(0);
    18. /* 求出凸包的下半部分 */
    19. for (int i = 1; i < n; i++) {
    20. while (list.size() > 1 && cross(trees[list.get(list.size() - 2)], trees[list.get(list.size() - 1)], trees[i]) < 0) {
    21. used[list.get(list.size() - 1)] = false;
    22. list.remove(list.size() - 1);
    23. }
    24. used[i] = true;
    25. list.add(i);
    26. }
    27. int m = list.size();
    28. /* 求出凸包的上半部分 */
    29. for (int i = n - 2; i >= 0; i--) {
    30. if (!used[i]) {
    31. while (list.size() > m && cross(trees[list.get(list.size() - 2)], trees[list.get(list.size() - 1)], trees[i]) < 0) {
    32. used[list.get(list.size() - 1)] = false;
    33. list.remove(list.size() - 1);
    34. }
    35. used[i] = true;
    36. list.add(i);
    37. }
    38. }
    39. /* list[0] 同时参与凸包的上半部分检测,因此需去掉重复的 list[0] */
    40. list.remove(list.size() - 1);
    41. int size = list.size();
    42. int[][] res = new int[size][2];
    43. for (int i = 0; i < size; i++) {
    44. res[i] = trees[list.get(i)];
    45. }
    46. return res;
    47. }
    48. /*比较斜率是否为左拐,大于0说明是左拐
    49. * (x2-x1)/(y2-y1) - (x3-x2)/(y3-y2) = (x2-x1)(y3-y2) - (x3-x2)(y2-y1)
    50. * */
    51. private int cross(int[] p, int[] q, int[] r) {
    52. return (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0]);
    53. }
    54. }

    587