当前位置:网站首页>每日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;
}
}
边栏推荐
猜你喜欢

What kind of air conditioner is this?

NAACL 2022 | TAMT:通过下游任务无关掩码训练搜索可迁移的BERT子网络

新华三的千亿企业梦,还得靠吃ICT老本来实现?

关于接口测试自动化的总结与思考

对半查找(折半查找)

Hardware development notes (VII): basic process of hardware development, making a USB to RS232 module (VI): creating 0603 package and associating principle graphic devices

Explore tidb lightning source code to solve the found bugs

Openhgnn releases version 0.3

Domestic database disorder

How to choose LAN instant messaging software
随机推荐
Quickly set up a website to visit foreign countries, set up SS and start BBR to quickly surf the Internet
Prometheus 2.26.0 新特性
Realization of hospital medical record management system based on JSP
#yyds干货盘点# 解决剑指offer:剪绳子(进阶版)
《预训练周刊》第51期:重构预训练、零样本自动微调、一键调用OPT
scrapy
爱可可AI前沿推介(6.27)
命令行编辑器 sed 基础用法总结
线程同步之信号量
重读经典:《The Craft of Research(1)》
Array related knowledge
赛迪顾问发布《“十四五” 关键应用领域之数据库市场研究报告》(附下载)
外包2年的我终于上岸了!记录我的字节跳动3轮面试,希望帮助到大家!
每日刷題記錄 (六)
对半查找(折半查找)
一道shell脚本的统计题
Completely solve the problem of Chinese garbled code in Web Engineering at one time
Daily question brushing record (6)
Yyds dry goods inventory solution sword finger offer: cut rope (advanced version)
Today's sleep quality record 78 points