Skip to content

Latest commit

 

History

History
56 lines (50 loc) · 1.1 KB

1779.找到最近的有相同-x-或-y-坐标的点.md

File metadata and controls

56 lines (50 loc) · 1.1 KB

1779.找到最近的有相同-x-或-y-坐标的点

/*
 * @lc app=leetcode.cn id=1779 lang=typescript
 *
 * [1779] 找到最近的有相同 X 或 Y 坐标的点
 */

// @lc code=start
function nearestValidPoint(x: number, y: number, points: number[][]): number {}
// @lc code=end

解法 1: 枚举

function nearestValidPoint(x: number, y: number, points: number[][]): number {
  let res = -1,
    min = Infinity
  for (let [i, [a, b]] of points.entries()) {
    if (a !== x && b !== y) continue
    const d = Math.abs(x - a) + Math.abs(y - b)
    if (d < min) {
      min = d
      res = i
    }
  }
  return res
}

Case

test.each([
  {
    input: {
      x: 3,
      y: 4,
      points: [
        [1, 2],
        [3, 1],
        [2, 4],
        [2, 3],
        [4, 4],
      ],
    },
    output: 2,
  },
  { input: { x: 3, y: 4, points: [[3, 4]] }, output: 0 },
  { input: { x: 3, y: 4, points: [[2, 3]] }, output: -1 },
])('input: x = $input.x, y = $input.y, points = $input.points', ({ input: { x, y, points }, output }) => {
  expect(nearestValidPoint(x, y, points)).toEqual(output)
})