力扣 1610. 可见点的最大数目

题目来源:https://leetcode-cn.com/problems/maximum-number-of-visible-points/

大致题意:
给定一个坐标,和角度 angle,以及一组点。返回以坐标为圆心,在给定角度 angle 可以任意旋转,半径可以为无限大的情况下,所能覆盖的最多点的数目

思路

  1. 以给定坐标为原点,将给定的点处理为极坐标点,并通过 atan2 函数将坐标转化为角度
  2. 二分寻找 (degree, degree + angle)能覆盖的最多点的数目
  3. 因为 degree + angle 值可能大于 2π,所以可以再存下将所有的点加上 2π

代码:

public int visiblePoints(List<List<Integer>> points, int angle, List<Integer> location) {
        List<Double> polarDegrees = new ArrayList<>();
        int locationX = location.get(0);
        int locationY = location.get(1);
        // 与给定坐标重合点的数目
        int samePointCount = 0;
        for (List<Integer> point : points) {
            int x = point.get(0);
            int y = point.get(1);
            // 如果与坐标重合,统计并进行下轮循环
            if (x == locationX && y == locationY) {
                samePointCount++;
                continue;
            }
            // 处理为相对于坐标的极坐标点的角度
            polarDegrees.add(Math.atan2(x - locationX, y - locationY));
        }
        // 排序,即按照角度升序排序
        Collections.sort(polarDegrees);
        int m = polarDegrees.size();
        // 为了防止越界,再将原角度加上 2 PI 
        for (int i = 0; i < m; i++) {
            polarDegrees.add(polarDegrees.get(i) + 2 * Math.PI);
        }
        int maxCount = 0;
        // 将给定角度转化为 PI
        double degree = angle * Math.PI / 180;
        for (int i = 0; i < m; i++) {
            // 二分查找以当前角度 i 为下界,i + degree 为上界的角度范围内覆盖的角度个数,也就是点个数
            int count = binarySearch(polarDegrees, polarDegrees.get(i) + degree) - i;
            // 更新最大值
            maxCount = Math.max(maxCount, count);
        }
        return maxCount + samePointCount;
    }

    public int binarySearch(List<Double> nums, double target) {
        int left = 0;
        int right = nums.size() - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums.get(mid) <= target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三更鬼

谢谢老板!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值