Sponsored
Sponsored
In this approach, you perform a left-to-right scan to compute the distance to the nearest occupied seat on the left and a right-to-left scan to compute the distance to the nearest occupied seat on the right. For each empty seat, the result will be the minimum of these distances. The final solution is the maximum among these minimum distances.
Time Complexity: O(n) where n is the number of seats. We pass over the list twice.
Space Complexity: O(n) due to the use of additional arrays for storing distances.
1using System;
2
3public class Solution {
4 public int MaxDistToClosest(int[] seats) {
5 int n = seats.Length;
6 int[] left = new int[n];
7 int[] right = new int[n];
8
9 for (int i = 0, last = -1; i < n; ++i) {
10 if (seats[i] == 1) last = i;
11 else left[i] = (last == -1) ? n : i - last;
12 }
13
14 for (int i = n - 1, last = -1; i >= 0; --i) {
15 if (seats[i] == 1) last = i;
16 else right[i] = (last == -1) ? n : last - i;
17 }
18
19 int maxDist = 0;
20 for (int i = 0; i < n; ++i) {
21 if (seats[i] == 0) {
22 maxDist = Math.Max(maxDist, Math.Min(left[i], right[i]));
23 }
24 }
25
26 return maxDist;
27 }
28
29 public static void Main(string[] args) {
30 int[] seats = { 1, 0, 0, 0, 1, 0, 1 };
31 Solution sol = new Solution();
32 Console.WriteLine(sol.MaxDistToClosest(seats));
33 }
34}
The C# solution is also structured around determining distances from the nearest people to the left and right, using two separate arrays for storing those distances.
This approach involves using a single pass over the seats array while utilizing two pointers. The first pointer stores the last filled seat position, and with each empty seat, the calculation is made based on its distance from the last filled position and the subsequent fill.
Time Complexity: O(n) for a single traversal.
Space Complexity: O(1) since it uses a constant amount of space.
1
public class Solution {
public int MaxDistToClosest(int[] seats) {
int prev = -1, future = 0, maxDist = 0;
for (int i = 0; i < seats.Length; ++i) {
if (seats[i] == 1) {
prev = i;
} else {
while (future < seats.Length && (seats[future] == 0 || future < i)) {
future++;
}
int leftDist = (prev == -1) ? seats.Length : i - prev;
int rightDist = (future == seats.Length) ? seats.Length : future - i;
int minDist = Math.Min(leftDist, rightDist);
maxDist = Math.Max(maxDist, minDist);
}
}
return maxDist;
}
public static void Main(string[] args) {
int[] seats = { 1, 0, 0, 0, 1, 0, 1 };
Solution sol = new Solution();
Console.WriteLine(sol.MaxDistToClosest(seats));
}
}
The C# solution mirrors these techniques within the language's syntax, generally computing distances within a single linear pass.