已知有很多会议,如果这些会议的时间有重叠,则将他们合并.
例如,有一个会议的时间为下午3点到下午5点,另外一个会议的时间为下午4点到6点,那么合并之后的会议时间为下午3点到6点。
func mergeSort(_ arr : [MeetingTime]) -> [MeetingTime]{
var arr = arr
guard arr.count > 0 else{
return []
}
arr.sort { (time1, time2) -> Bool in
if time1.start != time2.start{
return time1.start < time2.start
}else{
return time1.end < time2.end
}
}
for item in arr{
print("\(item.start):\(item.end)")
}
//定义一个数组 用来装合并后的值
var res = [MeetingTime]()
res.append(arr[0])
for i in 1...arr.count - 1{
let current = arr[i]
let last = res.last!
if current.start > last.end{
res.append(current)
}else{
last.end = max(last.end,current.end)
}
}
return res
}
class MeetingTime{
var start : Int
var end : Int
public init(_ start : Int,_ end : Int){
self.start = start
self.end = end
}
}
var arr = [MeetingTime]()
let time1 = MeetingTime(0, 1)
let time2 = MeetingTime(1, 2)
let time3 = MeetingTime(9, 10)
let time4 = MeetingTime(4, 6)
let time5 = MeetingTime(5, 8)
let time6 = MeetingTime(1, 2)
let time7 = MeetingTime(18, 20)
let time8 = MeetingTime(22, 21)
arr.append(time1)
arr.append(time2)
arr.append(time3)
arr.append(time4)
arr.append(time5)
arr.append(time6)
arr.append(time7)
arr.append(time8)
let res = mergeSort(arr)
print("-------归并结果--------")
for item in res{
print("\(item.start):\(item.end)")
}
打印结果:
0:1
1:2
1:2
4:6
5:8
9:10
18:20
22:21
-------归并结果--------
0:2
4:8
9:10
18:20
22:21











网友评论