目录
Study Plan and Problem Number: Top Interview Quesitons 3
Date:July 3rd, 2022
Study Plan and Problem Number: Top Interview Quesitons 3
Problem 1:
Syntax:
Map in C++ STL:
- Basic understanding: mapping is more like a dictionary in python, which is to say, each unit is a pair, and it's a "vector" or "list" for a group of pairs.
- Two ways to insert elements in random order:
// empty map container map<int, int> gquiz1; // insert elements in random order gquiz1.insert(pair<int, int>(1, 40)); // another way of inserting a value in a map gquiz1[7]=10;
- It's common to use iterator to manipulate the content
//initialize a map iterator map<int, int>::iterator itr; cout << "\nThe map gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { //first and second element are accessed by using arrow to first and second //pretty similar to pairs cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; //copy a map to another, using iterator method map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); //erase all pairs with by a key2 gquiz2.erase(2); //remove all element up to 3 gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); //remove all element after 3 gquiz2.erase(gquiz2.find(3), gquiz.end());
Structure and typedef:
- Typedef plays a similar role as the "import A as B", such that we can call the datatype as B for the rest of time.
-
The typedef can be used to structure, but there's not a big meaning but make the code more clear in sense of naming. Also, there can be a constructor in struct:
typedef struct myStruct{ int var1_; int var2_; //default constructor: myStruct(): var1_(0), var2_(0) {} //customized constructor: myStruct(int var1, int var2): var1_(var1), var2_(var2) {} }myStruct //final name of struct
Algorithm & Structure:
Sliced window method:
- When considering to find a sub-string or vector that contains a special property within the input string, it's a good method to use mapping/hash table with slicing window.
- Two make the slicing working, there shall be two dummy variables, front and back.
Bug:
- When using this type of for-loop iteration
typdef struct customStruct{ int var1; char var2; }customStruct; vector<customStruct> stList; for(customStruct st: stList){ //do something to the struct e.g. //st.var1 = 123; }
Notice that the 'st' is just a copy of object in the vector, so it can't modify the actual content within. It's essential to use dummy variable in this case:
for(int i = 0; i < stList.size(); i++){ //do something to the struct e.g. //stList[i].var1 = 123; }
Tomorrow's Plan:
-
2-3 questions in top interview set
种一棵树最好的时机是十年前 其次是现在。