【每日一题Day43】LC1779找到最近的相同X和相同Y的点 | 模拟

本文介绍了一个算法问题:在二维平面上找到与指定位置共享相同X或Y坐标的最近点,并给出了具体的实现方法。

找到最近的相同X和相同Y的点【LC1779】

You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.

Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.

The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).

就是很奇怪 csdn发布文章总是要用手机的热点 校园网就进不来

  • 思路:遍历points数组,当point的横坐标与x相等或者纵坐标与y相等时,计算其与给定点的曼哈顿距离,返回距离最小的point的index即可

  • 实现

    class Solution {
        public int nearestValidPoint(int x, int y, int[][] points) {
            int minIndex = -1;
            int minDis = Integer.MAX_VALUE;
            for (int i = 0; i < points.length; i++){
                if (points[i][0] == x || points[i][1] == y){
                    int dis = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);
                    if (dis < minDis){
                        minIndex = i;
                        minDis = dis;
                    }
                }
            }
            return minIndex;
    
        }
    }
    
    • 复杂度

      • 时间复杂度:O(logn)O(log n)O(logn)
      • 空间复杂度:O(1)O(1)O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值