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

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

找到最近的相同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(1)
目录
相关文章
|
4月前
【每日一题Day290】LC1281整数的各位积和之差 | 模拟
【每日一题Day290】LC1281整数的各位积和之差 | 模拟
16 0
|
4月前
【每日一题Day285】LC980不同路径 III | 回溯
【每日一题Day285】LC980不同路径 III | 回溯
20 0
|
4月前
【每日一题Day119】LC1250检查好数组 | 数学
【每日一题Day119】LC1250检查好数组 | 数学
28 0
|
4月前
【每日一题Day345】LC2562找出数组的串联值 | 模拟
【每日一题Day345】LC2562找出数组的串联值 | 模拟
19 0
|
4月前
【每日一题Day258】LC2532过桥的时间 | 模拟 优先队列
【每日一题Day258】LC2532过桥的时间 | 模拟 优先队列
26 0
|
4月前
|
算法
【每日一题Day297】LC2682找出转圈游戏输家 | 模拟+哈希表
【每日一题Day297】LC2682找出转圈游戏输家 | 模拟+哈希表
31 0
|
4月前
【每日一题Day308】LC57插入区间 | 模拟
【每日一题Day308】LC57插入区间 | 模拟
20 0
|
4月前
|
前端开发
【每日一题Day228】LC2460对数组执行操作 | 模拟+双指针
【每日一题Day228】LC2460对数组执行操作 | 模拟+双指针
19 0
|
4月前
【每日一题Day353】LC2525根据规则将箱子分类 | 模拟
【每日一题Day353】LC2525根据规则将箱子分类 | 模拟
14 0
|
4月前
|
测试技术 索引
【每日一题Day296】LC833字符串中的查找与替换 | 排序+模拟
【每日一题Day296】LC833字符串中的查找与替换 | 排序+模拟
19 0