LeetCode-in-Java

3516. Find Closest Person

Easy

You are given three integers x, y, and z, representing the positions of three people on a number line:

Both Person 1 and Person 2 move toward Person 3 at the same speed.

Determine which person reaches Person 3 first:

Return the result accordingly.

Example 1:

Input: x = 2, y = 7, z = 4

Output: 1

Explanation:

Since Person 1 reaches Person 3 first, the output is 1.

Example 2:

Input: x = 2, y = 5, z = 6

Output: 2

Explanation:

Since Person 2 reaches Person 3 first, the output is 2.

Example 3:

Input: x = 1, y = 5, z = 3

Output: 0

Explanation:

Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.

Constraints:

Solution

public class Solution {
    public int findClosest(int x, int y, int z) {
        int d1 = Math.abs(z - x);
        int d2 = Math.abs(z - y);
        if (d1 == d2) {
            return 0;
        } else if (d1 < d2) {
            return 1;
        } else {
            return 2;
        }
    }
}