1503. Last Moment Before All Ants Fall Out of a Plank
leetcode medium
Task
У нас есть деревянная доска длиной n единиц. Некоторые муравьи ходят по доске, каждый муравей движется со скоростью 1 единица в секунду. Некоторые муравьи движутся влево, другие движутся вправо.
Когда два муравья, движущиеся в разных направлениях, встречаются в какой-то точке, они меняют свои направления и продолжают двигаться дальше. Предполагается, что изменение направлений не занимает дополнительного времени.
Когда муравей достигает одного из концов доски в момент времени t, он сразу же падает с доски.
Дано целое число n и два целых массива left и right, обозначающие позиции муравьев, движущихся влево и вправо соответственно. Верните момент, когда последний(е) муравей(и) падает(ют) с доски.
Пример:
Input: n = 4, left = [4,3], right = [0,1]
Output: 4
Explanation: In the image above:
-The ant at index 0 is named A and going to the right.
-The ant at index 1 is named B and going to the right.
-The ant at index 3 is named C and going to the left.
-The ant at index 4 is named D and going to the left.
The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).
C# solution
matched/originalpublic class Solution {
public int GetLastMoment(int n, int[] left, int[] right) {
int ans = 0;
foreach (int num in left) {
ans = Math.Max(ans, num);
}
foreach (int num in right) {
ans = Math.Max(ans, n - num);
}
return ans;
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int GetLastMoment(int n, vector<int>& left, vector<int>& right) {
int ans = 0;
foreach (int num in left) {
ans = max(ans, num);
}
foreach (int num in right) {
ans = max(ans, n - num);
}
return ans;
}
}Java solution
auto-draft, review before submitimport java.util.*;
import java.math.*;
// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
public int GetLastMoment(int n, int[] left, int[] right) {
int ans = 0;
foreach (int num in left) {
ans = Math.max(ans, num);
}
foreach (int num in right) {
ans = Math.max(ans, n - num);
}
return ans;
}
}JavaScript solution
matched/originalvar getLastMoment = function(n, left, right) {
let ans = 0
for (let num of left) {
ans = Math.max(ans, num)
}
for (let num of right) {
ans = Math.max(ans, n - num)
}
return ans
}Python solution
matched/originalclass Solution:
def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:
ans = 0
for num in left:
ans = max(ans, num)
for num in right:
ans = max(ans, n - num)
return ansGo solution
matched/originalfunc getLastMoment(n int, left []int, right []int) int {
ans := 0
for _, num := range left {
if num > ans {
ans = num
}
}
for _, num := range right {
if n - num > ans {
ans = n - num
}
}
return ans
}Explanation
Algorithm
Инициализируйте переменную ans значением 0.
Итерация по массиву left и обновление ans значением num, если оно больше текущего значения ans.
Итерация по массиву right и обновление ans значением n - num, если оно больше текущего значения ans. Верните значение ans.
😎