中级农民
- 积分
- 113
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-3-30
- 最后登录
- 1970-1-1
|
话不多说,直接上代码,请指教
- def longestPoolChain(intervals)
- sortedIntervals = intervals.sort_by(&:first) # 假设给的arry是乱序的,如果根据timestamp顺序过来,这个sort可以省
- pools = []
- map = {}
-
- sortedIntervals.each do |interval|
- driverId = interval[1]
- if map.key?(driverId)
- pools << [map[driverId], interval]
- map.delete(driverId)
- else
- map[driverId] = interval
- end
- end
- sortedPools = pools.sort_by {|pool| pool[0][0]}
- head, tail = sortedPools[0]
- currentPools = 1
- maxPools = 1
- (1...sortedPools.size).each do |i|
- pool = sortedPools[i]
- if pool[0][0] <= tail[0]
- head = [head, pool[0]].max_by(&:first)
- tail = [tail, pool[1]].min_by(&:first)
- currentPools += 1
- maxPools = [maxPools, currentPools].max
- else
- head, tail = pool
- currentPools = 1
- end
- end
- maxPools
- end
- logs = [[101, 1, 1, "P"], [102, 1, 1, "D"], [105, 3, 3, "P"],
- [107, 2, 2, "P"], [109, 2, 2, "D"], [111, 3, 3, "D"],
- [115, 1, 1, "P"], [120, 1, 1, "D"]]
- p longestPoolChain(logs) # 2
复制代码
居然没有ruby语言选择,不知道能不能高亮[/i] |
|