LeetCode-in-Java

4024. Nearest Available Drone

Easy

You are given a 2D integer array drones, where drones[i] = [xi, yi, rangei] represents the x-coordinate, y-coordinate, and travel range of the ith drone.

You are also given an integer array target = [tx, ty], representing the coordinates of the target.

A drone drones[i] can reach the target if the Manhattan distance between its coordinates and the target coordinates is less than or equal to its rangei.

Return the index of the reachable drone with the minimum Manhattan distance to the target. If there is a tie, return the smallest index. If no drone can reach the target, return -1.

Example 1:

Input: drones = [[0,0,8],[2,2,9]], target = [3,4]

Output: 1

Explanation:

Example 2:

Input: drones = [[2,1,5],[4,4,5],[6,6,8]], target = [5,5]

Output: 1

Explanation:

Example 3:

Input: drones = [[4,4,5]], target = [8,6]

Output: -1

Explanation:

Constraints:

Solution

public class Solution {
    public int nearestDrone(int[][] drones, int[] target) {
        int min = Integer.MAX_VALUE;
        int idx = -1;
        for (int i = 0; i < drones.length; i++) {
            int[] d = drones[i];
            int dist = Math.abs(target[0] - d[0]) + Math.abs(target[1] - d[1]);
            if (dist <= d[2] && min > dist) {
                min = dist;
                idx = i;
            }
        }
        return idx;
    }
}