javascript - 求時(shí)間段之間的交集的最優(yōu)解
問題描述
判斷一段時(shí)間與一堆一段時(shí)間之間是否有交集。有與起止時(shí)間相同的判斷為有交集如
判斷 12:30:00--14:20:00與下列時(shí)間段是否有交集10:00:00-12:00:00, 12:10:00-12:50:00 , 14:30:00-15:00:00
轉(zhuǎn)換為時(shí)間戳然后一一循環(huán)比較
function is_cross($st1, $et1, $st2, $et2) {$status = $st2 - $st1;if ($status > 0) { $status2 = $st2 - $et1; if ($status2 >= 0) {return false; } else {return true; }} else { $status2 = $et2 - $st1; if ($status2 > 0) {return true; } else {return false; }} }
這能解決問題,但是求更優(yōu)的方法,最小的時(shí)間復(fù)雜度
問題解答
回答1:public function inter(){
$tar=[6,4]; if($tar[0]>$tar[1]){$temp=$tar[0];$tar[0]=$tar[1];$tar[1]=$temp; } $all=[[5,6],[7,9],[1,4],[3,1],[1,3],[8,7] ]; //排序 foreach ($all as &$v){if($v[0]>$v[1]){ $temp=$v[0]; $v[0]=$v[1]; $v[1]=$temp;} } foreach ($all as $k=>$v){$left=$tar[0]>$v[1];$right=$v[0]>$tar[1];if(!($left||$right)){ var_dump($v);} }}回答2:
將時(shí)間轉(zhuǎn)化為時(shí)間戳,然后-------對(duì)比。
回答3:如果這個(gè) 一堆一段時(shí)間 需要被多次使用: 可以用線段樹。一次使用時(shí)'一一對(duì)比'也不會(huì)更慢。
回答4:# -*- coding: utf-8 -*-def is_mixed(t1, t2): ’’’ 假定時(shí)間段格式是:'10:00:00-12:00:00' 判斷 t1,t2是否有交集 ’’’ s1, e1 = t1.split('-') s2, e2 = t2.split('-') if s1 > e2 and s2 > e1:return True if s2 > e1 and s1 > e2:return True return Falset1 = '12:30:00-04:20:00't2 = '03:00:00-22:23:00'if is_mixed(t1, t2): print '有交集!'else: print '木有交集!'
python版本,js應(yīng)該也是一樣的
回答5:轉(zhuǎn)換成時(shí)間戳能方便比較點(diǎn)回答6:
這樣可以從periods挑出和period有交集的時(shí)間段。
period = '12:30:00-14:20:00'periods = ['10:00:00-12:00:00', '12:10:00-12:50:00','14:30:00-15:00:00']print([x+’-’+y for [b,e] in [period.split('-')] for [x,y] in [p.split('-') for p in periods] if x<=e and y>=b])回答7:
把時(shí)間轉(zhuǎn)換為整型123000, 反向判斷a -- bc -- d 這兩個(gè)時(shí)間段,在什么情況下沒有交集
b < c
a > d
相關(guān)文章:
1. python - 有什么好的可以收集貨幣基金的資源?2. java - 為什么第一個(gè)線程已經(jīng)釋放了鎖,第二個(gè)線程卻不行?3. javascript - 關(guān)于<a>元素與<input>元素的JS事件運(yùn)行問題4. css3 - 我想要背景長(zhǎng)度變化,而文字不移動(dòng),要怎么修改呢5. MySQL中的enum類型有什么優(yōu)點(diǎn)?6. css3 - 純css實(shí)現(xiàn)點(diǎn)擊特效7. python - 啟動(dòng)Eric6時(shí)報(bào)錯(cuò):’qscintilla_zh_CN’ could not be loaded8. mysql - 記得以前在哪里看過一個(gè)估算時(shí)間的網(wǎng)站9. android下css3動(dòng)畫非常卡,GPU也不差啊10. 大家好,我想請(qǐng)問一下怎么做搜索欄能夠搜索到自己網(wǎng)站的內(nèi)容。
