LeetCode 1637. 两点之间不包含任何点的最宽垂直区域

【LetMeFly】1637.两点之间不包含任何点的最宽垂直面积

力扣题目链接:https://leetcode.cn/problems/widest-vertical-area-between-two-points-containing-no-points/

给你 n 个二维平面上的点 points ,其中 points[i] = [xi, yi] ,请你返回两点之间内部不包含任何点的 最宽垂直面积 的宽度。

垂直面积 的定义是固定宽度,而 y 轴上无限延伸的一块区域(也就是高度为无穷大)。 最宽垂直面积 为宽度最大的一个垂直面积。

请注意,垂直区域 边上 的点 不在 区域内。

示例 1:

输入:points = [[8,7],[9,9],[7,4],[9,7]]
输出:1
解释:红色区域和蓝色区域都是最优区域。

示例 2:

输入:points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
输出:3

提示:

  • n == points.length
  • 2 <= n <= 105
  • points[i].length == 2
  • 0 <= xi, yi <= 109

方法一:排序 / Set

这道题只需要考虑横坐标。

将所有的横坐标排序后,间隔最远的横坐标就是答案。

(当然,也可以使用有序集合(底层是红黑树)来实现)

emm,总觉得这中文版题目描述不太完美,“最宽区域”,我选 [ 1000000000 , + ∞ ) [1000000000, +\infty) [1000000000,+)不行么

  • 时间复杂度 O ( n log ⁡ n ) O(n\log n) O(nlogn)
  • 空间复杂度 O ( log ⁡ n ) O(\log n) O(logn) O ( d i f f ( p o i n t s [ 0 ] ) ) O(diff(points[0])) O(diff(points[0]))(不同的横坐标的个数,也可以理解为 O ( n ) O(n) O(n)

AC代码

C++

class Solution {
    
    
public:
    int maxWidthOfVerticalArea(vector<vector<int>>& points) {
    
    
        set<int> se;
        for (vector<int>& point : points) {
    
    
            se.insert(point[0]);
        }
        int ans = 0;
        int last = *se.begin();
        for (int t : se) {
    
    
            ans = max(ans, t - last);
            last = t;
        }
        return ans;
    }
};

Python

# from typing import List
"""Python的set是无序的"""

class Solution:
    def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
        x = [p[0] for p in points]
        x.sort()
        return max(x[i] - x[i - 1] for i in range(1, len(x)))

同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/129851128

猜你喜欢

转载自blog.csdn.net/Tisfy/article/details/129851128