javascript - python小算法
問題描述
有個日期字符串list,如下:
lst = [’2017-06-01’, ’2017-06-08’, ’2017-06-15’, ’2017-06-22’, ’2017-06-29’, ...]
求s = [’2017-06-09’]與lst中哪個日期字符串最相近
思路1:將s和lst的值轉換為日期,遍歷比較相差的秒數,最小的就是要找的日期字符串。
有沒有更好的實現方法??
問題解答
回答1:我給個思路給你參考下lst.append(s)lst.sort()num=lst.index(s)然后比較lst[num-1]和lst[num+1]這兩個相差的秒數,小的一個就是結果,這樣就不用遍歷算時間戳了。覺得不錯就給贊加采納吧。
回答2:將日期通過去掉-轉換為整數, 再分別與s中日期相減,得到絕對值最小的數為最相近的日期.
# Python codelst = [’2017-06-01’, ’2017-06-08’, ’2017-06-15’, ’2017-06-22’, ’2017-06-29’]s = [’2017-06-09’]date = [’’.join(x.split(’-’)) for x in lst]datetoint = [int(x) for x in date]gaps = [abs(x - int(’’.join(s[0].split(’-’)))) for x in datetoint]mostrecentdate = lst[gaps.index(min(gaps))]print(mostrecentdate)回答3:
感覺lz的意思是不要遍歷lst,不管是sort還是通減其實都發生了遍歷應該用二分法吧,大概是這意思
i = 0j = len(list)while True: index = (i + j) / 2 if s > lst[index]:i = index else:j = index continue
就當偽碼看了,反正是這意思,這樣遍歷次數最少。
相關文章:
1. css - 關于偽類背景問題2. html - 移動端radio無法選中3. apache - 怎么給localhost后面默認加上8080端口4. html5 - 如何實現圖中的刻度漸變效果?5. python - django的模板預加載6. mysql - 數據庫建字段,默認值空和empty string有什么區別 1107. python 計算兩個時間相差的分鐘數,超過一天時計算不對8. 關于Navicat連接到mysql,我改了root的密碼后,Navicat連接報錯1862?9. mysql起不來了,為什么?10. windows-7 - Win7中Vmware Workstatoin與Xampp中Apache服務器端口沖突?
