3516. Find Closest Person #2132
-
Topics: You are given three integers
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:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine which of two people (Person 1 or Person 2) reaches a third person (Person 3) first when both are moving towards Person 3 at the same speed. The solution involves comparing the distances each person has to travel to reach Person 3. The person with the shorter distance will arrive first. If both distances are equal, they arrive at the same time. Approach
Let's implement this solution in PHP: 3516. Find Closest Person <?php
/**
* @param Integer $x
* @param Integer $y
* @param Integer $z
* @return Integer
*/
function findClosest($x, $y, $z) {
$dist1 = abs($x - $z);
$dist2 = abs($y - $z);
if ($dist1 < $dist2) {
return 1;
} elseif ($dist2 < $dist1) {
return 2;
} else {
return 0;
}
}
// ---------- Example test cases ----------
// Example 1
echo findClosest(2, 7, 4) . "\n"; // Output: 1
// Example 2
echo findClosest(2, 5, 6) . "\n"; // Output: 2
// Example 3
echo findClosest(1, 5, 3) . "\n"; // Output: 0
?> Explanation:
This approach efficiently checks the necessary conditions by leveraging basic arithmetic and comparison operations, ensuring correctness and simplicity. The solution handles all edge cases, including when the distances are equal, and processes the inputs in constant time, making it optimal for the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to determine which of two people (Person 1 or Person 2) reaches a third person (Person 3) first when both are moving towards Person 3 at the same speed. The solution involves comparing the distances each person has to travel to reach Person 3. The person with the shorter distance will arrive first. If both distances are equal, they arrive at the same time.
Approach