Today, I saw a common problem in the Q & A: algorithm (merging overlapping time segments)
Here we will first describe the problem:
Merge consecutive time periods in the same day, such:
Starttime endtime
06:10:58 08:15:28
07:38:56 10:34:45
10:55:00 11:34:00
13:09:34 17:45:23
14:23:12 15:24:14
16:14:25 17:52:15
...
After merging:
Starttime endtime
06:10:58 10:34:45
10:55:00 11:34:00
13:09:34 17:52:15
...
Avoid the occurrence of N ^ 2 In case of time complexity, that is, compare any element in the set with other elements once.
This is a common problem. I will post my answers for you to make a picture.Algorithm
Code:
Public Class Bw22617
{
Private List < Betime > Timelist = New List < Betime > (){
New Betime {begintime = New Datetime ( 2011 , 3 , 1 , 10 , 55 , 0 ), Endtime = New Datetime ( 2011 , 3 , 1 , 11 , 34 , 0 )},
New Betime {begintime = New Datetime ( 2011 , 3 , 1 , 13 , 9 , 34 ), Endtime = New Datetime ( 2011 , 3 , 1 , 17 , 45 , 23 )},
New Betime {begintime = New Datetime ( 2011 , 3 , 1 , 14 , 23 , 12 ), Endtime = New Datetime ( 2011 , 3 , 1 , 15 , 24 , 14 )},
New Betime {begintime = New Datetime ( 2011 , 3 , 1 , 7 , 38 , 56 ), Endtime = New Datetime ( 2011 , 3 , 1 , 10 , 34 , 45 )},
New Betime {begintime = New Datetime ( 2011 , 3 , 1 , 6 , 10 , 58 ), Endtime = New Datetime ( 2011 , 3 , 1 , 8 , 15 , 28 )},
New Betime {begintime = New Datetime ( 2011 , 3 , 1 , 16 , 14 , 25 ), Endtime = New Datetime ( 2011 , 3 , 1 , 17 , 52 , 15 )}
};
Public Void Union ()
{
// Sort data first
Timelist = Timelist. orderby (P => P. begintime). tolist < Betime > ();
For ( Int I = 0 ; I < Timelist. Count - 1 ; I ++ )
{
Int J = I + 1 ;
If (Timelist [I]. endtime > = Timelist [J]. begintime)
{
// The end time of the last data record is smaller than the end time of the previous data record.
If (Timelist [I]. endtime > = Timelist [J]. endtime)
{
Timelist [J] = Timelist [I];
}
Else
{
Timelist [J]. begintime = Timelist [I]. begintime;
}
Timelist [I] = Null ;
}
Else
{
I ++ ;
}
}
Timelist. foreach (
Delegate (Betime P)
{
If (P ! = Null )
{
Console. writeline ( " Begintime: " + P. begintime + " \ Tendtime: " + P. endtime );
}
}
);
}
}
Public Class Betime
{
Public Datetime begintime { Get ; Set ;}
Public Datetime endtime { Get ; Set ;}
}
Call Code (very simple ):
Static Void Main ( String [] ARGs)
{
Bw22617 Test = New Bw22617 ();
Test. Union ();
Console. Read ();
}
Result:
You are welcome to propose more efficient algorithms!
Thank you very much for your comments.ProgramThere is indeed a problem, mainly when the end time of the second data is smaller than the end time of the first data and the data is not sorted, it has been changed