LeetCode 1656. Design an ordered flow

There are n (id, value) pairs, where id is an integer between 1 and n, and value is a string. There are no two (id, value) pairs with the same id.

Design a stream to get n (id, value) pairs in any order, and return some values ​​in increasing order of id when called multiple times.

Implement the OrderedStream class:

OrderedStream(int n) constructs a stream that can receive n values, and sets the current pointer ptr to 1.
String[] insert(int id, String value) stores a new (id, value) pair into the stream. After storage:
If the stream stores (id, value) pairs with id = ptr, find the longest continuous increasing sequence of id starting from id = ptr, and return the list of values ​​associated with these ids in order. Then, update ptr to the last id + 1.
Otherwise, an empty list is returned.

Example:
Input
["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
[[5], [3, "ccccc"], [1, "aaaaa"], [ 2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
output
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], [ "Ddddd", "eeeee"]]

Interpret
OrderedStream os = new OrderedStream(5);
os.insert(3, “ccccc”); // Insert(3, “ccccc”), return []
os.insert(1, “aaaaa”); // Insert( 1, "aaaaa"), return ["aaaaa"]
os.insert(2, "bbbbb"); // insert (2, "bbbbb"), return ["bbbbb", "ccccc"]
os.insert(5 , “Eeeee”); // Insert (5, “eeeee”), return []
os.insert(4, “ddddd”); // Insert (4, “ddddd”), return [“ddddd”, “eeeee ”]

The idea is to check whether there is an element at the position pointed to by ptr after each insertion, and if so, return the element and the consecutive elements after the element, and add ptr:

class OrderedStream {
    
    
public:
    OrderedStream(int n) {
    
    
        svec.resize(n + 1);
    }
    
    vector<string> insert(int id, string value) {
    
    
        vector<string> ret;

        svec[id] = value;

        while (1) {
    
    
            if (svec.size() == ptr || svec[ptr].empty()) {
    
    
                break;
            }

            ret.push_back(svec[ptr]);
            ++ptr;
        }

        return ret;
    }

    vector<string> svec;
    int ptr = 1;
};

Guess you like

Origin blog.csdn.net/tus00000/article/details/112622418