This problem is prone to timeout, mainly because the timestamps are inherently ordered. If you assume they are unordered, you will almost certainly time out. For example, using a multiset to store timestamps to maintain order, but actually a simple vector suffices.
Note: The std::distance function. Some iterators do not support subtraction, so you must use this to compute the distance.
Note: If you store a class or struct in std::set, you must implement the comparison operator because set is ordered.
std::lower_bound
Purpose: Returns an iterator to the first element that is >= the specified value. - If the value exists: returns the first position of that value. - If the value does not exist: returns the first element greater than the target value. - If all elements are less than the target value: returns the end() iterator.
To find elements less than the target value in reverse: std::lower_The iterator returned by bound minus one, i.e., std::lower_bound(vec.begin(), vec.end(), target) - 1。
std::upper_bound
Purpose: Returns an iterator to the first element that is > the specified value. - If the value exists: skips all equal values, returns the first element greater than the target value. - If the value does not exist: returns the first element greater than the target value. - If all elements are less than or equal to the target value: returns the end() iterator.
To find elements less than or equal to the target value in reverse: std::upper_The iterator returned by bound minus one, i.e., std::upper_bound(vec.begin(), vec.end(), target) - 1。
Note: when writing operator<
The parameter must be const Movie& (cannot accept non-const reference)
The function itself must be const (will not modify *this)
intgetCount(int destination, int startTime, int endTime){ vector<int> &vec = router_map[destination]; return std::distance(std::lower_bound(vec.begin(), vec.end(), startTime), std::upper_bound(vec.begin(), vec.end(), endTime)); } };
/** * Your Router object will be instantiated and called as such: * Router* obj = new Router(memoryLimit); * bool param_1 = obj->addPacket(source,destination,timestamp); * vector<int> param_2 = obj->forwardPacket(); * int param_3 = obj->getCount(destination,startTime,endTime); */