当前位置:网站首页>每日3题(1):找到最近的有相同 X 或 Y 坐标的点
每日3题(1):找到最近的有相同 X 或 Y 坐标的点
2022-06-27 13:34:00 【程序猿不脱发2】
题目:
给你两个整数 x 和 y ,表示你在一个笛卡尔坐标系下的 (x, y) 处。同时,在同一个坐标系下给你一个数组 points ,其中 points[i] = [ai, bi] 表示在 (ai, bi) 处有一个点。当一个点与你所在的位置有相同的 x 坐标或者相同的 y 坐标时,我们称这个点是 有效的 。
请返回距离你当前位置 曼哈顿距离 最近的 有效 点的下标(下标从 0 开始)。如果有多个最近的有效点,请返回下标 最小 的一个。如果没有有效点,请返回 -1 。
两个点 (x1, y1) 和 (x2, y2) 之间的 曼哈顿距离 为 abs(x1 - x2) + abs(y1 - y2) 。
示例 1:
输入:x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
输出:2
解释:所有点中,[3,1],[2,4] 和 [4,4] 是有效点。有效点中,[2,4] 和 [4,4] 距离你当前位置的曼哈顿距离最小,都为 1 。[2,4] 的下标最小,所以返回 2 。
示例 2:
输入:x = 3, y = 4, points = [[3,4]]
输出:0
提示:答案可以与你当前所在位置坐标相同。
示例 3:
输入:x = 3, y = 4, points = [[2,3]]
输出:-1
解释:没有 有效点。
提示:
1 <= points.length <= 10^4
points[i].length == 2
1 <= x, y, ai, bi <= 10^4
思路:
遍历,记录有效点,保留最小值的下标
java代码:
class Solution {
public int nearestValidPoint(int x, int y, int[][] points) {
int m = points.length;
int minLength = Integer.MAX_VALUE;
int minPoint = -1;
for (int i = 0; i < m; i++) {
if (x == points[i][0] || y == points[i][1]) {
if (minLength > Math.abs(x - points[i][0]) + Math.abs(y - points[i][1])) {
minLength = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);
minPoint = i;
}
}
}
return minPoint;
}
}
边栏推荐
- OpenHGNN发布0.3版本
- Journal quotidien des questions (6)
- Summary and Thinking on interface test automation
- Hue new account error reporting solution
- Can flush open an account for stock trading? Is it safe?
- crane:字典项与关联数据处理的新思路
- How to set postman to Chinese? (Chinese)
- 防火墙基础之华为华三防火墙web页面登录
- NAACL 2022 | TAMT:通过下游任务无关掩码训练搜索可迁移的BERT子网络
- MySQL index and its classification
猜你喜欢
随机推荐
7 killer JS lines of code
Quick news: Huawei launched the Hongmeng developer competition; Tencent conference released the "Wanshi Ruyi" plan
Pytorch learning 1 (learning documents on the official website)
dynamic programming
AGCO AI frontier promotion (6.27)
IJCAI 2022 | 用一行代码大幅提升零样本学习方法效果,南京理工&牛津提出即插即用分类器模块
How ASP connects Excel
每日刷题记录 (六)
jvm 性能调优、监控工具 -- jps、jstack、jmap、jhat、jstat、hprof
Openhgnn releases version 0.3
#yyds干货盘点# 解决剑指offer:剪绳子(进阶版)
防火墙基础之华为华三防火墙web页面登录
快讯:华为启动鸿蒙开发者大赛;腾讯会议发布“万室如意”计划
A pang's operation record
Type 'image' is not a subtype of type 'imageprovider < object > solution
What kind of air conditioner is this?
Interviewer: do you understand redis' shared object pool?
Awk concise tutorial
POSIX AIO -- Introduction to glibc version asynchronous IO
类模板中可变参的逐步展开