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
就當偽碼看了,反正是這意思,這樣遍歷次數最少。
相關文章:
