生活随笔
收集整理的這篇文章主要介紹了
LeetCode 635. 设计日志存储系统(map)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
1. 題目
你將獲得多條日志,每條日志都有唯一的 id 和 timestamp,timestamp 是形如 Year:Month:Day:Hour:Minute:Second 的字符串,例如 2017:01:01:23:59:59,所有值域都是零填充的十進制數。
設計一個日志存儲系統實現如下功能:
-
void Put(int id, string timestamp):給定日志的 id 和 timestamp,將這個日志存入你的存儲系統中。
-
int[] Retrieve(String start, String end, String granularity):返回在給定時間區間內的所有日志的 id。start 、 end 和 timestamp 的格式相同,granularity 表示考慮的時間級。
比如,start = "2017:01:01:23:59:59", end = "2017:01:02:23:59:59", granularity = "Day" 代表區間 2017 年 1 月 1 日到 2017 年 1 月 2 日。
樣例
1 :
put
(1, "2017:01:01:23:59:59");
put
(2, "2017:01:01:22:59:59");
put
(3, "2016:01:01:00:00:00");
retrieve
("2016:01:01:01:01:01","2017:01:01:23:00:00","Year");
// 返回值
[1,2,3],返回從
2016 年到
2017 年所有的日志。
retrieve
("2016:01:01:01:01:01","2017:01:01:23:00:00","Hour");
// 返回值
[1,2], 返回從
2016:01:01:01 到
2017:01:01:23 區間內的日志,
日志
3 不在區間內。注釋 :
Put 和 Retrieve 的指令總數不超過
300。
年份的區間是
[2000,2017],小時的區間是
[00,23]。
Retrieve 的輸出順序不作要求。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/design-log-storage-system
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
- 轉化為 秒,在map里二分查找到下限,找到結束為止
- 注意月、日是從1開始的,需要 -1
- 然后是結束的日期 e 時,需要 + 該粒度的一個單位的秒數
class LogSystem {vector
<long long> second
= {12*31*24*3600, 31*24*3600, 24*3600, 3600, 60, 1};map
<string
, int> unit
= {{"Year",0},{"Month",1},{"Day",2},{"Hour",3},{"Minute",4},{"Second",5}};map
<long long, int> m
;
public:LogSystem() {}void put(int id
, string timestamp
) {m
[timeToint(timestamp
)] = id
;}vector
<int> retrieve(string s
, string e
, string gra
) {long long start
= timeToint(s
, unit
[gra
]);long long end
= timeToint(e
, unit
[gra
], true);vector
<int> ans
;for(auto it
= m
.lower_bound(start
); it
!= m
.end(); ++it
){if(it
->first
>= end
)break;ans
.push_back(it
->second
);}return ans
;}long long timeToint(string
& s
, int g
= 5, bool end
= false){ long long Year
= stoi(s
.substr(0,4));long long Month
= stoi(s
.substr(5,2));long long Day
= stoi(s
.substr(8,2));long long Hour
= stoi(s
.substr(11,2));long long Minute
= stoi(s
.substr(14,2));long long Second
= stoi(s
.substr(17,2));long long t
;if(g
==5)t
= (Year
)*second
[0]+(Month
-1)*second
[1]+(Day
-1)*second
[2]+(Hour
)*second
[3]+(Minute
)*second
[4]+(Second
)*second
[5];else if(g
==4)t
= (Year
)*second
[0]+(Month
-1)*second
[1]+(Day
-1)*second
[2]+(Hour
)*second
[3]+(Minute
)*second
[4];else if(g
==3)t
= (Year
)*second
[0]+(Month
-1)*second
[1]+(Day
-1)*second
[2]+(Hour
)*second
[3];else if(g
==2)t
= (Year
)*second
[0]+(Month
-1)*second
[1]+(Day
-1)*second
[2];else if(g
==1)t
= (Year
)*second
[0]+(Month
-1)*second
[1];elset
= (Year
)*second
[0];t
+= end
? second
[g
] :0;return t
;}
};
28 ms 13.7 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 635. 设计日志存储系统(map)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。