Answered step by step
Verified Expert Solution
Question
1 Approved Answer
import java.util.ArrayList; import java.util.Comparator; class Train { int trainId; String arrivalTime; String departureTime; public Train ( int trainId, String arrivalTime, String departureTime ) { this.trainId
import java.util.ArrayList;
import java.util.Comparator;
class Train
int trainId;
String arrivalTime;
String departureTime;
public Train
int trainId, String arrivalTime, String departureTime
this.trainId
trainId;
this.arrivalTime
arrivalTime;
this.departureTime
departureTime;
class TrainScheduleManager
ArrayList trains;
public TrainScheduleManager
this.trains
new ArrayList
;
public void addTrain
int trainId, String arrivalTime, String departureTime
Train newTrain
new Train
trainId
arrivalTime departureTime
;
int index
binarySearchInsertPosition
arrivalTime
;
trains.add
index
newTrain
;
private int binarySearchInsertPosition
String targetArrivalTime
int low
;
int high
trainssize
;
while
low
high
int mid
low
high
low
;
String midArrivalTime
trainsget
mid
arrivalTime;
if
midArrivalTime
compareTo
targetArrivalTime
low
mid
;
else if
midArrivalTime
compareTo
targetArrivalTime
high
mid
;
else
Handle cases where arrival times are the same
unlikely for this problem
low
mid
;
Insert after duplicates
if any
return low;
Insert position
public void removeTrain
int trainId
for
int i
; i
trainssize
; i
if
trains
get
i
trainId
trainId
trains.remove
i
;
break;
public void displaySchedule
for
Train train : trains
System.out.println
Train ID:
traintrainId
Arrival:
trainarrivalTime
Departure:
traindepartureTime
;
public class Main
public static void main
String
args
TrainScheduleManager manager
new TrainScheduleManager
;
manager.addTrain
:
:
;
manager.addTrain
:
:
;
manager.addTrain
:
:
;
manager.addTrain
:
:
;
System.out.println
Initial Train Schedule:"
;
manager.displaySchedule
;
manager.removeTrain
;
System.out.println
Updated Train Schedule after removing Train
:
;
manager.displaySchedule
;
describe the algotithm used to solve this problem
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started