This week I attended ByteDance’s summer camp. The opening ceremony was on Saturday, so I completed this biweekly contest from the bed in a five-star hotel. It was wonderfully comfortable, and the contest result was still decent. Since I had to attend the summer camp classes the next morning, I skipped the weekly contest. But I still joined Kick Start Round E in the afternoon, skipping the summer camp class for it. What can I say? I really want to go to Google.
The biweekly contest problems were not hard. They felt like the kind of beginner-level problems you see on other OJs.
1165. Single-Row Keyboard
This tests the use of a hash table. Just build the reverse mapping from letter to index.
Time complexity: O(N) Space complexity: O(N)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intcalculateTime(string keyboard, string word){ vector<int> location(26); for (int i = 0; i < keyboard.size(); ++i) { location[keyboard[i] - 'a'] = i; } int ans = 0; int current = 0; for (char c : word) { ans += std::abs(location[c - 'a'] - current); current = location[c - 'a']; } return ans; } };
1166. Design File System
This tests basic data structures (tree) and string processing. Build a tree from the paths. Each file or directory is a node, and each node has a value. The lookup and insertion processes are similar to a Trie. Time complexity: O(N). Space complexity: O(N).
classFileSystem { structNode { unordered_map<string, shared_ptr<Node>> children; int value; Node(int v) : value(v) {} }; vector<string> split(const string& path){ string tmp; vector<string> stk; stringstream ss(path); while(getline(ss,tmp,'/')) { stk.push_back(tmp); } return stk; } shared_ptr<Node> m; public: FileSystem() { m = make_shared<Node>(0); } boolcreate(string path, int value){ auto words = split(path); auto current = m; for (int i = 1; i < words.size() - 1; ++i) { constauto& word = words[i]; if (current->children.find(word) == current->children.end()) { returnfalse; } else { current = current->children[word]; } } if (current->children.find(words.back()) != current->children.end()) { returnfalse; } current->children[words.back()] = make_shared<Node>(value); returntrue; } intget(string path){ auto words = split(path); auto current = m; for (int i = 1; i < words.size(); ++i) { constauto& word = words[i]; if (current->children.find(word) == current->children.end()) { return-1; } else { current = current->children[word]; } } return current->value; } };
/** * Your FileSystem object will be instantiated and called as such: * FileSystem* obj = new FileSystem(); * bool param_1 = obj->create(path,value); * int param_2 = obj->get(path); */
1167. Minimum Cost to Connect Sticks
Greedy algorithm. Each time, choose the two sticks with the smallest cost and connect them. The earlier a stick is connected, the more likely its length is to affect the total cost.