├── Algorithm ├── DP │ ├── d.txt │ ├── data.txt │ ├── levenshtein-string.cpp │ ├── matrix.cpp │ └── max_sum_subarray.cpp ├── Number │ ├── K-WayMerge.cpp │ ├── ListNode.h │ ├── sort-bubble.cpp │ ├── sort-heap.cpp │ ├── sort-insert.cpp │ ├── sort-merge.cpp │ ├── sort-quick.cpp │ ├── sort-select.cpp │ ├── sort-shell.cpp │ └── sqrtn.cpp └── Tree │ ├── Deutsch-Schorr-Waite.cpp │ ├── traversal.cpp │ └── tree.h ├── Basic ├── CopyConstructor.cpp ├── DefaultConstructor.cpp ├── NRV.cpp ├── Point.cpp ├── Point3d.cpp ├── Singleton.cpp ├── opertaor-new-delete.cpp ├── placement-new.cpp ├── trait.cpp ├── 多态.cpp ├── 数组地址加1.cpp └── 数组引用传递.cpp ├── Boost ├── adapter.cpp ├── base64.cpp ├── boost_bind.cpp ├── file.cpp ├── fopen.cpp ├── md5.cpp ├── mutex.cpp ├── new.cpp ├── offset.cpp ├── optional.cpp ├── share.cpp ├── thread.cpp └── timer.cpp ├── CPP-Primer ├── Q2 │ ├── Foo.cpp │ ├── Foo.h │ └── main.cpp ├── Q4 │ └── empty.cpp ├── chapter1.cpp ├── chapter10.cpp ├── chapter12.cpp ├── chapter13.cpp ├── chapter14.cpp ├── chapter15.cpp ├── chapter2.cpp ├── chapter3.cpp ├── chapter6.cpp ├── chapter7.cpp ├── chapter8.cpp ├── chapter9.cpp └── query.cpp ├── CrackInterview ├── Chapter3 │ └── Q3-6.cpp └── Chapter5 │ ├── Q5.1-tip.cpp │ └── Q5.1.cpp ├── DesignPattern ├── CreateMode(1)-Factory │ ├── Factory.cpp │ ├── Factory.h │ ├── Product.cpp │ ├── Product.h │ └── main.cpp ├── CreateMode(2)-AbstractFactory │ ├── AbstractFactory.cpp │ ├── AbstractFactory.h │ ├── Product.cpp │ ├── Product.h │ └── main.cpp ├── CreateMode(3)-Singleton │ ├── Singleon.cpp │ ├── Singleton.h │ ├── Singleton2.cpp │ ├── Singleton2.h │ └── main.cpp ├── CreateMode(4)-Builder │ ├── BuildPerson.cpp │ ├── Builder.cpp │ ├── Builder.h │ ├── Director.cpp │ ├── Director.h │ ├── Product.cpp │ ├── Product.h │ └── main.cpp ├── CreateMode(5)-Prototype │ ├── Prototype.cpp │ ├── Prototype.h │ └── main.cpp ├── StructMode(1)-Adapter │ ├── Adapter.cpp │ ├── Adapter.h │ ├── Adapter1.cpp │ ├── Adapter1.h │ └── main.cpp ├── StructMode(2)-Decorator │ ├── Decorator.cpp │ ├── Decorator.h │ └── main.cpp ├── StructMode(3)-Bridge │ ├── Abstraction.cpp │ ├── Abstraction.h │ ├── AbstractionImp.cpp │ ├── AbstractionImp.h │ └── main.cpp ├── StructMode(4)-Composite │ ├── Component.cpp │ ├── Component.h │ ├── Composite.cpp │ ├── Composite.h │ ├── Leaf.cpp │ ├── Leaf.h │ └── main.cpp ├── StructMode(5)-Flyweight │ ├── Flyweight.cpp │ ├── Flyweight.h │ ├── FlyweightFactory.cpp │ ├── FlyweightFactory.h │ └── main.cpp └── StructMode(7)-Proxy │ ├── Proxy.cpp │ ├── Proxy.h │ ├── Subject.cpp │ ├── Subject.h │ └── main.cpp ├── LICENSE ├── Leetcode ├── .vscode │ └── launch.json ├── Q1.cpp ├── Q10.cpp ├── Q101.cpp ├── Q103.cpp ├── Q105.cpp ├── Q108.cpp ├── Q109.cpp ├── Q11.cpp ├── Q110.cpp ├── Q113.cpp ├── Q116.cpp ├── Q119.cpp ├── Q12.cpp ├── Q120.cpp ├── Q122.cpp ├── Q124.cpp ├── Q125.cpp ├── Q128.cpp ├── Q129.cpp ├── Q13.cpp ├── Q130.cpp ├── Q134.cpp ├── Q135.cpp ├── Q137.cpp ├── Q14.cpp ├── Q141.cpp ├── Q142.cpp ├── Q144.cpp ├── Q148.cpp ├── Q15.cpp ├── Q152.cpp ├── Q153.cpp ├── Q154.cpp ├── Q16.cpp ├── Q160.cpp ├── Q165.cpp ├── Q166-2.cpp ├── Q166.cpp ├── Q167.cpp ├── Q168.cpp ├── Q169.cpp ├── Q17.cpp ├── Q172.cpp ├── Q179.cpp ├── Q18.cpp ├── Q189.cpp ├── Q19.cpp ├── Q199.cpp ├── Q2.cpp ├── Q20.cpp ├── Q200.cpp ├── Q201.cpp ├── Q202.cpp ├── Q203.cpp ├── Q205.cpp ├── Q206.cpp ├── Q208.cpp ├── Q21.cpp ├── Q211.cpp ├── Q213.cpp ├── Q216.cpp ├── Q219.cpp ├── Q22.cpp ├── Q220.cpp ├── Q221.cpp ├── Q222.cpp ├── Q223.cpp ├── Q228.cpp ├── Q229.cpp ├── Q23.cpp ├── Q234.cpp ├── Q238.cpp ├── Q24.cpp ├── Q241.cpp ├── Q25.cpp ├── Q257.cpp ├── Q26.cpp ├── Q260.cpp ├── Q263.cpp ├── Q268.cpp ├── Q278.cpp ├── Q282.cpp ├── Q287.cpp ├── Q289.cpp ├── Q29.cpp ├── Q290.cpp ├── Q299.cpp ├── Q3.cpp ├── Q30.cpp ├── Q300.cpp ├── Q307.cpp ├── Q309.cpp ├── Q31.cpp ├── Q316.cpp ├── Q318.cpp ├── Q32.cpp ├── Q321.cpp ├── Q326.cpp ├── Q327.cpp ├── Q336-2.cpp ├── Q336.cpp ├── Q337.cpp ├── Q34.cpp ├── Q342.cpp ├── Q345.cpp ├── Q350.cpp ├── Q352-2.cpp ├── Q352-3.cpp ├── Q352-4.cpp ├── Q352.cpp ├── Q357.cpp ├── Q36.cpp ├── Q367.cpp ├── Q372.cpp ├── Q376.cpp ├── Q378.cpp ├── Q38.cpp ├── Q380.cpp ├── Q381.cpp ├── Q382.cpp ├── Q384.cpp ├── Q39.cpp ├── Q392.cpp ├── Q393.cpp ├── Q394.cpp ├── Q396.cpp ├── Q397.cpp ├── Q398.cpp ├── Q4.cpp ├── Q40.cpp ├── Q400.cpp ├── Q401.cpp ├── Q402.cpp ├── Q405.cpp ├── Q406-2.cpp ├── Q406.cpp ├── Q409.cpp ├── Q41.cpp ├── Q413.cpp ├── Q414.cpp ├── Q415.cpp ├── Q419.cpp ├── Q421.cpp ├── Q423.cpp ├── Q43.cpp ├── Q435.cpp ├── Q436.cpp ├── Q437.cpp ├── Q438.cpp ├── Q441.cpp ├── Q442.cpp ├── Q445.cpp ├── Q447.cpp ├── Q448.cpp ├── Q45.cpp ├── Q452.cpp ├── Q453.cpp ├── Q454.cpp ├── Q455.cpp ├── Q456.cpp ├── Q459.cpp ├── Q46.cpp ├── Q462.cpp ├── Q464.cpp ├── Q47.cpp ├── Q476.cpp ├── Q48.cpp ├── Q485.cpp ├── Q486.cpp ├── Q49.cpp ├── Q495.cpp ├── Q496.cpp ├── Q5.cpp ├── Q50 ├── Q50.cpp ├── Q500.cpp ├── Q523.cpp ├── Q524.cpp ├── Q53.cpp ├── Q532.cpp ├── Q538.cpp ├── Q539.cpp ├── Q54.cpp ├── Q541.cpp ├── Q542.cpp ├── Q543.cpp ├── Q547.cpp ├── Q55.cpp ├── Q556.cpp ├── Q56.cpp ├── Q560.cpp ├── Q561.cpp ├── Q563.cpp ├── Q564.cpp ├── Q567.cpp ├── Q568.cpp ├── Q57.cpp ├── Q572.cpp ├── Q573.cpp ├── Q575.cpp ├── Q576.cpp ├── Q6.cpp ├── Q60.cpp ├── Q62.cpp ├── Q63.cpp ├── Q64.cpp ├── Q67.cpp ├── Q69.cpp ├── Q7.cpp ├── Q70.cpp ├── Q73.cpp ├── Q74.cpp ├── Q75.cpp ├── Q76.cpp ├── Q78.cpp ├── Q83.cpp ├── Q84.cpp ├── Q85-1.cpp ├── Q85-2.cpp ├── Q85.cpp ├── Q86.cpp ├── Q88.cpp ├── Q9.cpp ├── Q90.cpp ├── Q94.cpp ├── Q95.cpp ├── Q96.cpp └── Q98.cpp ├── MoreEffectiveCPP ├── item10.cpp ├── item11.cpp ├── item12.cpp ├── item13.cpp ├── item14.cpp ├── item15.cpp ├── item16.cpp ├── item17.cpp ├── item18.cpp ├── item19.cpp ├── item2.cpp ├── item20.cpp ├── item22.cpp ├── item25.cpp ├── item3.cpp ├── item4.cpp ├── item5.cpp ├── item6.cpp ├── item7.cpp ├── item8.cpp ├── item9.cpp └── stack-unwinding.cpp ├── POJ ├── poj1003.cpp ├── poj1004.cpp ├── poj1045.cpp ├── poj1051.cpp └── poj1068.cpp ├── PythonMachineLearning ├── .ipynb_checkpoints │ ├── Adaline-checkpoint.ipynb │ ├── Chaper6 ModelEvaluation And Hyperparameter Tuning-checkpoint.ipynb │ ├── Chapter5 Compressing Data via Dimensionality Reduction-checkpoint.ipynb │ ├── Chapter7 Ensemble Learning-checkpoint.ipynb │ ├── Chapter8 ApplyingMachineLearningToSentimentAnalysis-checkpoint.ipynb │ ├── Chapter9-checkpoint.ipynb │ ├── Data Preprocessing-checkpoint.ipynb │ ├── NumpyTutorial-checkpoint.ipynb │ ├── PandasTutorial-checkpoint.ipynb │ ├── Perceptron-checkpoint.ipynb │ ├── Untitled-checkpoint.ipynb │ ├── Untitled1-checkpoint.ipynb │ ├── pltTutorial-checkpoint.ipynb │ └── pml-sklearn-3-checkpoint.ipynb ├── Adaline.ipynb ├── Chaper6 ModelEvaluation And Hyperparameter Tuning.ipynb ├── Chapter5 Compressing Data via Dimensionality Reduction.ipynb ├── Chapter7 Ensemble Learning.ipynb ├── Chapter8 ApplyingMachineLearningToSentimentAnalysis.ipynb ├── Chapter9.ipynb ├── Data Preprocessing.ipynb ├── NumpyTutorial.ipynb ├── PandasTutorial.ipynb ├── Perceptron.ipynb ├── Untitled.ipynb ├── Untitled1.ipynb ├── iris.csv ├── ml-gd.png ├── pltTutorial.ipynb ├── pml-sklearn-3.ipynb ├── tree.dot └── tree.png ├── README.md └── README_EN.md /Algorithm/DP/d.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 2 2 3 | 1 1 4 | 1 1 5 | 2 3 6 | 1 1 1 7 | 1 1 1 8 | 3 2 9 | 1 1 10 | 1 1 11 | 1 1 12 | -------------------------------------------------------------------------------- /Algorithm/DP/data.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 1 2 3 | 3 6 4 | 3 4 5 | 1 2 3 4 6 | 1 2 4 5 7 | 3 4 5 6 8 | 4 5 9 | 2 3 4 5 6 10 | 3 4 7 8 9 11 | 5 6 7 8 9 12 | 5 4 3 6 7 13 | 5 3 14 | 3 5 5 15 | 4 7 8 16 | 7 6 4 17 | 4 5 6 18 | 3 8 9 19 | -------------------------------------------------------------------------------- /Algorithm/Number/K-WayMerge.cpp: -------------------------------------------------------------------------------- 1 | #include "ListNode.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | private: 11 | struct cmp 12 | { 13 | bool operator ()(const ListNode *a, const ListNode *b) 14 | { 15 | return a->val > b->val; 16 | } 17 | }; 18 | public: 19 | ListNode *mergeKLists(vector &lists) { 20 | int n = lists.size(); 21 | if(n == 0)return NULL; 22 | ListNode node(0), *res = &node; 23 | priority_queue, cmp> que; 24 | for(int i = 0; i < n; i++) 25 | if(lists[i]) 26 | que.push(lists[i]); 27 | while(!que.empty()) 28 | { 29 | ListNode * p = que.top(); 30 | que.pop(); 31 | res->next = p; 32 | res = p; 33 | 34 | if(p->next) 35 | que.push(p->next); 36 | } 37 | return node.next; 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | int *p = (int *)malloc(1024); 44 | for(int i=0;i<256;i++) cout << *p++ << endl; 45 | Solution s; 46 | } 47 | -------------------------------------------------------------------------------- /Algorithm/Number/ListNode.h: -------------------------------------------------------------------------------- 1 | #ifndef _LIST_NODE_ 2 | #define _LIST_NODE_ 3 | class ListNode 4 | { 5 | public: 6 | ListNode(int val):val(val){} 7 | public: 8 | int val; 9 | ListNode *next; 10 | }; 11 | 12 | #endif 13 | -------------------------------------------------------------------------------- /Algorithm/Number/sort-bubble.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | vector number = {-1,3,3,5,61,23,8,10,11,29}; 8 | for(int i=1;i number[i]) //把大的冒泡到最后 12 | { 13 | swap(number[i],number[j]); 14 | } 15 | } 16 | 17 | 18 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | //把数组分为两半,左侧已经是有序的,每次取无序的第一个,判断和有序的大小,查找需要插入的位置。 6 | 7 | int main() 8 | { 9 | //vector number = {-1,3,3,5,61,23,8,10,11,29}; 10 | vector number = {6,5,4,3,2,1}; 11 | 12 | 13 | int k = 0; 14 | for(int i=1;i=0;j--) 19 | { 20 | if(number[j] > tmp) number[j+1] = number[j]; 21 | else break; 22 | } 23 | number[j+1] = tmp; //不断后移,j+1的位置是空的,等待插入 24 | } 25 | 26 | 27 | 28 | for(int i=0;i 3 | #include 4 | using namespace std; 5 | 6 | void merge(vector&num,int l,int mid,int r) 7 | { 8 | vector tmp; 9 | int i = l,j=mid+1; 10 | while(i<=mid && j<=r) 11 | { 12 | if(num[i] < num[j]) tmp.push_back(num[i++]); 13 | else tmp.push_back(num[j++]); 14 | } 15 | while(i<=mid) tmp.push_back(num[i++]); 16 | while(j<=mid) tmp.push_back(num[j++]); 17 | 18 | for(int i=0,k=l;i&num,int l,int r) 23 | { 24 | if(l < r) 25 | { 26 | int mid = l+(r-l)/2; 27 | sort_merge(num,l,mid); 28 | sort_merge(num,mid+1,r); 29 | merge(num,l,mid,r); 30 | } 31 | } 32 | 33 | 34 | 35 | int main() 36 | { 37 | //vector num = {1,4,3,6,10,33,2,3,5}; 38 | vector num = {1,4,3,6,10,33,2,3,5,100,-1,16,87,22,34}; 39 | sort_merge(num,0,num.size()-1); 40 | for(int x:num) cout << x << ","; 41 | cout << endl; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Algorithm/Number/sort-quick.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Algorithm/Number/sort-quick.cpp -------------------------------------------------------------------------------- /Algorithm/Number/sort-select.cpp: -------------------------------------------------------------------------------- 1 | //选择排序 ,每次选择序列中最小的放到首位。 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | vector number = {-1,3,3,5,61,23,8,10,11,29}; 9 | 10 | for(int i=0;i number[j]) 17 | { 18 | k = j; 19 | minn = number[j]; 20 | } 21 | } 22 | swap(number[k],number[i]); 23 | } 24 | 25 | for(int i=0;i 8 | #include 9 | using namespace std; 10 | 11 | //把数组分为两半,左侧已经是有序的,每次取无序的第一个,判断和有序的大小,查找需要插入的位置。 12 | 13 | int main() 14 | { 15 | //vector number = {-1,3,3,5,61,23,8,10,11,29}; 16 | vector number = {10,9,8,7,6,5,4,3,2,1,0}; 17 | 18 | 19 | int increment = number.size(); 20 | while(increment > 1) 21 | { 22 | increment = increment/3+1; 23 | for(int i=increment;i=0;j-=increment) 28 | { 29 | if(number[j] > tmp) number[j+increment] = number[j]; 30 | else break; 31 | } 32 | number[j+increment] = tmp; //不断后移,j+1的位置是空的,等待插入 33 | } 34 | } 35 | 36 | 37 | 38 | for(int i=0;i 2 | using namespace std; 3 | 4 | int Pow(int x, int n) 5 | { 6 | if (n == 1) 7 | return x; 8 | else if (n > 1) 9 | { 10 | int s; 11 | int m = n / 2; 12 | s = Pow (x, m); 13 | if (n % 2 == 0) 14 | return (s * s); 15 | else 16 | return (s * s * x); 17 | } 18 | } 19 | 20 | int main() 21 | { 22 | int x, n; 23 | while (cin >> x >> n) 24 | { 25 | cout << Pow(x, n) << endl; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Algorithm/Tree/Deutsch-Schorr-Waite.cpp: -------------------------------------------------------------------------------- 1 | //使用常量空间,线性时间遍历任意图 2 | // 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | void Visit(TreeNode *node) 8 | { 9 | cout << node->val << endl; 10 | } 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Algorithm/Tree/traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * lzjqsdd@gmail.com 3 | * 树的遍历:先序遍历,中序遍历,后序遍历,都是以root节点来看的 4 | */ 5 | 6 | #include -------------------------------------------------------------------------------- /Algorithm/Tree/tree.h: -------------------------------------------------------------------------------- 1 | #ifndef TREE_H 2 | #define TREE_H 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | #endif -------------------------------------------------------------------------------- /Basic/CopyConstructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class BaseString 5 | { 6 | public: 7 | BaseString(){cout << "Call BaseString Default Constructor" << endl;} 8 | BaseString(char *str){this->str = str; len = 10;} 9 | ~BaseString(){} 10 | BaseString(const BaseString& basestring) //copy constructor 11 | { 12 | this->str = basestring.str; 13 | this->len = basestring.len; 14 | cout << "Call BaseString Copy Constructor " << endl; 15 | } 16 | char *str; 17 | int len; 18 | }; 19 | 20 | class Word 21 | { 22 | public: 23 | Word(){} 24 | //Word(char *str){bs.str = str;bs.len = 10;flag = 1;} //默认编译器扩展添加了BaseString的默认构造函数 25 | 26 | 27 | Word(char *str): 28 | bs(str) 29 | {flag = 1;} //basestring调用了用户定义的构造函数 30 | 31 | ~Word(){} 32 | 33 | //没有设定拷贝构造函数 34 | private: 35 | BaseString bs; //由于包含了member class object,默认的拷贝初始化是递归进行的 36 | int flag; 37 | }; 38 | 39 | 40 | int main() 41 | { 42 | char cc[] = "1234"; 43 | Word wd(cc); 44 | Word wd2 = wd; //测试调用copy constructor 45 | } 46 | -------------------------------------------------------------------------------- /Basic/DefaultConstructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | namespace lzjqsdd 5 | { 6 | class Foo 7 | { 8 | public: 9 | Foo() 10 | { 11 | this->val = 1; 12 | cout << "Foo Default Constructor" << endl; 13 | } 14 | ~Foo(){} 15 | private: 16 | int val; 17 | }; 18 | 19 | 20 | class Bar 21 | { 22 | public: 23 | //只有用户定义的构造函数,没有默认构造函数 24 | Bar(float fval){this->fval = fval;} //测试编译器是否会扩充构造函数来构造foo 25 | Bar(){this->fval = fval;} //如果增加了默认构造函数,但是有用户代码,编译器是否会扩充 26 | ~Bar(){} 27 | 28 | private: 29 | Foo foo; //Foo有默认构造函数 30 | float fval; 31 | }; 32 | } 33 | 34 | 35 | using namespace lzjqsdd; 36 | int main() 37 | { 38 | Bar bb(1); 39 | } 40 | -------------------------------------------------------------------------------- /Basic/NRV.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Base{ 4 | public: 5 | friend Base add(Base &a,Base &b); 6 | static int count; 7 | static void show(){cout << count << endl;} 8 | static void init(){count = 0;} 9 | Base(){x = 10;cout << "call default constructor" << endl;count++;} 10 | ~Base(){cout << "call default deconstructor" << endl;} 11 | Base(const Base &base){x = base.x;cout << "call copy constructor " << endl;} 12 | private: 13 | int x; 14 | }; 15 | 16 | int Base::count = 0; //为什么加这句话,参考静态成员初始化代码 17 | 18 | Base add(Base &a,Base &b) 19 | { 20 | Base c; 21 | c.x = a.x + b.x; 22 | return c; 23 | } 24 | 25 | int main() 26 | { 27 | Base a,b; 28 | Base::init(); 29 | Base c = add(a,b); 30 | Base::show(); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Basic/Point.cpp: -------------------------------------------------------------------------------- 1 | #ifndef POINT 2 | #define POINT 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | class Point 9 | { 10 | public: 11 | Point(float xval); 12 | virtual ~Point(); 13 | 14 | float x() const; 15 | static int PointCount(); 16 | 17 | protected: 18 | virtual ostream& print(ostream &os) const; 19 | float _x; 20 | static int _point_count; 21 | }; 22 | #endif 23 | 24 | 25 | int main() 26 | { 27 | cout << sizeof(Point) << endl; 28 | } 29 | -------------------------------------------------------------------------------- /Basic/Point3d.cpp: -------------------------------------------------------------------------------- 1 | #ifndef POINT3D 2 | #define POINT3D 3 | 4 | #include 5 | 6 | class Point3d 7 | { 8 | public: 9 | Point3d(float x=0.0,float y=0.0,float z=0.0): 10 | _x(x),_y(y),_z(z){}; 11 | 12 | float x() {return _x;} 13 | float y() {return _y;} 14 | float z() {return _z;} 15 | 16 | void x(float xval){_x = xval;} 17 | 18 | private: 19 | float _x; 20 | float _y; 21 | float _z; 22 | }; 23 | 24 | inline ostream& operator<<(ostream &os,const Point3d &pt) 25 | { 26 | os << "(" << pt.x() << "," << pt.y() << "," << pt.z() << ")" << endl; 27 | } 28 | -------------------------------------------------------------------------------- /Basic/Singleton.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Basic/Singleton.cpp -------------------------------------------------------------------------------- /Basic/opertaor-new-delete.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class TestNew 6 | { 7 | public: 8 | TestNew(){cout << "constructor of X" << endl;} 9 | ~TestNew(){cout << "deconstructor of X" << endl;} 10 | 11 | void * operator new (size_t size,string str) 12 | { 13 | cout << "operator new size " << size << "with string " << str << endl; 14 | return ::operator new(size); 15 | } 16 | 17 | void * operator new (size_t size) 18 | { 19 | cout << "operator new size " << size << endl; 20 | return ::operator new(size); 21 | } 22 | 23 | void operator delete(void * pointee) 24 | { 25 | cout << "operator delete" << endl; 26 | ::operator delete(pointee); 27 | } 28 | 29 | private: 30 | int num; 31 | }; 32 | 33 | 34 | int main() 35 | { 36 | //TestNew *px = new("A new class") TestNew; //new 调用了被重载的operator new 操作符 37 | TestNew *px = new TestNew; //new 调用了被重载的operator new 操作符 38 | delete px; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Basic/placement-new.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Test 5 | { 6 | public: 7 | Test(int x){_x = x;} 8 | Test(){_x = 0;} 9 | ~Test(){} 10 | 11 | private: 12 | int _x; 13 | }; 14 | 15 | 16 | #define N 100000000 17 | int main() 18 | { 19 | int *p = new int[10]; 20 | //Test * tp = new Test[10]; //直接分配会因为没有默认构造函数而分配失败 21 | 22 | //使用placement new来分配内存 23 | char *buff = new char[sizeof(Test)]; //预先在堆上分配buffer 24 | //char buff2[sizeof(Test)]; //或者在栈上分配 25 | 26 | Test *tp = new(buff) Test(1); 27 | 28 | 29 | #ifdef TEST_ARRAY 30 | #ifdef PLACEMENT_NEW 31 | /////////////////////////////////////////////////////////// 32 | //如果要分配一个数组呢? 33 | char *buff_array = new char[sizeof(Test) * N]; 34 | Test *tpa = (Test*) buff_array; //强制把内存解释为Test数组 35 | //for(int i=0;i~Test();} 54 | delete buff2; 55 | #endif 56 | 57 | #ifdef COMMON_NEW 58 | for(int i=0;i~Test();delete tpb;} 59 | #endif 60 | #endif 61 | 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Basic/多态.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Base 6 | { 7 | public: 8 | Base(){}; 9 | virtual void display(){cout << "Base" << endl;} 10 | void display2(){cout << "Base2" << endl;} 11 | }; 12 | 13 | class Derive:public Base 14 | { 15 | public: 16 | Derive(){}; 17 | virtual void display(){cout << "Derive" << endl;} 18 | void display2(){cout << "Derive2" << endl;} 19 | }; 20 | 21 | class C:public Derive{ 22 | public: 23 | C(){}; 24 | void display(){cout << "C" << endl;} 25 | }; 26 | 27 | int main() 28 | { 29 | /* 30 | Derive dd; 31 | Base &b = dd; 32 | b.display(); 33 | Derive dd2; 34 | Base &b2 = dd2; 35 | b2.display2(); 36 | dd2.display2(); 37 | */ 38 | C c; 39 | Base &d = c; 40 | d.display(); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Basic/数组地址加1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a[4] = {1,2,3,4}; 7 | cout << a << endl; 8 | cout << &a[0] << endl; 9 | cout << &a[1] << endl; 10 | cout << &a[2] << endl; 11 | cout << &a[3] << endl; 12 | cout << &a << endl; 13 | cout << &a+1 << endl; 14 | cout << &a+2 << endl; 15 | } 16 | -------------------------------------------------------------------------------- /Basic/数组引用传递.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | void printV(int (&a)[2]) 7 | { 8 | for(int i=0;i<2;i++) 9 | cout << a[i] << endl; 10 | } 11 | 12 | template 13 | void printVT(T (&a)[N]) 14 | { 15 | for(T i=0;i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class AddValue { 8 | public: 9 | AddValue(int v):theValue(v){} 10 | void operator()(int& elem) const { 11 | elem += theValue; 12 | cout << elem << ","; 13 | }; 14 | private: 15 | int theValue; 16 | }; 17 | 18 | int main() 19 | { 20 | list coll; 21 | for(int i=1;i<=9;++i) 22 | coll.push_back(i); 23 | 24 | //for_each(coll.begin(), coll.end(), AddValue(10)); 25 | for_each(coll.begin(), coll.end(), AddValue(*coll.begin())); 26 | cout << endl; 27 | } 28 | -------------------------------------------------------------------------------- /Boost/base64.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | std::string EncodeBase64(const std::string &val) 8 | { 9 | using namespace boost::archive::iterators; 10 | typedef base64_from_binary> It; 11 | auto tmp = std::string(It(val.begin()),It(val.end())); 12 | return tmp.append((3 - val.size() % 3) % 3,'='); 13 | } 14 | 15 | int main() 16 | { 17 | std::string s; 18 | while(std::cin >> s) 19 | { 20 | std::string res = EncodeBase64(s); 21 | std::cout << res << std::endl; 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Boost/boost_bind.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Boost/boost_bind.cpp -------------------------------------------------------------------------------- /Boost/file.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | using namespace boost::filesystem; 5 | 6 | int main(int argc, char* argv[]) 7 | { 8 | if (argc < 2) 9 | { 10 | cout << "Usage: tut2 path\n"; 11 | return 1; 12 | } 13 | 14 | path p(argv[1]); // avoid repeated path construction below 15 | 16 | while(2){ 17 | if (exists(p)) // does path p actually exist? 18 | { 19 | /* 20 | if (is_regular_file(p)) // is path p a regular file? 21 | cout << p << " size is " << file_size(p) << '\n'; 22 | 23 | else if (is_directory(p)) // is path p a directory? 24 | cout << p << " is a directory\n"; 25 | else 26 | cout << p << " exists, but is not a regular file or directory\n"; 27 | */ 28 | 29 | std::time_t lastmtime = last_write_time(p); 30 | cout << "last modify time is : " << lastmtime << endl; 31 | file_status fs = status(p); 32 | cout << fs.permissions() << endl; 33 | 34 | } 35 | else 36 | cout << p << " does not exist\n"; 37 | 38 | sleep(2); 39 | } 40 | 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Boost/fopen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // 为了使用 exit() 3 | int main() 4 | { 5 | int ch; 6 | FILE* fp; 7 | fp=fopen("a.iso","r+"); // 只供读取 8 | if(fp==NULL) // 如果失败了 9 | { 10 | printf("unable\n"); 11 | } 12 | else 13 | printf("enable\n"); 14 | fclose(fp); // 关闭文件 15 | return 0; 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /Boost/mutex.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void wait(int seconds) 6 | { 7 | boost::this_thread::sleep_for(boost::chrono::seconds{seconds}); 8 | } 9 | 10 | boost::mutex mutex; 11 | 12 | void thread() 13 | { 14 | using boost::this_thread::get_id; 15 | for(int i=0;i<5;++i) 16 | { 17 | wait(1); 18 | mutex.lock(); 19 | std::cout << "Thread " << get_id() << ": " << i << std::endl; 20 | mutex.unlock(); 21 | } 22 | } 23 | 24 | 25 | int main() 26 | { 27 | boost::thread t1{thread}; 28 | boost::thread t2{thread}; 29 | t1.join(); 30 | t2.join(); 31 | } 32 | -------------------------------------------------------------------------------- /Boost/new.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | //#include 3 | #include // 使用_set_new_mode和set_new_handler 4 | void nomem_handler() 5 | { 6 | std::cout<<"call nomem_handler"< 2 | using namespace std; 3 | class A{ 4 | public: 5 | A() 6 | { m_a = 10; m_b = 2;} 7 | ~A() {} 8 | void fun(){ 9 | cout << m_a << m_b << endl; 10 | } 11 | int m_a; 12 | int m_b; 13 | }; 14 | 15 | 16 | class B{ 17 | public: 18 | B() {m_c = 3;} 19 | ~B() {} 20 | void fun() 21 | { 22 | cout << m_c << endl; 23 | } 24 | int m_c; 25 | }; 26 | 27 | 28 | 29 | int main(){ 30 | A a; 31 | B *pb = (B*)(&a); 32 | cout << &a << endl; 33 | cout << &(a.m_a) << endl; 34 | /* cout << &(A::m_a) << endl; cout << &(A::m_b) << endl; cout << &(B::m_c) << endl; */ 35 | //cout << &(pb->m_c) << endl; 36 | pb->fun(); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Boost/optional.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | boost::optional convert(const std::string& text) 10 | { 11 | std::stringstream s(text); 12 | int i; 13 | if((s >> i) && s.get() == std::char_traits::eof()) 14 | return i; 15 | else 16 | return boost::none; 17 | } 18 | 19 | 20 | int main() 21 | { 22 | //optional用于接收返回值不在取值范围内的数据,比如EOF,NULL等 23 | //const std::string& text = "123a4"; 24 | const std::string& text = "123"; 25 | boost::optional oi = convert(text); 26 | //optional 是UB-Safe的 27 | //if(oi) cout << *oi << endl; 28 | int k = oi.value_or(0); 29 | cout << k << endl; 30 | 31 | 32 | //关于is_initialized 33 | boost::optional xx; 34 | assert(x.is_initialized()); 35 | } 36 | -------------------------------------------------------------------------------- /Boost/share.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | 8 | class B{ 9 | public: 10 | B(int x):a(x){std::cout << "call b ctor..." << a << std::endl;} 11 | ~B() {std::cout << "call b dstor..." << a << std::endl;} 12 | private: 13 | int a; 14 | }; 15 | 16 | class A 17 | { 18 | typedef shared_ptr pint; 19 | public: 20 | A(){ 21 | data[0].reset(new B(0)); 22 | data[1].reset(new B(1)); 23 | } 24 | pint data[2]; 25 | }; 26 | 27 | 28 | int main() 29 | { 30 | A a; 31 | } 32 | -------------------------------------------------------------------------------- /Boost/timer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | using namespace boost; 5 | 6 | int main() 7 | { 8 | timer t; 9 | cout << "max timespan:" << t.elapsed_max()/3600 <<"h" << endl; 10 | cout << "min timespan:" << t.elapsed_min() <<"s" << endl; 11 | 12 | cout << "now time elapsed:" << t.elapsed() << "s" << endl; 13 | } 14 | -------------------------------------------------------------------------------- /CPP-Primer/Q2/Foo.cpp: -------------------------------------------------------------------------------- 1 | //Foo.cpp 2 | #include "Foo.h" 3 | Foo::Foo() 4 | { 5 | x = 10; 6 | } 7 | 8 | void Foo::setX(int x) 9 | { 10 | this->x = x; 11 | } 12 | 13 | int Foo::getX() const 14 | { 15 | return x; 16 | } 17 | -------------------------------------------------------------------------------- /CPP-Primer/Q2/Foo.h: -------------------------------------------------------------------------------- 1 | //Foo.h 2 | #ifndef __FOO__ 3 | #define __FOO__ 4 | 5 | class Foo{ 6 | private: 7 | int x; 8 | public: 9 | Foo(); 10 | void setX(int x); //没有const,意味着不安全 11 | int getX() const; //有const意味着该函数不会修改Foo的成员。 12 | }; 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /CPP-Primer/Q2/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Foo.h" 2 | 3 | int main() 4 | { 5 | //const Foo fo; 6 | //fo.setX(10); //const对象调用非const成员函数,报错。 7 | 8 | const Foo fo; 9 | fo.getX(); 10 | } 11 | -------------------------------------------------------------------------------- /CPP-Primer/Q4/empty.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Foo{}; 5 | 6 | int main() 7 | { 8 | cout << sizeof(Foo)<< endl; 9 | } 10 | -------------------------------------------------------------------------------- /CPP-Primer/chapter1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout<<"Come up and c++ me some time."< 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | shared_ptrp1; 8 | } 9 | -------------------------------------------------------------------------------- /CPP-Primer/chapter14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct absInt { 5 | int operator()(int val) const { 6 | return val < 0 ? -val:val; 7 | } 8 | } 9 | 10 | int main() 11 | { 12 | absInt ai; 13 | ai(10); //a是个对象,但是可以像函数一样使用 14 | } 15 | -------------------------------------------------------------------------------- /CPP-Primer/chapter15.cpp: -------------------------------------------------------------------------------- 1 | class Quote{ 2 | public : 3 | Quote() = default; 4 | Quote(const std::string &book,double sales_price): 5 | bookNo(book), 6 | price(sales_price) 7 | { 8 | } 9 | 10 | virtual ~Quote() = default; 11 | 12 | 13 | std::string isbn() const; 14 | virtual double net_price(std::size_t n) const 15 | { 16 | return n*price; 17 | } 18 | 19 | virtual void show(std::size_t n) const {} = 0; 20 | 21 | private: 22 | std::string bookNo; 23 | protected: 24 | doube price = 0.0; 25 | } 26 | 27 | class Bulk_quote final: public Quote{ 28 | public: 29 | double net_price(std::size_t ) const override; 30 | } 31 | -------------------------------------------------------------------------------- /CPP-Primer/chapter6.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void foo(const int i) 5 | { 6 | cout << "i:" << endl; 7 | } 8 | 9 | void foo_array(int *a) 10 | { 11 | cout << a[0] << endl; 12 | } 13 | 14 | void lookup(int *p) 15 | { 16 | *p = 20; 17 | cout << "no-const func" << *p << endl; 18 | } 19 | 20 | void lookup(const int *p) 21 | { 22 | cout << "const func" << *p << endl; 23 | } 24 | 25 | int global_a = 101; 26 | int global_b = 201; 27 | void defaultArg(int a = global_a,int b = global_b) 28 | { 29 | cout << "gloabl_a:" << a < 2 | #include 3 | using namespace std; 4 | 5 | 6 | int age = 10; 7 | 8 | class Person 9 | { 10 | public: 11 | typedef std::string::size_type H; 12 | Person(H height,unsigned int age = 20,string name = "Alice"): 13 | age(age), 14 | name(name) 15 | { 16 | ::age = 20; 17 | } 18 | 19 | Person(int agee) 20 | { 21 | age = agee; 22 | } 23 | 24 | Person(string name) 25 | { 26 | } 27 | 28 | Person() = default; 29 | inline void show() 30 | { 31 | cout << ::age << endl; 32 | cout << name << endl; 33 | } 34 | 35 | Person& add(const Person &p) 36 | { 37 | age += p.age; 38 | this->name = p.name; 39 | return *this; 40 | } 41 | private: 42 | unsigned int age; 43 | string name; 44 | }; 45 | 46 | 47 | int main() 48 | { 49 | Person person; 50 | 51 | int agee = 24; 52 | string name = "lzjqsdd"; 53 | person.add(name); 54 | person.show(); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /CPP-Primer/chapter8.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | string fis = "/home/lzjqsdd/a.txt"; 10 | string fos = "/home/lzjqsdd/b.txt"; 11 | //fstream strm(s.c_str()); 12 | //strm.close(); 13 | 14 | ifstream in(fis.c_str()); 15 | ofstream out(fos.c_str()); 16 | int a = 0; 17 | if(in && out){ 18 | while(in >> a) 19 | out << a << endl; 20 | //cout << a << endl; 21 | } 22 | 23 | string is = "abcdedf -12345"; 24 | string sx; 25 | istringstream sis(is); 26 | sis >> sx; 27 | cout << "sx:" << sx << endl; 28 | ostringstream sos;//不需要构造参数 29 | sos << sx << endl; //将sx输出到流sos中 30 | cout << "sos.str:" << sos.str() << endl; ///打印sos中的内容 31 | 32 | sos.clear(); 33 | double da = -2.15; 34 | string sa = "try"; 35 | sos << da << sa; 36 | cout << sos.str() << endl; //轻松实现itoa 37 | 38 | int aa; 39 | sis >> aa; 40 | cout << aa << endl; 41 | } 42 | -------------------------------------------------------------------------------- /CPP-Primer/query.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/CPP-Primer/query.cpp -------------------------------------------------------------------------------- /CrackInterview/Chapter3/Q3-6.cpp: -------------------------------------------------------------------------------- 1 | //将一个栈增序排序。不应该对该栈进行任何假设。程序中能用到的栈操作有:push | pop | peek | isEmpty。 2 | //Solve1: 构造一个临时的栈,用插入排序。(这个想法很秒) 3 | //初始空栈,弹出原栈S第一个元素压入临时栈STmp,出栈S的栈顶元素,如果S栈顶元素小于STmp栈顶元素,则把STmp元素压回原栈,直到小于S的栈顶元素。如果大于的话直接压入到临时栈。 4 | //然后重复上述操作,继续比较两个栈顶元素。 5 | //但是考虑到每次往回压到S中中已经比较过栈顶元素了,所以压入原栈的元素可以不用再次比较。再次开辟一个栈直接保存下来,或者采用计数器来优化操作。 6 | //Solve2: 出栈压入到优先队列中,然后再压回到原栈中。 -------------------------------------------------------------------------------- /CrackInterview/Chapter5/Q5.1-tip.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a = 1; //a是有符号数 7 | //如果最高位是1,右移若干位到达i,则最高为到i之间全是1 8 | cout << a << endl; 9 | a <<= 31; 10 | cout << a << endl; 11 | a >>= 29; 12 | cout << a << endl; 13 | } 14 | -------------------------------------------------------------------------------- /CrackInterview/Chapter5/Q5.1.cpp: -------------------------------------------------------------------------------- 1 | //You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j). 2 | // 3 | //EXAMPLE: 4 | //Input: N = 10000000000, M = 10101, i = 2, j = 6 5 | //Output: N = 10001010100 6 | //译文: 7 | //给定两个 32 位的数,N 和 M,还有两个指示位的数,i 和 j。 写程序使得 N 中第 i 位到第 j 位的值与 M 中的相同 (即:M 变成 N 的子串且位于 N 的第 i 位和第 j 位之间) 8 | //例子: 9 | //输入: N = 10000000000, M = 10101, i = 2, j = 6 10 | 11 | 12 | //Tips 13 | //将数末尾n位置为0,可以通过先右移n位,再左n位。 14 | //取x末尾的n位数。(1<> (j+1) << (j+1))|(m << i)|ret; 25 | } 26 | 27 | //方案2: 28 | //n的中间i-j位为0,其他位为1作为mask,然后和n做位与运算,得到的是n中间段被清0. 29 | //然后用上述结果和(m< 5 | using namespace std; 6 | 7 | Factory::Factory() 8 | {} 9 | 10 | Factory::~Factory() 11 | {} 12 | 13 | ConcreteFactory::ConcreteFactory() 14 | { 15 | cout << "ConcreteFactory....." << endl; 16 | } 17 | 18 | ConcreteFactory::~ConcreteFactory() 19 | {} 20 | 21 | Product * ConcreteFactory::CreateProduct() 22 | { 23 | return new ConcreteProduct(); 24 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(1)-Factory/Factory.h: -------------------------------------------------------------------------------- 1 | #ifndef _FACTORY_H_ 2 | #define _FACTORY_H_ 3 | 4 | class Product; 5 | 6 | class Factory 7 | { 8 | public: 9 | virtual ~Factory() = 0; 10 | virtual Product* CreateProduct() = 0; 11 | protected: 12 | Factory(); 13 | private: 14 | }; 15 | 16 | class ConcreteFactory:public Factory 17 | { 18 | public: 19 | ~ConcreteFactory(); 20 | ConcreteFactory(); 21 | Product* CreateProduct(); 22 | protected: 23 | private: 24 | 25 | }; 26 | 27 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(1)-Factory/Product.cpp: -------------------------------------------------------------------------------- 1 | #include "Product.h" 2 | 3 | #include 4 | using namespace std; 5 | 6 | Product::Product() 7 | {} 8 | 9 | Product::~Product() 10 | {} 11 | 12 | ConcreteProduct::ConcreteProduct() 13 | { 14 | cout << "ConcreteProduct..." << endl; 15 | }; 16 | 17 | ConcreteProduct::~ConcreteProduct() 18 | {}; -------------------------------------------------------------------------------- /DesignPattern/CreateMode(1)-Factory/Product.h: -------------------------------------------------------------------------------- 1 | #ifndef _PRODUCT_H_ 2 | #define _PRODUCT_H_ 3 | 4 | class Product 5 | { 6 | public: 7 | virtual ~Product() = 0; 8 | protected: 9 | Product(); //屏蔽构造函数 10 | private: 11 | 12 | }; 13 | 14 | class ConcreteProduct: public Product 15 | { 16 | public: 17 | ~ConcreteProduct(); 18 | ConcreteProduct(); 19 | protected: 20 | private: 21 | }; 22 | 23 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(1)-Factory/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Factory.h" 2 | #include "Product.h" 3 | #include 4 | using namespace std; 5 | 6 | int main(int argc, char **argv) 7 | { 8 | Factory *fac = new ConcreteFactory(); 9 | Product * p = fac->CreateProduct(); 10 | return 0; 11 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(2)-AbstractFactory/AbstractFactory.cpp: -------------------------------------------------------------------------------- 1 | #include "Product.h" 2 | #include "AbstractFactory.h" 3 | 4 | #include 5 | using namespace std; 6 | 7 | AbstractFactory::AbstractFactory() 8 | { 9 | 10 | } 11 | 12 | AbstractFactory::~AbstractFactory() 13 | { 14 | 15 | } 16 | 17 | ConcreteFactory1::ConcreteFactory1() 18 | { 19 | 20 | } 21 | 22 | ConcreteFactory1::~ConcreteFactory1() 23 | { 24 | 25 | } 26 | 27 | AbstractProductA* ConcreteFactory1::CreateProductA() 28 | { 29 | cout << "CreateProductA By ConcreteFactory1" << endl; 30 | return new ProductA1(); //这个工厂生产的是A1和B2的产品 31 | } 32 | 33 | AbstractProductB* ConcreteFactory1::CreateProductB() 34 | { 35 | cout << "CreateProductB By ConcreteFactory1" << endl; 36 | return new ProductB2(); 37 | } 38 | 39 | 40 | ConcreteFactory2::ConcreteFactory2() 41 | { 42 | 43 | } 44 | 45 | ConcreteFactory2::~ConcreteFactory2() 46 | { 47 | 48 | } 49 | 50 | AbstractProductA* ConcreteFactory2::CreateProductA() 51 | { 52 | cout << "CreateProductA By ConcreteFactory2" << endl; 53 | return new ProductA2(); //这个工厂生产A2和B1的产品 54 | } 55 | 56 | AbstractProductB* ConcreteFactory2::CreateProductB() 57 | { 58 | cout << "CreateProductB By ConcreteFactory2" << endl; 59 | return new ProductB1(); 60 | } 61 | -------------------------------------------------------------------------------- /DesignPattern/CreateMode(2)-AbstractFactory/AbstractFactory.h: -------------------------------------------------------------------------------- 1 | #ifndef ABSTRACTFACTORY_H_ 2 | #define ABSTRACTFACTORY_H_ 3 | 4 | class AbstractProductA; 5 | class AbstractProductB; 6 | 7 | class AbstractFactory 8 | { 9 | public: 10 | virtual ~AbstractFactory(); 11 | virtual AbstractProductA* CreateProductA() = 0; 12 | virtual AbstractProductB* CreateProductB() = 0; 13 | protected: 14 | AbstractFactory(); 15 | private: 16 | }; 17 | 18 | class ConcreteFactory1:public AbstractFactory 19 | { 20 | public: 21 | ConcreteFactory1(); 22 | ~ConcreteFactory1(); 23 | AbstractProductA* CreateProductA(); 24 | AbstractProductB* CreateProductB(); 25 | protected: 26 | private: 27 | }; 28 | 29 | class ConcreteFactory2:public AbstractFactory 30 | { 31 | public: 32 | ConcreteFactory2(); 33 | ~ConcreteFactory2(); 34 | AbstractProductA* CreateProductA(); 35 | AbstractProductB* CreateProductB(); 36 | protected: 37 | private: 38 | }; 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /DesignPattern/CreateMode(2)-AbstractFactory/Product.cpp: -------------------------------------------------------------------------------- 1 | #include "Product.h" 2 | #include 3 | using namespace std; 4 | 5 | AbstractProductA::AbstractProductA() 6 | { 7 | 8 | } 9 | 10 | AbstractProductA::~AbstractProductA() 11 | { 12 | 13 | } 14 | 15 | AbstractProductB::AbstractProductB() 16 | { 17 | 18 | } 19 | 20 | AbstractProductB::~AbstractProductB() 21 | { 22 | 23 | } 24 | 25 | ProductA1::ProductA1() 26 | { 27 | cout << "ProductA1..." << endl; 28 | } 29 | 30 | ProductA1::~ProductA1() 31 | { 32 | 33 | } 34 | 35 | ProductA2::ProductA2() 36 | { 37 | cout << "ProductA2..." << endl; 38 | } 39 | 40 | ProductA2::~ProductA2() 41 | { 42 | 43 | } 44 | 45 | ProductB1::ProductB1() 46 | { 47 | cout << "ProductB1..." << endl; 48 | } 49 | 50 | ProductB1::~ProductB1() 51 | { 52 | 53 | } 54 | 55 | ProductB2::ProductB2() 56 | { 57 | cout << "ProductB2..." << endl; 58 | } 59 | 60 | ProductB2::~ProductB2() 61 | { 62 | 63 | } 64 | -------------------------------------------------------------------------------- /DesignPattern/CreateMode(2)-AbstractFactory/Product.h: -------------------------------------------------------------------------------- 1 | #ifndef _PRODUCT_H_ 2 | #define _PRODUCT_H_ 3 | class AbstractProductA //产品A 4 | { 5 | public: 6 | virtual ~AbstractProductA(); 7 | protected: 8 | AbstractProductA(); //抽象基类不能实例化 9 | private: 10 | }; 11 | 12 | 13 | class AbstractProductB //产品B 14 | { 15 | public: 16 | virtual ~AbstractProductB(); 17 | protected: 18 | AbstractProductB(); 19 | private: 20 | }; 21 | 22 | 23 | class ProductA1:public AbstractProductA 24 | { 25 | public: 26 | ProductA1(); 27 | ~ProductA1(); 28 | protected: 29 | private: 30 | }; 31 | 32 | class ProductA2:public AbstractProductA 33 | { 34 | public: 35 | ProductA2(); 36 | ~ProductA2(); 37 | protected: 38 | private: 39 | }; 40 | 41 | class ProductB1:public AbstractProductB 42 | { 43 | public: 44 | ProductB1(); 45 | ~ProductB1(); 46 | protected: 47 | private: 48 | }; 49 | 50 | class ProductB2:public AbstractProductB 51 | { 52 | public: 53 | ProductB2(); 54 | ~ProductB2(); 55 | protected: 56 | private: 57 | }; 58 | 59 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(2)-AbstractFactory/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Product.h" 2 | #include "AbstractFactory.h" 3 | 4 | int main(int argc,char **argv) 5 | { 6 | AbstractFactory *af1 = new ConcreteFactory1(); 7 | af1->CreateProductA(); 8 | af1->CreateProductB(); 9 | 10 | AbstractFactory *af2 = new ConcreteFactory2(); 11 | af2->CreateProductA(); 12 | af2->CreateProductB(); 13 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(3)-Singleton/Singleon.cpp: -------------------------------------------------------------------------------- 1 | #include "Singleton.h" 2 | 3 | #include 4 | using namespace std; 5 | 6 | Singleton* Singleton::_instance = NULL; //静态成员初始化在类外部 7 | pthread_mutex_t Singleton::mutex; 8 | 9 | Singleton::Singleton() 10 | { 11 | pthread_mutex_init(&mutex,NULL); 12 | cout << "Singleton..." << endl; 13 | } 14 | 15 | Singleton* Singleton::instance() 16 | { 17 | if(_instance == NULL) 18 | { 19 | pthread_mutex_lock(&mutex); 20 | if(_instance == NULL) 21 | _instance = new Singleton(); 22 | pthread_mutex_unlock(&mutex); 23 | } 24 | 25 | return _instance; 26 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(3)-Singleton/Singleton.h: -------------------------------------------------------------------------------- 1 | #ifndef _SINGLETON_H_ 2 | #define _SINGLETON_H_ 3 | #include 4 | class Singleton 5 | { 6 | public: 7 | static Singleton* instance(); 8 | protected: 9 | Singleton(); 10 | Singleton(const Singleton&); //将拷贝构造和=操作符也保护起来,防止被复制 11 | Singleton& operator=(const Singleton&); 12 | private: 13 | static Singleton* _instance; 14 | static pthread_mutex_t mutex; //线程互斥锁 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(3)-Singleton/Singleton2.cpp: -------------------------------------------------------------------------------- 1 | #include "Singleton2.h" 2 | #include 3 | using namespace std; 4 | 5 | Singleton2* Singleton2::_instance = new Singleton2(); 6 | 7 | Singleton2::Singleton2() 8 | { 9 | cout << "Singleton2..." << endl; 10 | } 11 | 12 | Singleton2* Singleton2::instance() 13 | { 14 | return _instance; 15 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(3)-Singleton/Singleton2.h: -------------------------------------------------------------------------------- 1 | #ifndef _SINGLETON2_H_ 2 | #define _SINGLETON2_H_ 3 | 4 | class Singleton2 5 | { 6 | public: 7 | static Singleton2* instance(); 8 | protected: 9 | Singleton2(); 10 | Singleton2& operator=(const Singleton2&); 11 | Singleton2(const Singleton2&); 12 | private: 13 | static Singleton2 * _instance; 14 | }; 15 | 16 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(3)-Singleton/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Singleton.h" 2 | #include "Singleton2.h" 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | Singleton *s1 = Singleton::instance(); 10 | Singleton *s2 = Singleton::instance(); //实例只会被创建一次 11 | 12 | if(s1 == s2) cout << "s1 == s2" << endl; 13 | 14 | Singleton2 *s3 = Singleton2::instance(); 15 | Singleton2 *s4 = Singleton2::instance(); 16 | 17 | if(s3 == s4) cout << "s3 == s3" << endl; 18 | 19 | //运行会发现Singleton2先输出,因为其在定义时就创建了对象。 20 | return 0; 21 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(4)-Builder/Builder.cpp: -------------------------------------------------------------------------------- 1 | #include "Builder.h" 2 | #include "Product.h" 3 | 4 | #include 5 | using namespace std; 6 | 7 | Builder::Builder() 8 | {} 9 | Builder::~Builder() 10 | {} 11 | 12 | ConcreteBuilder::ConcreteBuilder() 13 | { 14 | 15 | } 16 | 17 | ConcreteBuilder::~ConcreteBuilder() 18 | { 19 | 20 | } 21 | 22 | void ConcreteBuilder::BuilderPartA(const string& buildPara) 23 | { 24 | cout << "Step1: Build ParaA... " << buildPara << endl; 25 | } 26 | void ConcreteBuilder::BuilderPartB(const string& buildPara) 27 | { 28 | cout << "Step2: Build ParaB... " << buildPara << endl; 29 | } 30 | void ConcreteBuilder::BuilderPartC(const string& buildPara) 31 | { 32 | cout << "Step3: Build ParaC... " << buildPara << endl; 33 | } 34 | void ConcreteBuilder::BuilderPartD(const string& buildPara) 35 | { 36 | cout << "Step4: Build ParaD... " << buildPara << endl; 37 | } 38 | 39 | Product* ConcreteBuilder::GetProduct() 40 | { 41 | BuilderPartA("pre-defined"); //默认参数 42 | BuilderPartB("pre-defined"); 43 | BuilderPartC("pre-defined"); 44 | BuilderPartD("pre-defined"); 45 | 46 | return new Product(); 47 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(4)-Builder/Builder.h: -------------------------------------------------------------------------------- 1 | #ifndef _BUILDER_H_ 2 | #define _BUILDER_H_ 3 | #include 4 | using namespace std; 5 | 6 | class Product; 7 | 8 | class Builder //统一建筑步骤接口 9 | { 10 | public: 11 | virtual ~Builder(); 12 | virtual void BuilderPartA(const string &buildPara) = 0; 13 | virtual void BuilderPartB(const string &buildPara) = 0; 14 | virtual void BuilderPartC(const string &buildPara) = 0; 15 | virtual void BuilderPartD(const string &buildPara) = 0; 16 | 17 | virtual Product* GetProduct() = 0; 18 | protected: 19 | Builder(); 20 | private: 21 | }; 22 | 23 | class ConcreteBuilder:public Builder //可以有不同的工人(或者建筑队) 24 | { 25 | public: 26 | ConcreteBuilder(); 27 | ~ConcreteBuilder(); 28 | void BuilderPartA(const string &buildPara); //每层可以有不同的设计风格,用参数来控制 29 | void BuilderPartB(const string &buildPara); 30 | void BuilderPartC(const string &buildPara); 31 | void BuilderPartD(const string &buildPara); 32 | 33 | Product* GetProduct(); 34 | protected: 35 | private: 36 | }; 37 | 38 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(4)-Builder/Director.cpp: -------------------------------------------------------------------------------- 1 | #include "Director.h" 2 | #include "Builder.h" 3 | 4 | Director::Director(Builder *bld) 5 | { 6 | _bld = bld; 7 | } 8 | 9 | Director::~Director() 10 | { 11 | 12 | } 13 | 14 | void Director::Construct() //设计师来指定每层的建筑风格 15 | { 16 | _bld->BuilderPartA("user-defined"); 17 | _bld->BuilderPartB("user-defined"); 18 | _bld->BuilderPartC("user-defined"); 19 | _bld->BuilderPartD("user-defined"); 20 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(4)-Builder/Director.h: -------------------------------------------------------------------------------- 1 | #ifndef _DIRECTOR_H_ 2 | #define _DIRECTOR_H 3 | 4 | class Builder; 5 | class Director 6 | { 7 | public: 8 | Director(Builder* bld); 9 | ~Director(); 10 | void Construct(); 11 | protected: 12 | private: 13 | Builder* _bld; //设计师管理者建筑师(工人) 14 | }; 15 | 16 | 17 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(4)-Builder/Product.cpp: -------------------------------------------------------------------------------- 1 | //Product.cpp 2 | #include "Product.h" 3 | #include 4 | using namespace std; 5 | 6 | Product::Product() 7 | { 8 | ProductPart(); 9 | cout << "return a product" << endl; 10 | } 11 | 12 | Product::~Product() 13 | { 14 | 15 | } 16 | 17 | void Product::ProducePart() 18 | { 19 | cout << "build part of product..." << endl; 20 | } 21 | 22 | ProductPart::ProductPart() 23 | { 24 | 25 | } 26 | 27 | ProductPart::~ProductPart() 28 | { 29 | 30 | } 31 | 32 | ProductPart* ProductPart::BuildPart() 33 | { 34 | return new ProductPart; 35 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(4)-Builder/Product.h: -------------------------------------------------------------------------------- 1 | #ifndef _PRODUCT_H_ 2 | #define _PRODUCT_H_ 3 | class Product 4 | { 5 | public: 6 | Product(); 7 | ~Product(); 8 | void ProducePart(); 9 | protected: 10 | private: 11 | }; 12 | 13 | 14 | class ProductPart 15 | { 16 | public: 17 | ProductPart(); 18 | ~ProductPart(); 19 | ProductPart* BuildPart(); 20 | protected: 21 | private: 22 | }; 23 | 24 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(4)-Builder/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Director.h" 2 | #include "Builder.h" 3 | #include "Product.h" 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | Director* d = new Director(new ConcreteBuilder()); 11 | d->Construct(); 12 | return 0; 13 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(5)-Prototype/Prototype.cpp: -------------------------------------------------------------------------------- 1 | #include "Prototype.h" 2 | #include 3 | using namespace std; 4 | 5 | Prototype::Prototype() 6 | {} 7 | 8 | Prototype::~Prototype() 9 | {} 10 | 11 | Prototype* Prototype::Clone() const 12 | { 13 | return NULL; 14 | } 15 | 16 | ConcretePrototype::ConcretePrototype() 17 | { 18 | x = 2; 19 | } 20 | 21 | ConcretePrototype::ConcretePrototype(const ConcretePrototype &cp) 22 | { 23 | cout << "ConcretePrototype copy..." << endl; 24 | x = cp.x; //可以使用默认的memberwise方式实现拷贝构造。 25 | } 26 | 27 | ConcretePrototype::~ConcretePrototype() 28 | { 29 | 30 | } 31 | 32 | Prototype* ConcretePrototype::Clone() const 33 | { 34 | return new ConcretePrototype(*this); 35 | } -------------------------------------------------------------------------------- /DesignPattern/CreateMode(5)-Prototype/Prototype.h: -------------------------------------------------------------------------------- 1 | #ifndef _PROTOTYPE_H_ 2 | #define _PROTOTYPE_H_ 3 | 4 | class Prototype 5 | { 6 | public: 7 | virtual ~Prototype(); 8 | virtual Prototype * Clone() const; 9 | int x; 10 | protected: 11 | Prototype(); 12 | }; 13 | 14 | class ConcretePrototype:public Prototype 15 | { 16 | public: 17 | ConcretePrototype(); 18 | ConcretePrototype(const ConcretePrototype& cp); //拷贝构造 19 | ~ConcretePrototype(); 20 | Prototype *Clone() const; 21 | protected: 22 | private: 23 | }; 24 | 25 | #endif -------------------------------------------------------------------------------- /DesignPattern/CreateMode(5)-Prototype/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Prototype.h" 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | Prototype *p1 = new ConcretePrototype(); 8 | Prototype *p2 = p1->Clone(); 9 | 10 | cout << p2->x << endl; 11 | return 0; 12 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(1)-Adapter/Adapter.cpp: -------------------------------------------------------------------------------- 1 | #include "Adapter.h" 2 | #include 3 | using namespace std; 4 | 5 | Target::Target() 6 | { 7 | 8 | } 9 | Target::~Target() 10 | { 11 | 12 | } 13 | 14 | void Target::Request() 15 | { 16 | cout << "Target::Request" << endl; 17 | } 18 | 19 | Adaptee::Adaptee() 20 | {} 21 | 22 | Adaptee::~Adaptee() 23 | {} 24 | 25 | void Adaptee::SpecificRequest() 26 | { 27 | cout <<"Adaptee::SpecificRequest" << endl; 28 | } 29 | 30 | Adapter::Adapter() 31 | {} 32 | 33 | Adapter::~Adapter() 34 | {} 35 | 36 | void Adapter::Request() 37 | { 38 | this->SpecificRequest(); 39 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(1)-Adapter/Adapter.h: -------------------------------------------------------------------------------- 1 | #ifndef _ADAPTER_H_ 2 | #define _ADAPTER_H_ 3 | 4 | //类模式的Adapter实现,在类层面实现了适配器 5 | 6 | class Target //客户要求的接口 7 | { 8 | public: 9 | Target(); 10 | virtual ~Target(); 11 | virtual void Request(); 12 | protected: 13 | private: 14 | }; 15 | 16 | class Adaptee //第三方要适配的类 17 | { 18 | public: 19 | Adaptee(); 20 | ~Adaptee(); 21 | void SpecificRequest(); 22 | protected: 23 | private: 24 | }; 25 | 26 | class Adapter:public Target,private Adaptee //适配器把两个不匹配的类通过多重继承方式连接起来 27 | { 28 | public: 29 | Adapter(); 30 | ~Adapter(); 31 | void Request(); 32 | protected: 33 | private: 34 | }; 35 | 36 | 37 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(1)-Adapter/Adapter1.cpp: -------------------------------------------------------------------------------- 1 | #include "Adapter1.h" 2 | #include 3 | using namespace std; 4 | 5 | Target::Target() 6 | { 7 | 8 | } 9 | Target::~Target() 10 | { 11 | 12 | } 13 | 14 | void Target::Request() 15 | { 16 | cout << "Target::Request" << endl; 17 | } 18 | 19 | Adaptee::Adaptee() 20 | {} 21 | 22 | Adaptee::~Adaptee() 23 | {} 24 | 25 | void Adaptee::SpecificRequest() 26 | { 27 | cout <<"Adaptee::SpecificRequest" << endl; 28 | } 29 | 30 | Adapter::Adapter(Adaptee *ade) 31 | { 32 | this->_ade = ade; 33 | } 34 | 35 | Adapter::~Adapter() 36 | {} 37 | 38 | void Adapter::Request() 39 | { 40 | this->_ade->SpecificRequest(); 41 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(1)-Adapter/Adapter1.h: -------------------------------------------------------------------------------- 1 | #ifndef _ADAPTER_H_ 2 | #define _ADAPTER_H_ 3 | 4 | //对象模式的Adapter实现,适配器继承自客户要求的接口,同时成员包含了第三方类对象。 5 | 6 | class Target //客户要求的接口 7 | { 8 | public: 9 | Target(); 10 | virtual ~Target(); 11 | virtual void Request(); 12 | protected: 13 | private: 14 | }; 15 | 16 | class Adaptee //第三方要适配的类 17 | { 18 | public: 19 | Adaptee(); 20 | ~Adaptee(); 21 | void SpecificRequest(); 22 | protected: 23 | private: 24 | }; 25 | 26 | class Adapter:public Target //适配器把两个不匹配的类通过多重继承方式连接起来 27 | { 28 | public: 29 | Adapter(Adaptee* ade); 30 | ~Adapter(); 31 | void Request(); 32 | protected: 33 | private: 34 | Adaptee* _ade; 35 | }; 36 | 37 | 38 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(1)-Adapter/main.cpp: -------------------------------------------------------------------------------- 1 | //main.cpp 2 | //#include "Adapter.h" 3 | #include "Adapter1.h" 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | Target *adt = new Adapter(new Adaptee); //直接用上适配器,把Adaptee适配了。 10 | adt->Request(); 11 | 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /DesignPattern/StructMode(2)-Decorator/Decorator.cpp: -------------------------------------------------------------------------------- 1 | #include "Decorator.h" 2 | #include 3 | using namespace std; 4 | 5 | Component::Component() 6 | { 7 | } 8 | 9 | Component::~Component() 10 | { 11 | } 12 | 13 | void Component::Operation() 14 | { 15 | 16 | } 17 | 18 | ConcreteComponent::ConcreteComponent() 19 | {} 20 | 21 | ConcreteComponent::~ConcreteComponent() 22 | {} 23 | 24 | void ConcreteComponent::Operation() 25 | { 26 | cout << "ConcreteComponent Operation" << endl; 27 | } 28 | 29 | Decorator::Decorator(Component *com) 30 | { 31 | this->_com = com; 32 | } 33 | 34 | Decorator::~Decorator() 35 | { 36 | } 37 | 38 | void Decorator::Operation() 39 | { 40 | } 41 | 42 | ConcreteDecorator::ConcreteDecorator(Component *com): 43 | Decorator(com) 44 | { 45 | } 46 | 47 | ConcreteDecorator::~ConcreteDecorator() 48 | { 49 | delete _com; 50 | } 51 | 52 | void ConcreteDecorator::Operation() 53 | { 54 | _com->Operation(); 55 | this->Addedbehavior(); //好吧,在这里加装饰了。挂上帘子了 56 | } 57 | 58 | void ConcreteDecorator::Addedbehavior() 59 | { 60 | std::cout<<"ConcreteDecorator::AddedBehacior...."< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | Component *com = new ConcreteComponent(); 8 | Decorator* dec = new ConcreteDecorator(com); 9 | 10 | dec->Operation(); 11 | 12 | delete dec; 13 | return 0; 14 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(3)-Bridge/Abstraction.cpp: -------------------------------------------------------------------------------- 1 | //Abstraction.cpp 2 | #include "Abstraction.h" 3 | #include "AbstractionImp.h" 4 | #include 5 | using namespace std; 6 | Abstraction::Abstraction() 7 | { 8 | } 9 | Abstraction::~Abstraction() 10 | { 11 | } 12 | RefinedAbstraction::RefinedAbstraction(AbstractionImp* imp) 13 | { 14 | _imp = imp; 15 | } 16 | RefinedAbstraction::~RefinedAbstraction() 17 | { 18 | } 19 | 20 | void RefinedAbstraction::Operation() 21 | { 22 | _imp->Operation(); 23 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(3)-Bridge/Abstraction.h: -------------------------------------------------------------------------------- 1 | //Abstraction.h 2 | #ifndef _ABSTRACTION_H_ 3 | #define _ABSTRACTION_H_ 4 | 5 | 6 | 7 | class AbstractionImp; //声明 8 | 9 | class Abstraction 10 | { 11 | public: 12 | virtual ~Abstraction(); 13 | virtual void Operation() = 0; //这个operation应该指的是两个维度类之间的关系。比方颜色给形状填充的过程。 14 | protected: 15 | Abstraction(); 16 | private: 17 | }; 18 | 19 | 20 | class RefinedAbstraction:public Abstraction 21 | { 22 | public: 23 | RefinedAbstraction(AbstractionImp *imp); 24 | ~RefinedAbstraction(); 25 | void Operation(); 26 | protected: 27 | private: 28 | AbstractionImp *_imp; // 29 | }; 30 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(3)-Bridge/AbstractionImp.cpp: -------------------------------------------------------------------------------- 1 | //AbstractionImp.cpp 2 | #include "AbstractionImp.h" 3 | #include 4 | using namespace std; 5 | AbstractionImp::AbstractionImp() 6 | { 7 | } 8 | AbstractionImp::~AbstractionImp() 9 | { 10 | } 11 | void AbstractionImp::Operation() 12 | { 13 | cout<<"AbstractionImp....imp..."< 5 | using namespace std; 6 | int main(int argc,char* argv[]) 7 | { 8 | AbstractionImp* imp = new ConcreteAbstractionImpB(); 9 | Abstraction* abs = new RefinedAbstraction(imp); 10 | abs->Operation(); 11 | return 0; 12 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(4)-Composite/Component.cpp: -------------------------------------------------------------------------------- 1 | //Component.cpp 2 | #include "Component.h" 3 | Component::Component() 4 | { 5 | } 6 | Component::~Component() 7 | { 8 | } 9 | void Component::Add(const Component &com) 10 | { 11 | } 12 | Component *Component::GetChild(int index) 13 | { 14 | return 0; 15 | } 16 | void Component::Remove(const Component &com) 17 | { 18 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(4)-Composite/Component.h: -------------------------------------------------------------------------------- 1 | //Component.h 2 | #ifndef _COMPONENT_H_ 3 | #define _COMPONENT_H_ 4 | class Component 5 | { 6 | public: 7 | Component(); 8 | virtual ~Component(); 9 | 10 | public: 11 | virtual void Operation() = 0; 12 | virtual void Add(const Component&); 13 | virtual void Remove(const Component&); 14 | virtual Component* GetChild(int); 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(4)-Composite/Composite.cpp: -------------------------------------------------------------------------------- 1 | //Composite.cpp 2 | #include "Composite.h" 3 | #include "Component.h" 4 | #define NULL 0 //define NULL POINTOR 5 | Composite::Composite() 6 | { 7 | //vector::iterator itend = comVec.begin(); 8 | } 9 | Composite::~Composite() 10 | { 11 | } 12 | void Composite::Operation() 13 | { 14 | vector::iterator comIter = comVec.begin(); 15 | for (; comIter != comVec.end(); comIter++) 16 | { 17 | (*comIter)->Operation(); 18 | } 19 | } 20 | void Composite::Add(Component *com) 21 | { 22 | comVec.push_back(com); 23 | } 24 | void Composite::Remove(Component *com) 25 | { 26 | comVec.erase(&com); 27 | } 28 | Component *Composite::GetChild(int index) 29 | { 30 | return comVec[index]; 31 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(4)-Composite/Composite.h: -------------------------------------------------------------------------------- 1 | //Composite.h 2 | #ifndef _COMPOSITE_H_ 3 | #define _COMPOSITE_H_ 4 | #include "Component.h" 5 | #include 6 | using namespace std; 7 | class Composite:public Component 8 | { 9 | public: 10 | Composite(); 11 | ~Composite(); 12 | 13 | public: 14 | void Operation(); 15 | void Add(Component *com); 16 | void Remove(Component *com); 17 | Component *GetChild(int index); 18 | 19 | protected: 20 | private: 21 | vector comVec; 22 | }; 23 | 24 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(4)-Composite/Leaf.cpp: -------------------------------------------------------------------------------- 1 | //Leaf.cpp 2 | #include "Leaf.h" 3 | #include 4 | using namespace std; 5 | Leaf::Leaf() 6 | { 7 | } 8 | Leaf::~Leaf() 9 | { 10 | } 11 | void Leaf::Operation() 12 | { 13 | cout << "Leaf operation....." << endl; 14 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(4)-Composite/Leaf.h: -------------------------------------------------------------------------------- 1 | //Leaf.h 2 | #ifndef _LEAF_H_ 3 | #define _LEAF_H_ 4 | #include "Component.h" 5 | class Leaf : public Component 6 | { 7 | public: 8 | Leaf(); 9 | ~Leaf(); 10 | void Operation(); 11 | 12 | protected: 13 | private: 14 | }; 15 | #endif //~_LEAF_H_ -------------------------------------------------------------------------------- /DesignPattern/StructMode(4)-Composite/main.cpp: -------------------------------------------------------------------------------- 1 | //main.cpp 2 | #include "Component.h" 3 | #include "Composite.h" 4 | #include "Leaf.h" 5 | #include 6 | using namespace std; 7 | int main(int argc, char *argv[]) 8 | { 9 | Leaf *l = new Leaf(); 10 | l->Operation(); 11 | Composite *com = new Composite(); 12 | com->Add(l); 13 | com->Operation(); 14 | Component *ll = com->GetChild(0); 15 | ll->Operation(); 16 | return 0; 17 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(5)-Flyweight/Flyweight.cpp: -------------------------------------------------------------------------------- 1 | #include "Flyweight.h" 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | Flyweight::Flyweight(string intrinsicState) 7 | { 8 | this->_intrinsicState = intrinsicState; 9 | } 10 | 11 | Flyweight::~Flyweight() 12 | { 13 | } 14 | 15 | void Flyweight::Operation(const string &extrinsicState) 16 | { 17 | } 18 | 19 | string Flyweight::GetIntrinsicState() 20 | { 21 | return this->_intrinsicState; 22 | } 23 | 24 | ConcreteFlyweight::ConcreteFlyweight(string intrinsicState) : Flyweight(intrinsicState) 25 | { 26 | cout << "ConcreteFlyweight Build....." << intrinsicState << endl; 27 | } 28 | 29 | ConcreteFlyweight::~ConcreteFlyweight() 30 | { 31 | } 32 | 33 | void ConcreteFlyweight::Operation(const string &extrinsicState) 34 | { 35 | cout << "ConcreteFlyweight:内蕴[" << this->GetIntrinsicState() << "] 外蕴[" << extrinsicState << "]" << endl; 36 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(5)-Flyweight/Flyweight.h: -------------------------------------------------------------------------------- 1 | #ifndef _FLYWEIGHT_H 2 | #define _FLYWEIGHT_H 3 | #include 4 | using namespace std; 5 | 6 | class Flyweight 7 | { 8 | public: 9 | virtual ~Flyweight(); 10 | virtual void Operation(const string &extrinsicState); 11 | string GetIntrinsicState(); 12 | 13 | protected: 14 | Flyweight(string intrinsicState); 15 | 16 | private: 17 | string _intrinsicState; 18 | }; 19 | 20 | class ConcreteFlyweight : public Flyweight 21 | { 22 | public: 23 | ConcreteFlyweight(string intrinsicState); 24 | ~ConcreteFlyweight(); 25 | void Operation(const string &extrinsicState); 26 | 27 | protected: 28 | private: 29 | }; 30 | 31 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(5)-Flyweight/FlyweightFactory.cpp: -------------------------------------------------------------------------------- 1 | //FlyweightFactory.cpp 2 | #include "FlyweightFactory.h" 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | FlyweightFactory::FlyweightFactory() 8 | { 9 | } 10 | FlyweightFactory::~FlyweightFactory() 11 | { 12 | } 13 | Flyweight *FlyweightFactory::GetFlyweight(const string &key) 14 | { 15 | vector::iterator it = _fly.begin(); 16 | for (; it != _fly.end(); it++) 17 | { 18 | //找到了,就一起用, ^_^ 19 | if ((*it)->GetIntrinsicState() == key) 20 | { 21 | cout << "already created by users...." << endl; 22 | return *it; 23 | } 24 | } 25 | Flyweight *fn = new ConcreteFlyweight(key); 26 | _fly.push_back(fn); 27 | return fn; 28 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(5)-Flyweight/FlyweightFactory.h: -------------------------------------------------------------------------------- 1 | //FlyweightFactory.h 2 | #ifndef _FLYWEIGHTFACTORY_H_ 3 | #define _FLYWEIGHTFACTORY_H_ 4 | #include "Flyweight.h" 5 | #include 6 | #include 7 | using namespace std; 8 | class FlyweightFactory 9 | { 10 | public: 11 | FlyweightFactory(); 12 | ~FlyweightFactory(); 13 | Flyweight *GetFlyweight(const string &key); 14 | 15 | protected: 16 | private: 17 | vector _fly; 18 | }; 19 | #endif //~_FLYWEIGHTFACTORY_H_ -------------------------------------------------------------------------------- /DesignPattern/StructMode(5)-Flyweight/main.cpp: -------------------------------------------------------------------------------- 1 | //main.cpp 2 | #include "Flyweight.h" 3 | #include "FlyweightFactory.h" 4 | #include 5 | using namespace std; 6 | int main(int argc, char *argv[]) 7 | { 8 | FlyweightFactory *fc = new FlyweightFactory(); 9 | Flyweight *fw1 = fc->GetFlyweight("hello"); 10 | fw1->Operation("testtest"); 11 | Flyweight *fw2 = fc->GetFlyweight("world!"); 12 | Flyweight *fw3 = fc->GetFlyweight("hello"); 13 | fw3->Operation("testtest2"); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(7)-Proxy/Proxy.cpp: -------------------------------------------------------------------------------- 1 | #include "Proxy.h" 2 | #include 3 | using namespace std; 4 | 5 | Proxy::Proxy(Subject* sub) 6 | { 7 | this->_sub = sub; 8 | } 9 | Proxy::~Proxy(){} 10 | void Proxy::Operation() 11 | { 12 | cout << "Proxy is Working..." << endl; 13 | this->_sub->Operation(); 14 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(7)-Proxy/Proxy.h: -------------------------------------------------------------------------------- 1 | #ifndef _PROXY_H_ 2 | #define _PROXY_H_ 3 | #include "Subject.h" 4 | 5 | class Subject; 6 | 7 | class Proxy:public Subject 8 | { 9 | public: 10 | Proxy(Subject *sub); 11 | ~Proxy(); 12 | void Operation(); 13 | private: 14 | Subject *_sub; 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(7)-Proxy/Subject.cpp: -------------------------------------------------------------------------------- 1 | #include "Subject.h" 2 | #include 3 | using namespace std; 4 | 5 | Subject::Subject(){} 6 | Subject::~Subject(){} 7 | void Subject::Operation(){} 8 | 9 | ConcreteSubject::ConcreteSubject(){} 10 | ConcreteSubject::~ConcreteSubject(){} 11 | void ConcreteSubject::Operation() 12 | { 13 | cout << "ConcreteSubject Operation ..." << endl; 14 | } -------------------------------------------------------------------------------- /DesignPattern/StructMode(7)-Proxy/Subject.h: -------------------------------------------------------------------------------- 1 | #ifndef _SUBJECT_H_ 2 | #define _SUBJECT_H_ 3 | 4 | class Subject 5 | { 6 | public: 7 | virtual ~Subject(); 8 | virtual void Operation(); 9 | protected: 10 | Subject(); 11 | }; 12 | 13 | class ConcreteSubject:public Subject 14 | { 15 | public: 16 | ConcreteSubject(); 17 | ~ConcreteSubject(); 18 | void Operation(); 19 | }; 20 | 21 | #endif -------------------------------------------------------------------------------- /DesignPattern/StructMode(7)-Proxy/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Subject.h" 2 | #include "Proxy.h" 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | Subject *ss = new ConcreteSubject(); 9 | Proxy *proxy = new Proxy(ss); 10 | proxy->Operation(); //用代理来处理 11 | return 0; 12 | } -------------------------------------------------------------------------------- /Leetcode/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "C++ Launch", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "program": "${workspaceRoot}/a.out", 9 | "args": [], 10 | "stopAtEntry": false, 11 | "cwd": "${workspaceRoot}", 12 | "environment": [], 13 | "externalConsole": true, 14 | "linux": { 15 | "MIMode": "gdb" 16 | }, 17 | "osx": { 18 | "MIMode": "lldb" 19 | }, 20 | "windows": { 21 | "MIMode": "gdb" 22 | } 23 | }, 24 | { 25 | "name": "C++ Attach", 26 | "type": "cppdbg", 27 | "request": "attach", 28 | "program": "enter program name, for example ${workspaceRoot}/a.out", 29 | "processId": "${command.pickProcess}", 30 | "linux": { 31 | "MIMode": "gdb" 32 | }, 33 | "osx": { 34 | "MIMode": "lldb" 35 | }, 36 | "windows": { 37 | "MIMode": "gdb" 38 | } 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /Leetcode/Q101.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSymmetric(TreeNode* root) { 13 | return solve(root,root); 14 | } 15 | 16 | bool solve(TreeNode *froot,TreeNode *broot) //左中右,右中左 17 | { 18 | if(froot!=NULL && broot!=NULL) 19 | { 20 | if(froot->val != broot->val) return false; 21 | else 22 | { 23 | return solve(froot->left,broot->right) && solve(froot->right,broot->left); 24 | } 25 | } 26 | else if((froot==NULL && broot!=NULL) || (froot!=NULL && broot==NULL)) //一个为空,一个不为空,不对称 27 | return false; 28 | return true; 29 | } 30 | }; -------------------------------------------------------------------------------- /Leetcode/Q103.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q103.cpp -------------------------------------------------------------------------------- /Leetcode/Q108.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一个数组,升序排列,把它转换成一个平衡的BST 2 | //思路:因为需要平衡的BST,而原有序列为有序,所以很朴素的想法,把原有序列等分,然后作为根节点。 3 | //因为原序列位链表,所以查找中点的代价为O(n),而二分建树需要O(logn),所有总复杂度为O(nlogn) 4 | 5 | //二分每次指定要分的长度,以及起始的位置。 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | TreeNode* sortedArrayToBST(vector& nums) { 19 | 20 | if(nums.size() == 0) return NULL; 21 | TreeNode *root = NULL; 22 | buildTree(nums,0,nums.size()-1,root); //传递的应该按照下标顺序,r-1,而不是r 23 | return root; 24 | } 25 | 26 | void buildTree(vector& nums,int l,int r,TreeNode *&root) 27 | { 28 | if(l <= r) 29 | { 30 | int mid = l+(r - l +1 )/2; //让中点偏右,(r-l)/2让中点偏左。 31 | root = new TreeNode(0); 32 | root->val = nums[mid]; 33 | buildTree(nums,l,mid-1,root->left); 34 | buildTree(nums,mid+1,r,root->right); 35 | } 36 | } 37 | }; -------------------------------------------------------------------------------- /Leetcode/Q11.cpp: -------------------------------------------------------------------------------- 1 | //给一个柱型图,每个柱子长度非零。求最多可以盛多少水?每个柱子都是一个容器,如果两个柱子之间的柱子比较低,还可以在顶部盛水 2 | //找出两个柱子i,j,这两个柱子组成的容器的容量最大 3 | //波峰图 4 | 5 | //TwoPointers 6 | //从两端开始构建容器,(木桶原理) 7 | //如果i之后的柱子更低,是得不到更多的容量。所以下面代码两个while循环重新确定新的容器边界 8 | 9 | 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | class Solution 15 | { 16 | public: 17 | int maxArea(vector &height) 18 | { 19 | int maxv = 0; 20 | int i = 0; 21 | int j = height.size() - 1; 22 | while (i < j) 23 | { 24 | int h = min(height[i], height[j]); 25 | maxv = max(maxv, (j - i) * h); 26 | while (height[i] <= h && i < j) 27 | ++i; 28 | while (height[j] <= h && i < j) 29 | --j; 30 | } 31 | return maxv; 32 | } 33 | }; -------------------------------------------------------------------------------- /Leetcode/Q110.cpp: -------------------------------------------------------------------------------- 1 | //判断一个树是不是平衡二叉树 2 | /** 3 | * Definition for a binary tree node. 4 | * struct TreeNode { 5 | * int val; 6 | * TreeNode *left; 7 | * TreeNode *right; 8 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool isBalanced(TreeNode* root) { 14 | if(root==NULL) return true; 15 | int i=0; 16 | return solve(root,i); 17 | } 18 | 19 | //判断每个节点的子数是不是平衡树 20 | bool solve(TreeNode *root,int &i) 21 | { 22 | if(root==NULL) 23 | { i = 0;return true;} //叶节点看做空数,平衡 24 | 25 | int ld,rd; //子树从0开始计算 26 | bool lt = solve(root->left,ld); 27 | bool rt = solve(root->right,rd); 28 | cout << ld << "," << rd << endl; 29 | if(lt && rt) 30 | { 31 | int x = abs(ld-rd); 32 | if(x > 1) return false; 33 | else 34 | { 35 | i = 1+(ld > rd ? ld:rd); //如果子树平衡,递归上一层,记录上一层子树(左/右)最长的长度。 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | }; -------------------------------------------------------------------------------- /Leetcode/Q113.cpp: -------------------------------------------------------------------------------- 1 | //Path Sum II 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> pathSum(TreeNode* root, int sum) { 15 | if(root == NULL) return {}; 16 | vector path; 17 | solve(root,path,sum); 18 | return result; 19 | } 20 | 21 | void solve(TreeNode *root,vector& path,long sum) 22 | { 23 | path.push_back(root->val); sum-= root->val; 24 | if(root->left == NULL && root->right==NULL) 25 | { 26 | if(sum == 0) result.push_back(path); 27 | } 28 | if(root->left!=NULL) 29 | solve(root->left,path,sum); 30 | if(root->right!=NULL) 31 | solve(root->right,path,sum); 32 | 33 | sum+=root->val; path.erase(path.end()-1); 34 | 35 | } 36 | 37 | vector > result; 38 | }; -------------------------------------------------------------------------------- /Leetcode/Q116.cpp: -------------------------------------------------------------------------------- 1 | //Populating Next Right Pointers in Each Node 2 | -------------------------------------------------------------------------------- /Leetcode/Q119.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | //返回杨辉三角形第n排,空间为O(n) ,可以重复利用上一层的数据,递推处理 5 | 6 | class Solution { 7 | public: 8 | vector getRow(int rowIndex) { 9 | if(rowIndex == 0) return {1}; 10 | else if(rowIndex == 1) return {1,1}; 11 | else //从第三层开始 12 | { 13 | vector r = {1,1}; 14 | for(int k=2;k<=rowIndex;k++) //递推rowindex次 15 | { 16 | int tmp = r[0]; 17 | for(int i=1;i 11 | #include 12 | using namespace std; 13 | class Solution { 14 | public: 15 | string intToRoman(int num) { 16 | vector in = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 17 | vector ro = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 18 | 19 | int i = 0; 20 | string result; 21 | while(num) 22 | { 23 | int k = num / in[i]; 24 | while(k--) result+=ro[i]; 25 | num = num % in[i]; 26 | i++; 27 | } 28 | return result; 29 | } 30 | }; -------------------------------------------------------------------------------- /Leetcode/Q120.cpp: -------------------------------------------------------------------------------- 1 | //类似于杨辉三角形的形式,求最小路径和 2 | //DP ,每次保留上一层的结果 3 | //opt,一维,O(n) 4 | 5 | class Solution { 6 | public: 7 | int minimumTotal(vector>& triangle) { 8 | int n = triangle.size(); 9 | vector opt(n,0); 10 | opt[0] = triangle[0][0]; 11 | for(int i=1;i=0;j--) 14 | { 15 | if(j == i) 16 | opt[j] = triangle[i][j]+opt[j-1]; 17 | else if(j == 0) 18 | opt[j] = triangle[i][j]+opt[j]; 19 | else 20 | opt[j] = triangle[i][j]+min(opt[j-1],opt[j]); 21 | } 22 | } 23 | 24 | long minr = LONG_MAX; 25 | for(int i=0;i opt[i]) minr = opt[i]; 27 | 28 | return minr; 29 | } 30 | }; -------------------------------------------------------------------------------- /Leetcode/Q122.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q122.cpp -------------------------------------------------------------------------------- /Leetcode/Q124.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q124.cpp -------------------------------------------------------------------------------- /Leetcode/Q125.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q125.cpp -------------------------------------------------------------------------------- /Leetcode/Q128.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一个未排序的序列,求出最长的连续序列。不要求原来有序。3,2,1,4也是连续的。 2 | 3 | //思路:建立连续序列的集合,如果后续的元素可以将当前集合连接起来,则形成行的序列。 4 | //需要维护每个集合的区间边界 5 | //使用并查集来做。 6 | 7 | 8 | //并查集之所以查的快,其记录是以元素所属集合id为出发点,每个元素都有个集合的记录。 9 | 10 | 11 | //如下方案有些像并查集,但是合并的过程只考虑了边界的元素 12 | //find的复杂度为logn,如果用unordered_map查询速度为O(1) 13 | 14 | class Solution { 15 | public: 16 | int longestConsecutive(vector& nums) { 17 | int res = 0; 18 | map dict; 19 | for(auto x:nums) 20 | { 21 | if(dict.find(x) == dict.end()) 22 | { 23 | int left = dict.find(x-1) != dict.end() ? dict[x-1] : 0; 24 | int right = dict.find(x+1) != dict.end() ? dict[x+1] : 0; 25 | int sum = left + right +1; 26 | dict[x] = sum; 27 | res = max(res,sum); 28 | 29 | //扩展边界元素所属集合的长度 30 | dict[x-left] = sum; 31 | dict[x+right] = sum; 32 | } 33 | } 34 | return res; 35 | } 36 | }; -------------------------------------------------------------------------------- /Leetcode/Q129.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q129.cpp -------------------------------------------------------------------------------- /Leetcode/Q13.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string s = "CMXCIX"; 9 | map value{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}}; 10 | map level{{'I',1},{'V',2},{'X',3},{'L',4},{'C',5},{'D',6},{'M',7}}; 11 | 12 | if(s.size() == 0) return 0; 13 | int sum = value[s[s.size()-1]]; 14 | for(int i=s.size()-2;i>=0;i--) 15 | { 16 | if(level[s[i]] < level[s[i+1]]) //如果当前的比之前的level小,在左侧,要减 17 | sum -= value[s[i]]; 18 | else 19 | sum += value[s[i]]; 20 | } 21 | cout << sum << endl; 22 | return sum; 23 | 24 | } 25 | 26 | 27 | //第二遍:罗马数字转int 28 | //按照规则,如果右侧比左侧的大(表示级别),则减去左侧字符,否则加上 29 | //自右向左 30 | 31 | class Solution { 32 | public: 33 | int romanToInt(string s) { 34 | map value{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}}; 35 | map level{{'I',1},{'V',2},{'X',3},{'L',4},{'C',5},{'D',6},{'M',7}}; 36 | //如果出现减去左侧,只减左侧的一个字符代表的数,所以倒着统计 37 | if(s.size() == 0) return 0; 38 | if(s.size() == 1) return value[s[0]]; 39 | int sum = value[s[s.size()-1]]; 40 | for(int i = s.size()-2;i>=0;--i) 41 | { 42 | if(level[s[i]] < level[s[i+1]]) 43 | sum-= value[s[i]]; 44 | else 45 | sum+= value[s[i]]; 46 | } 47 | return sum; 48 | } 49 | }; -------------------------------------------------------------------------------- /Leetcode/Q137.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q137.cpp -------------------------------------------------------------------------------- /Leetcode/Q14.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q14.cpp -------------------------------------------------------------------------------- /Leetcode/Q141.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | 10 | //使用快慢指针判断是不是有环 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | if(head==NULL) return false; 15 | ListNode *p = head; 16 | ListNode *p2 = head->next; 17 | while(true) 18 | { 19 | if(p==p2) return true; 20 | if(p==NULL || p2==NULL) return false; //说明走到头了 21 | if(p!=NULL) 22 | p = p->next; 23 | if(p2!=NULL) 24 | { 25 | p2 = p2->next; 26 | if(p2!=NULL) p2 = p2->next; 27 | } 28 | 29 | } 30 | } 31 | }; -------------------------------------------------------------------------------- /Leetcode/Q142.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一个链表(有环),给出环开始的地方 2 | //先通过快慢指针得到相遇的位置,然后快指针速度置为1,慢指针从头开始,则相遇时即为环开始节点 3 | 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * struct ListNode { 8 | * int val; 9 | * ListNode *next; 10 | * ListNode(int x) : val(x), next(NULL) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode *detectCycle(ListNode *head) { 16 | ListNode*fast = head; 17 | ListNode*slow = head; 18 | while(fast && fast->next) //初始条件两个相同,所以while这里的条件使用fast来确定 19 | { 20 | fast = fast->next->next; 21 | slow = slow->next; 22 | if(fast == slow) break; 23 | } 24 | if(fast == NULL || fast->next==NULL) return NULL; //如果没有环就返回NULL 25 | slow = head; 26 | while(fast!=slow) 27 | { 28 | fast = fast->next; 29 | slow = slow->next; 30 | } 31 | return fast; 32 | } 33 | }; 34 | 35 | //或者对地址采用hash方法 -------------------------------------------------------------------------------- /Leetcode/Q144.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector preorderTraversal(TreeNode* root) { 13 | 14 | vector result; 15 | inorder(root,result); 16 | return result; 17 | } 18 | 19 | void inorder(TreeNode*root,vector&result) 20 | { 21 | if(root != NULL) 22 | { 23 | result.push_back(root->val); 24 | inorder(root->left,result); 25 | inorder(root->right,result); 26 | } 27 | } 28 | }; 29 | 30 | 31 | //非递归方法,借助外部的栈 32 | class Solution { 33 | public: 34 | vector inorderTraversal(TreeNode* root) { 35 | vector result; 36 | stack s; 37 | TreeNode *cur = root; 38 | while(!s.empty() || cur) 39 | { 40 | if(cur) //不断深度遍历左子树 41 | { 42 | result.push_back(cur->val); 43 | s.push(cur); //压栈 44 | cur = cur->left; 45 | } 46 | else 47 | { 48 | cur = s.top(); 49 | s.pop(); 50 | cur = cur->right; 51 | } 52 | } 53 | return result; 54 | } 55 | }; -------------------------------------------------------------------------------- /Leetcode/Q152.cpp: -------------------------------------------------------------------------------- 1 | //Maximum Product Subarray 2 | // [2,3,-2,4] 连续最大的乘积 3 | // 由于可能出现负数,所以负的最大乘以一个负数肯定更大。DP算法,每一步计算一个最大值,计算一个最小值 4 | // optMax[i] = max{ nums[i] * optMax[i-1], nums[i]*optMin[i-1],nums[i]}; 5 | // optMin[i] = min{ nums[i] * optMax[i-1], nums[i]*optMin[i-1],nums[i]}; 6 | 7 | class Solution { 8 | public: 9 | int maxProduct(vector& nums) { 10 | 11 | int maxp = nums[0],minp = nums[0],result = nums[0]; 12 | 13 | for(int i=1;i result) result = maxp; //保留规划过程中的最大值,最后一个maxp并非是最大的。Error 20 | } 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /Leetcode/Q153.cpp: -------------------------------------------------------------------------------- 1 | //给定一个数组,该数组之前是有序的,经过某个pivot旋转得到的。 2 | //求最小的数,数组中没有重复的元素 3 | 4 | //0 1 2 3 4 5 6 7 变为4 5 6 7 0 1 2 5 | //思路:直接找到转折点 6 | //7,6,5,4,3,2,1,0会出现么? 7 | //三种趋势,直上直下,直上,直下 8 | 9 | /*------------------ 10 | /\ / \ 11 | / \ / \ 12 | --------------------*/ 13 | 14 | class Solution { 15 | public: 16 | int findMin(vector& nums) { 17 | int i = 0; 18 | while(i < nums.size()-1 && nums[i] < nums[i+1]) ++i; //因为下降趋势停止有两种情况,直下和转折 19 | if(i == nums.size()-1) return nums.front(); //keep asend 20 | else 21 | { 22 | if(nums[i+1] < nums[i+2]) return nums[i+1]; 23 | else return nums.back(); 24 | } 25 | } 26 | }; 27 | 28 | 29 | //经典二分搜索问题 30 | //只要存在pivot,那么首元素肯定大于尾元素 31 | int findMin(vector &num) { 32 | int start=0,end=num.size()-1; 33 | 34 | while (start=num[start]) { 41 | start = mid+1; 42 | } else { 43 | end = mid; 44 | } 45 | } 46 | 47 | return num[start]; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Leetcode/Q160.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q160.cpp -------------------------------------------------------------------------------- /Leetcode/Q165.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q165.cpp -------------------------------------------------------------------------------- /Leetcode/Q167.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q167.cpp -------------------------------------------------------------------------------- /Leetcode/Q168.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //按照26进制来处理 7 | //给定的是正整数,所以从1开始 8 | //打表,数组表示为A-Z 对应0~25,下标为对应的数字.比如array[3]为Z 9 | //给定的数都减一,从0开始表示26进制更直观 10 | // (n-1)/26+1; n = (n-1)/26 why:因为即使是26也不能进位,然而进制确实26进制,所以为了刚好商刚好为26导致的余数 11 | // 为0,通过-1可以做到避免进位,但是余数就少了1,所以计算余数要再加1. 12 | // 余数应该是1~26, 13 | class Solution { 14 | public: 15 | string convertToTitle(int n) { 16 | string table = ".ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 17 | string result; 18 | while(n!=0) 19 | { 20 | int x = (n-1)%26+1; 21 | result.append(1,table[x]); 22 | n = (n-1)/26; 23 | } 24 | reverse(result.begin(),result.end()); 25 | cout << result << endl; 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /Leetcode/Q172.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | 看阶乘的这些数中,有多少个5, 6 | 第一遍看多少是5的倍数, 7 | 第二遍看多少是5^2的倍数, 8 | ... 9 | 10 | 0的阶乘是1,有0个0; 11 | 负数没有阶乘 12 | */ 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | int trailingZeroes(int n) { 19 | if(n<=0) return 0; 20 | int x = 5; 21 | int result = 0; 22 | int c = log(n)/log(5); 23 | for(int i=0;i& nums) { 7 | sort(nums.begin(),nums.end(),cmp); 8 | string result; //注意去除000000 9 | for(int x:nums) result+=to_string(x); 10 | 11 | } 12 | }; 13 | 14 | static bool cmp(const int &a,const int &b) 15 | { 16 | string sa = to_string(a); 17 | string sb = to_string(b); 18 | string tmp1 = sa+sb; 19 | string tmp2 = sb+sa; 20 | return tmp1 > tmp2 ? tmp1:tmp2; 21 | } 22 | 23 | //526,52 24 | //524,52 -------------------------------------------------------------------------------- /Leetcode/Q18.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q18.cpp -------------------------------------------------------------------------------- /Leetcode/Q189.cpp: -------------------------------------------------------------------------------- 1 | //Rotate Array 2 | class Solution { 3 | public: 4 | void rotate(vector& nums, int k) { 5 | k%=nums.size(); 6 | if(k > nums.size()/2) 7 | addtoback(nums,k); 8 | else 9 | addtofront(nums,k); 10 | } 11 | void addtofront(vector&nums,int k) 12 | { 13 | for(int i=0;i&nums,int k) 19 | { 20 | int rk = nums.size()-k; 21 | for(int i=0;i vec; 34 | for(int i=0;i<10;++i) 35 | vec.push_back(i+1); 36 | int last = *(vec.end()-1); 37 | int* pos = &vec[0]; 38 | memmove(pos+1 ,pos, sizeof(int)*(vec.size()-1)); 39 | *vec.begin() = last; -------------------------------------------------------------------------------- /Leetcode/Q19.cpp: -------------------------------------------------------------------------------- 1 | //Remove Nth Node From End of List 2 | //题意:给定链表,移除倒数第N个节点,并返回head 3 | //题目假定n输入始终合法 4 | 5 | //第一遍思路:把到时第n个转换为正的第len-n+1个。 6 | 7 | //第二遍 8 | //思路:如果只有一个节点,移除第一个之后链表为空.如果删除的是head呢? 9 | //two-pointers 10 | //让第一个指针先走n步,第二个指针开始走,当第一个指针达到尾部时,第二个指针刚好位于第n个节点 11 | //因为要删除的是第n个节点,定位到第n-1个节点,方便删除。 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * struct ListNode { 16 | * int val; 17 | * ListNode *next; 18 | * ListNode(int x) : val(x), next(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | ListNode* removeNthFromEnd(ListNode* head, int n) { 24 | ListNode *p = head,*q = head; 25 | while(n--) p = p->next; 26 | if(p == NULL) //说明删除的是头节点 27 | return head->next; 28 | while(p && p->next) 29 | { 30 | q = q->next; 31 | p = p->next; 32 | } 33 | 34 | if(q->next == NULL) return NULL; //只有一个节点 35 | else 36 | { 37 | q->next = q->next->next; 38 | } 39 | return head; 40 | } 41 | }; -------------------------------------------------------------------------------- /Leetcode/Q20.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | bool isVaild(string s) 8 | { 9 | if(s.size() == 0) return 0; 10 | stack sk; 11 | map dict = {{'(',')'},{'[',']'},{'{','}'},{'#','#'}; 12 | sk.push_back('#'); 13 | for(int i=0;i sk; 32 | sk.push('#'); //加入哨兵方便处理 33 | map dict = {{'(',')'},{'[',']'},{'{','}'},{'#','#'}}; 34 | for(int i = 0;i>= 1; 19 | n >>= 1; //只要小于,最后一位的所有数的AND操作都是0; 20 | //result <<= 1; 21 | result++; 22 | } 23 | return m << result; 24 | } 25 | }; -------------------------------------------------------------------------------- /Leetcode/Q202.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int solve(int i) 8 | { 9 | int sum = 0; 10 | while(i!=0) 11 | { 12 | int m = i%10; 13 | sum += m*m; 14 | i = i/10; 15 | } 16 | return sum; 17 | } 18 | 19 | int main() 20 | { 21 | int n; 22 | while(cin >> n) 23 | { 24 | vector history; 25 | while(true) 26 | { 27 | int s = solve(n); 28 | if(find(history.begin(),history.end(),s) != history.end()) //说明出现了 29 | break; 30 | cout << s << endl; 31 | if(s != 1) 32 | { 33 | history.push_back(s); //计入出现的数 34 | n = s; 35 | } 36 | else 37 | { 38 | cout << "happy" << endl; 39 | break; 40 | } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Leetcode/Q203.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q203.cpp -------------------------------------------------------------------------------- /Leetcode/Q205.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIsomorphic(string s, string t) { 4 | //同构首先长度得一致 5 | //if(s.size()!=t.size()) return false; //题目假设长度一致 6 | if(s.size()==0 && t.size() == 0) return true; 7 | map dict; 8 | map check; //看s是不是两个映射到一个字符了。记录被映射的字符 9 | for(int i=0;i tmp; 14 | ListNode *prev = NULL; 15 | ListNode *curr = head; 16 | while(curr!=NULL) 17 | { 18 | ListNode *nextTmp = curr->next; 19 | curr->next = prev; 20 | prev = curr; 21 | curr = nextTmp; 22 | } 23 | return prev; 24 | } 25 | }; -------------------------------------------------------------------------------- /Leetcode/Q21.cpp: -------------------------------------------------------------------------------- 1 | //合并两个有序的链表 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 14 | ListNode * result = new ListNode(0); 15 | ListNode *p = result; 16 | while(l1 && l2) //如果使用了l1&&l1->next,则会少最后一个元素。只要l1不为空,就说明有值 17 | { 18 | if(l1->val < l2->val) 19 | { 20 | p->next = l1; 21 | l1 = l1->next; 22 | } 23 | else 24 | { 25 | p->next = l2; 26 | l2 = l2->next; 27 | } 28 | p=p->next; 29 | } 30 | while(l1) {p->next = l1;l1=l1->next;p = p->next;} 31 | while(l2) {p->next = l2;l2=l2->next;p = p->next;} 32 | return result->next; 33 | } 34 | }; -------------------------------------------------------------------------------- /Leetcode/Q213.cpp: -------------------------------------------------------------------------------- 1 | //HouseRobber II 2 | //本题的房子是个环状,同样考虑动态规划,第一次考虑第一个而不考虑最后一个,第二次不考虑第一个而考虑最后一个,输出两次动态规划的最大值 3 | 4 | 5 | class Solution { 6 | public: 7 | int rob(vector& nums) { 8 | 9 | if(nums.size()==1) return nums[0]; 10 | else if(nums.size() == 2) return max(nums[0],nums[1]); 11 | 12 | vector opt1(nums.size(),0); 13 | opt[0] = nums[0]; 14 | opt[1] = max(nums[0],nums[1]); //相邻只能robbe一个 15 | for(int i=2;i> combinationSum3(int k, int n) { 7 | return solve(1,n); 8 | } 9 | 10 | vector> solve(int cur,int n,int k) 11 | { 12 | vector> result; 13 | for(int i=cur;i<=9;++i) 14 | { 15 | if(i > n) return; 16 | else if(i == n && k==1) 17 | { 18 | result.push_back(vector(1,i)); 19 | } 20 | else // i> res = solve(i+1,n-i,k-1); 23 | for(auto re:res) 24 | { 25 | re.push_back(i); 26 | result.push_back(re); 27 | } 28 | } 29 | } 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /Leetcode/Q219.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q219.cpp -------------------------------------------------------------------------------- /Leetcode/Q220.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一组整数,以及t,k.判断是否存在两个数,其差的绝对值最多为t并且 2 | //两个数的索引值之差最多为k 3 | 4 | //思路:先排序,然后锁定其中一个,另一个使用二分查找(upper_bound) 5 | 6 | 7 | class Solution { 8 | public: 9 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { 10 | if(nums.size() == 0) return false; 11 | vector> a; 12 | for(int i = 0;i&p1,const pair&p2){return p1.first < p2.first;}; 15 | for(int i=0;i= nums[j].如果不满足,则如果使用upper_bound查找,则返回的是第一个元素。 19 | auto p = std::upper_bound(a.begin()+i+1,a.end(),make_pair(a[i].first+t,0),cmp); 20 | ///if(p == a.begin()+i+1) continue; 21 | //else //如果有,则看这些里面的索引之差是否满足条件 22 | //{ 23 | for(auto it = a.begin()+i+1; it != p; ++it) 24 | { 25 | if(abs(it->second - a[i].second) <=k) return true; 26 | } 27 | //} 28 | } 29 | return false; 30 | } 31 | }; -------------------------------------------------------------------------------- /Leetcode/Q222.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int countNodes(TreeNode* root) { 13 | return solve(root,1); 14 | } 15 | 16 | int solve(TreeNode *root,int no) 17 | { 18 | int ld = depthFirst(root->left); 19 | int rd = depthFirst(root->right); 20 | if(ld == 0 && rd == 0) //说明二分查找递归到终止点了 21 | { 22 | return no; 23 | } 24 | if(ld == rd) //说明终止点在右子树上 25 | return solve(root->right,2*no+1); 26 | else if(ld > rd) //终止点在左子树上 27 | return solve(root->left,2*no); 28 | 29 | return 0; 30 | } 31 | 32 | int depthFirst(TreeNode *root) //左子树深度遍历 33 | { 34 | int i = 0; 35 | while(root!=NULL) 36 | { 37 | root = root->left; 38 | i++; 39 | } 40 | return i; 41 | } 42 | 43 | int result; 44 | }; -------------------------------------------------------------------------------- /Leetcode/Q223.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q223.cpp -------------------------------------------------------------------------------- /Leetcode/Q228.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一个没有重复数字的有序数组,把这些值的取值范围一一列出来 2 | //For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 3 | 4 | //用i,j表示range,如果遇到不连续,则重新开启新的区间,并把之前的区间加入到结果中 5 | #include 6 | #include 7 | using namespace std; 8 | class Solution { 9 | public: 10 | vector summaryRanges(vector& nums) { 11 | vectorresult; 12 | if(nums.size() == 0) return result; 13 | int i =0,j = 0; 14 | while(j"+to_string(nums[j])); 23 | j++; 24 | i=j; 25 | } 26 | } 27 | if(i == j) 28 | result.push_back(to_string(nums[i])); 29 | else 30 | result.push_back(to_string(nums[i])+"->"+to_string(nums[j])); 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /Leetcode/Q229.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定数组,查找所有出现n/3次的元素 2 | //unordered_map记录次数 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector majorityElement(vector& nums) { 11 | vectorresult; 12 | unordered_map dict; 13 | for(auto it=nums.begin();it!=nums.end();++it) 14 | { 15 | if(dict.find(*it) != dict.end()) dict[*it]=0; 16 | else dict[*it]++; 17 | 18 | if(dict[*it] > nums.size()/3) result.push_back(*it); 19 | } 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode/Q238.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q238.cpp -------------------------------------------------------------------------------- /Leetcode/Q257.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | struct TreeNode { 8 | int val; 9 | TreeNode *left; 10 | TreeNode *right; 11 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 12 | }; 13 | 14 | 15 | class Solution { 16 | public: 17 | vector binaryTreePaths(TreeNode* root) { 18 | //string s; 19 | result.clear(); 20 | solve(root,""); 21 | return result; 22 | } 23 | 24 | vector result; 25 | void solve(TreeNode *root,string s) 26 | { 27 | if(root==NULL) return; 28 | s.insert(s.size()-1,1,root->val); 29 | if(root->left==NULL && root->right == NULL) 30 | { 31 | cout<left,s); 35 | solve(root->right,s); 36 | } 37 | }; -------------------------------------------------------------------------------- /Leetcode/Q26.cpp: -------------------------------------------------------------------------------- 1 | //Easy题,给定一个sort好的数组,移除重复元素,返回新的数组的长度。 2 | //但是引用传递进来的,题目也要求删除这些元素 3 | //其实就是返回不重复元素的长度 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | class Solution { 9 | public: 10 | int removeDuplicates(vector& nums) { 11 | if(nums.size() == 0) return 0; 12 | int count = 1; 13 | auto it = nums.begin()+1; 14 | while(it!= nums.end()) 15 | { 16 | if(*it == *(it-1)) 17 | it = nums.erase(it); 18 | else 19 | { 20 | it++; 21 | count++; 22 | } 23 | } 24 | return count; 25 | } 26 | }; -------------------------------------------------------------------------------- /Leetcode/Q260.cpp: -------------------------------------------------------------------------------- 1 | //数组中有两个数只出现一次,其他出现两次。 2 | 3 | class Solution { 4 | public: 5 | vector singleNumber(vector& nums) { 6 | int AandB = 0; 7 | for(int x:nums) 8 | AandB ^= x; 9 | for(int b:nums) 10 | { 11 | int a = AandB; //3^5 12 | x = a^x; //if x== 3 x = 3^3^5 = 5; 13 | a = a^x; //a = 3^5^5 = 3; 14 | if(a^x = AandB) return {a,x}; 15 | } 16 | } 17 | }; 18 | 19 | http://www.wengweitao.com/lintcode-single-number-i-ii-iii-luo-dan-de-shu.html -------------------------------------------------------------------------------- /Leetcode/Q263.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //质因子只有2,3,5的,一个和数可以分解为质数相乘,不断用2,3,5进行分解,如果最后剩余的数不是1,说明有其他质因子 7 | 8 | class Solution { 9 | public: 10 | bool isUgly(int num) { 11 | if(num<=0) return false; 12 | while(num%2 == 0) num/=2; 13 | while(num%3 == 0) num/=3; 14 | while(num%5 == 0) num/=5; 15 | if(num == 1) return true; 16 | return false; 17 | } 18 | }; -------------------------------------------------------------------------------- /Leetcode/Q268.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q268.cpp -------------------------------------------------------------------------------- /Leetcode/Q278.cpp: -------------------------------------------------------------------------------- 1 | //二分查找 2 | // Forward declaration of isBadVersion API. 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | bool isBadVersion(int version); 8 | 9 | class Solution { 10 | public: 11 | int firstBadVersion(int n) { 12 | return find(1,n); 13 | } 14 | int find(int i,int j) 15 | { 16 | if(i == j && isBadVersion(i)) 17 | { 18 | cout << "yes" << endl; 19 | //result = i; 20 | return i; 21 | } 22 | else 23 | { 24 | int mid = i+(j-i)/2; 25 | if(isBadVersion(mid)) //如果是次品,包含该mid往左查找 26 | { 27 | cout << "find(" << i << "," << mid << ")" << endl; 28 | return find(i,mid); 29 | } 30 | else 31 | { 32 | cout << "find(" << mid+1 << "," << j << ")" << endl; 33 | return find(mid+1,j); //不包含mid往左查找 34 | } 35 | } 36 | } 37 | //int result; 38 | }; 39 | 40 | bool isBadVersion(int version) 41 | { 42 | vector pro = {1}; 43 | return pro[version-1]; 44 | } 45 | 46 | int main() 47 | { 48 | int n = 1; 49 | Solution s; 50 | cout << s.firstBadVersion(n) << endl; 51 | } -------------------------------------------------------------------------------- /Leetcode/Q282.cpp: -------------------------------------------------------------------------------- 1 | //282. Expression Add Operators 2 | //题意:给一个string包含0~9,尝试添加操作符"+,-,*"使得表达式的值等于目标target,给出所有的可能的表达式的形势 3 | 4 | class Solution { 5 | public: 6 | vector addOperators(string num, int target) { 7 | vector nums; 8 | istringstream in(num); 9 | int a; 10 | while(in >> a) nums.push_back(a); 11 | } 12 | 13 | string DandC(vector&nums,int l,int r) 14 | { 15 | 16 | } 17 | }; -------------------------------------------------------------------------------- /Leetcode/Q287.cpp: -------------------------------------------------------------------------------- 1 | //题意:在n+1个元素中查找相同的元素,元素取值范围为1-n,并且假定只有一个重复元素 2 | //根据容屉原理,说明每个元素至少都出现了一次,多出来那一次就是重复的元素 3 | 4 | //但是重复元素不止一次啊!!,比如[2,2,2,2] 5 | //可转化为求链表中环开始的位置的问题 同142 6 | 7 | //元素取值位1~n,如果不含重复元素,从1~n+1开始每个下标对应一个。 8 | //[x,1,2,3,4,5,6] 9 | //[2,1,2,3,4,5,6] 10 | //那如果出现重复元素,则在访问过程中肯定会再次访问到该元素,说明访问顺序中存在环。访问方式:元素值作为下次访问的下标 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | int findDuplicate(vector& nums) { 16 | //return accumulate(nums.begin(),nums.end(),0) - (nums.size() * (nums.size()-1))/2; 17 | //起始访问的位置下标为0 18 | int slow = nums[0]; 19 | int fast = nums[nums[0]]; 20 | while(slow != fast) 21 | { 22 | fast = nums[nums[fast]]; 23 | slow = nums[slow]; 24 | } 25 | slow = 0; 26 | while(slow != fast) 27 | { 28 | fast = nums[fast]; 29 | slow = nums[slow]; 30 | } 31 | return slow; 32 | } 33 | 34 | int main() 35 | { 36 | vector test= {1,2,3,4,2,5}; 37 | cout < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //Longest Up Subsequence 7 | //[10 9 2 5 3 7 101 18] 8 | int solve(vector &num) 9 | { 10 | int max_len = 1; 11 | vectoropt(num.size(),1); 12 | for(int i=0;i num[j]) 17 | { 18 | opt[i] = max(opt[i],opt[j]+1); 19 | } 20 | } 21 | if(max_len < opt[i]) max_len = opt[i]; 22 | } 23 | return max_len; 24 | } 25 | 26 | 27 | int solve_nlogn(vector &num) 28 | { 29 | if(num.size()==0) return 0; 30 | 31 | vectorend(num.size(),0); 32 | end[0] = num[0]; 33 | int j = 1; 34 | for(int i=1;i end[j-1]) end[j++] = num[i]; //如果比最长序列的还大,就添加新序列,并加上去. 38 | else //需要替换某个序列最后的大元素为当前较小的值 39 | { 40 | auto it = lower_bound(end.begin(),end.begin()+j-1,num[i]); 41 | *it = num[i]; 42 | } 43 | } 44 | return j; 45 | } 46 | 47 | int main() 48 | { 49 | vector test = {10,9,2,5,3,7,101,18,9,10,11}; 50 | cout << solve_nlogn(test) << endl; 51 | } 52 | -------------------------------------------------------------------------------- /Leetcode/Q309.cpp: -------------------------------------------------------------------------------- 1 | //Best Time to Buy and Sell Stock with Cooldown 2 | //类比Q122,卖完股票之后一天不能买入 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int maxProfit(vector& prices) { 10 | if(prices.size() <= 1) return 0; 11 | vector buy; 12 | vector sell; 13 | sell.push_back(0); //sell[0] = 0,sell[1] = 14 | sell.push_back(max(prices[1] - prices[0],0)); //卖出只有一种情况,day0买入,day1卖出 15 | buy.push_back(-prices[0]); 16 | buy.push_back(max(-prices[0],-prices[1])); //状态为买入,第一天买入或者第二天买入 17 | for(int i=2;i 7 | #include 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | class Solution { 14 | public: 15 | int maxProduct(vector& words) { 16 | if(words.size()==0) return 0; 17 | //因为求最长,所以尽可能让这两个单词长度大,预先从大到小排序,然后查找。 18 | //sort(words.begin(),words.end(),[](const string a,const string b){return a.size() > b.size();}); 19 | //for(string s:words) 20 | // cout << s << endl; 21 | int max = 0; 22 | for(int i=0;i(ni) << endl; 26 | for(int j=i+1;j(nj) << endl; 30 | if((ni&nj) == 0) //说明两个字符串没有相同字母.这里的与运算带括号,不然运算顺序低于== 31 | { 32 | int tmp = words[i].size() * words[j].size(); 33 | if(tmp > max) max = tmp; //可能无重复字母的符合条件有多个,选择最长的 34 | } 35 | } 36 | } 37 | return max; 38 | } 39 | 40 | int getBit(const string &s) 41 | { 42 | int n=0; 43 | for(char c:s) 44 | n = n|(1<<(c-'a')); 45 | return n; 46 | } 47 | }; -------------------------------------------------------------------------------- /Leetcode/Q321.cpp: -------------------------------------------------------------------------------- 1 | 321. Create Maximum Number 2 | //题意:给定两个数组nums1,nums2,元素取值为0~9,要求从其中选择k个数组成一个数字,使得这个数最大 3 | 4 | //思路:考虑结果数字最大,意味着最终结果来自于两个数组中较大的一些数。并且要求结果中来自各自的数组的元素的相对位置 5 | //不变。可以从前往后遍历两个数组,把靠前的较小的数字移除(移除|nums1|+|nums2|-k个)。剩下的按照从大打到的顺序组合起来即可。 6 | 7 | //为什么这么考虑。如果考虑每次选择较大的一个,那么可能nums[1]某个位置较小,而其后元素都很大,但是因为从前往后选择,导致结果过多 8 | //的选择Nums[2]中的元素。 9 | 10 | //让组合的结果尽可能大,也就意味着靠前的小的元素应该被移除。留下大的让按照相对顺序组合。 11 | 12 | 13 | 14 | class Solution { 15 | public: 16 | vector maxNumber(vector& nums1, vector& nums2, int k) { 17 | k = nums1.size() + nums2.size() - k ; //转换为删除k个较小的元素使得结果最大。 18 | auto it1 = nums1.begin(); 19 | auto it2 = nums2.begin(); 20 | while(it1!=nums.end() && it2!=nums.end()) 21 | { 22 | 23 | } 24 | } 25 | }; -------------------------------------------------------------------------------- /Leetcode/Q326.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | double x = log(n) / log(3); 11 | cout << x << endl; 12 | return x == (int)x ? true : false; 13 | } -------------------------------------------------------------------------------- /Leetcode/Q327.cpp: -------------------------------------------------------------------------------- 1 | //线段树应用:解决连续区间动态查询问题,比如查询区间[i,j]最小值问题 -------------------------------------------------------------------------------- /Leetcode/Q337.cpp: -------------------------------------------------------------------------------- 1 | //337. House Robber III 2 | //小偷来二叉树上偷了。。。 -------------------------------------------------------------------------------- /Leetcode/Q34.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int removeDuplicates(vector& nums) { 8 | vector::iterator it; 9 | for(it = nums.begin();it test; 27 | test.push_back(1); 28 | test.push_back(2); 29 | test.push_back(2); 30 | test.push_back(2); 31 | test.push_back(3); 32 | Solution s; 33 | s.removeDuplicates(test); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Leetcode/Q342.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /*class Solution { 5 | public: 6 | bool isPowerOfFour(int num) { 7 | if( (num&(num-1)) == 0 ) 8 | { 9 | cout << (num&0x55555555) << endl; 10 | if(num&0x55555555 == 0) return false; 11 | else return true; 12 | } 13 | else 14 | return false; 15 | } 16 | }; 17 | */ 18 | 19 | int main() 20 | { 21 | int num = 16; 22 | if( (num&(num-1)) == 0 ) 23 | { 24 | cout << (num&0x55555555) << endl; 25 | if((num&0x55555555) == num){cout << 1 << endl; return true;} 26 | else {cout << 0 << endl; return false;} 27 | } 28 | else 29 | { 30 | cout << 10 << endl; 31 | return false; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Leetcode/Q350.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | //可以使用c++自带的集合操作,但是对vector求集合操作要先对vector进行排序 9 | //sort 排序 10 | //set_union 并集 11 | //set_intersection 交集 12 | //set_symmetric_difference 对称差集 13 | 14 | int main() 15 | { 16 | vector nums1 = {1,2,3,4,4,5,6,7,7,7}; 17 | vector nums2 = {1,1,2,3,4,4,5,6,7,7,8,9}; 18 | 19 | //setsa; 20 | //setsb; 21 | //for(auto it = a.begin();it!=a.end();it++) sa.insert(*it); 22 | //for(auto it = b.begin();it!=b.end();it++) sb.insert(*it); 23 | //setresult; 24 | vector result; 25 | sort(nums1.begin(),nums1.end()); 26 | sort(nums2.begin(),nums2.end()); 27 | set_intersection(nums1.begin(),nums1.end(),nums2.begin(),nums2.end(),inserter(result,result.begin())); 28 | for(auto it = result.begin();it!=result.end();it++) cout << *it << endl; 29 | } -------------------------------------------------------------------------------- /Leetcode/Q357.cpp: -------------------------------------------------------------------------------- 1 | //给定数n,输出n位的数中,多少数的每个位均不相同 2 | 3 | 4 | class Solution { 5 | public: 6 | int countNumbersWithUniqueDigits(int n) { 7 | int s; 8 | if(n == 0) return 0; 9 | else if(n == 1) return 10; 10 | else 11 | { 12 | s = 10; 13 | int tmp = 9; 14 | int x = 10; 15 | for(int i=2;i<=n;i++){ 16 | tmp*=(--x); 17 | s+= tmp; 18 | } 19 | } 20 | return s; 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode/Q367.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public: 5 | bool isPerfectSquare(int num) { 6 | 7 | } 8 | }; -------------------------------------------------------------------------------- /Leetcode/Q372.cpp: -------------------------------------------------------------------------------- 1 | //Super Pow 2 | //参考快速幂的求法 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | int superPow(int a, vector& b) { 12 | int ans = 1; 13 | for(auto rit = b.rbegin();rit!=b.rend();++rit) 14 | { 15 | int tmp = powermod(a,*rit,1337); 16 | ans = (ans * tmp) % 1337; 17 | a = powermod(a,10,1227); 18 | } 19 | return ans; 20 | } 21 | 22 | int powermod(int a,int b,int c) //每次求一个进位的a 23 | { 24 | int ans = 1; 25 | a = a%c; 26 | while(b>0) 27 | { 28 | if(b%2 == 1) ans = (ans * a) % c; 29 | b = b/2; 30 | a = (a * a) % c; 31 | } 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Leetcode/Q378.cpp: -------------------------------------------------------------------------------- 1 | //n*n matrix,�����������������ҵ�k��С�� 2 | /* 3 | --------------- 4 | |1 5 9 5 | | ----------- 6 | |10 | 11 13 7 | | | ------- 8 | |12 | 13 | 15 9 | | | | 10 | */ 11 | 12 | 13 | matrix = [ 14 | [ 1, 5, 9], 15 | [10, 11, 13], 16 | [12, 13, 15] 17 | ], 18 | k = 8, 19 | 20 | return 13 21 | 22 | class Solution { 23 | public: 24 | int kthSmallest(vector>& matrix, int k) { 25 | int n = matrix.size(); 26 | int s = 2*n-1; 27 | int i = 0; 28 | while(k > s) { k-=s;s-=2;i++;} //并不是如上图所示外层都小于内层 29 | vector target; 30 | target.push_back(matrix[i][i]); 31 | int j = i+1; 32 | while(jval; 25 | p = p->next; 26 | } 27 | return res; 28 | } 29 | private: 30 | ListNode *head; 31 | }; 32 | 33 | /** 34 | * Your Solution object will be instantiated and called as such: 35 | * Solution obj = new Solution(head); 36 | * int param_1 = obj.getRandom(); 37 | */ -------------------------------------------------------------------------------- /Leetcode/Q384.cpp: -------------------------------------------------------------------------------- 1 | //Shuffle An Arrray 2 | //水塘抽样 3 | //从包含n个项目的集合S中选取k个样本,其中n为一很大或未知的数量,尤其适用于不能把所有n个项目都存放到主内存的情况 -------------------------------------------------------------------------------- /Leetcode/Q39.cpp: -------------------------------------------------------------------------------- 1 | //Combination Sum 2 | //题目意思:给定一组没有重复的数,以及一个目标的和sum,求有多少中不同的组合,其和为sum 3 | //每个候选的数可以无限次使用 4 | 5 | 6 | //有点类似于代价为1的完全背包,但是求解目标不一样,一个是求最大的可携带的,而该题是求满足和为sum的组合数。 7 | 8 | //01 背包(ZeroOnePack): 有 N 件物品和一个容量为 V 的背包。(每种物品均只有一件)第 i 件物品的费用是 c[i],价值是 w[i]。求解将哪些物品装入背包可使价值总和最大。 9 | //完全背包 (CompletePack): 有 N 种物品和一个容量为 V 的背包,每种物品都有无限件可用。第 i 种物品的费用是 c[i],价值是 w[i]。求解将哪些物品装入背包可使这些物品的费用总和不超过背包容量,且价值总和最大。 10 | //多重背包 (MultiplePack): 有 N 种物品和一个容量为 V 的背包。第 i 种物品最多有 n[i] 件可用,每件费用是 c[i],价值是 w[i]。求解将哪些物品装入背包可使这些物品的费用总和不超过背包容量,且价值总和最大。 11 | 12 | //back-tracking方法 13 | -------------------------------------------------------------------------------- /Leetcode/Q392.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q392.cpp -------------------------------------------------------------------------------- /Leetcode/Q393.cpp: -------------------------------------------------------------------------------- 1 | //判断给定的序列数是不是合理的UTF-8编码。 2 | //每个数表示一个字节编码。 3 | //比如第一个数表示该字符有3个bytes组成,那么接下来两个应该也是10。如果编码合法。继续往下判断是不是正常的。 4 | 5 | class Solution { 6 | public: 7 | bool validUtf8(vector& data) { 8 | unsigned int len = data.size(); 9 | if(len == 1 && ((data[0] & (1<<7))) != 0 ) return false; 10 | if(len >1 && len < 8) 11 | { 12 | //首先提取第一个字节data[0] 13 | //如果是3个字节表示,设置mask1 = 11100000 14 | //使用异或运算,如果匹配,那么前n+1位的异或值肯定为0,如果不匹配,则前n+1位中肯定有1.说明异或的结果大于等于 1 << (8-n); 15 | //后续位则随意设置不考虑。 16 | 17 | //同理对后续的字节,首位都是10. 所以设置掩码为1000 0000, 异或结果如果大于等于 1 << 6,则不是合法的uft8编码 18 | unsigned int mask1 = ((1 << len)-1) << (8-len); //Example. 1110 0000 19 | unsigned int mask2 = (1 << 7); 20 | 21 | if((data[0] ^ mask1) >= (1 << 6)) return false; 22 | for(int i=1;i= (1 << 6)) return false; 25 | } 26 | } 27 | 28 | return true; 29 | } 30 | }; -------------------------------------------------------------------------------- /Leetcode/Q394.cpp: -------------------------------------------------------------------------------- 1 | //Decode String 2 | //给定一组类似于字符串描述,然后进行解码 3 | //s = "3[a]2[bc]", return "aaabcbc". 4 | //s = "3[a2[c]]", return "accaccacc". 5 | //s = "2[abc]3[cd]ef", return "abcabccdcdcdef". 6 | 7 | //使用栈来解析规则 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | 14 | class Solution { 15 | public: 16 | string decodeString(string s) { 17 | stack nums; 18 | stack oper; 19 | int x = 0; 20 | string result; 21 | for(char c:s) 22 | { 23 | if(c >= '0' && c<='9') 24 | x = x*10+c-'0'; 25 | else 26 | { 27 | string tmp; 28 | if(c == '[') 29 | { 30 | nums.push(x); 31 | x = 0; 32 | oper.push(c); 33 | } 34 | else if(c>='a' && c<='z') 35 | { 36 | tmp.append(1,c); 37 | } 38 | else 39 | { 40 | int n = nums.top(); nums.pop(); 41 | for(int i=0;i10->1 5 | //(-1) 11->100->10->1 6 | 7 | //111 8 | // 9 | 10 | //如果最后两位是11的话,最好的操作是+1. 11 | //除此之外-1都是最佳的操作。 12 | 13 | //觉得这道题本质还是DP。n的规模不断缩小,其最优值肯定包含更小规模的最优值。 14 | //分为如下情况: 15 | //n为偶数: opt(n) = 1+opt(n+1) 16 | //n为奇数: opt(n) = 2+min{ opt((n+1)/2), opt((n-1)/2)} 17 | //为什么是2+min呢?首先如果是奇数,不管+1还是-1都会变为偶数,而偶数的操作是固定的。 18 | //比如opt(5) = min{opt(6),opt(4)} = min{1+opt(3),1+opt(2)} = 1+min{opt(3),opt(2)} 19 | //如果以打表的方式,opt(5)的最有子问题没有opt(6),但是opt(6)最优和opt(3)是等价的。 20 | 21 | //opt一般使用打表来记录子问题的解,带来的空间代价比较高。 22 | 23 | #include 24 | #include 25 | #include 26 | using namespace std; 27 | 28 | class Solution { 29 | public: 30 | int integerReplacement(int n) { 31 | if(n == 1) return 0; 32 | if(opt.count(n) == 0) //如果没有计算过 33 | { 34 | if(n & 1) //如果n是奇数 35 | { 36 | //opt[n] = 2+min(integerReplacement((n-1)/2), integerReplacement((n+1)/2)); //但是这里出现了n+1.考虑边界情况.n+1可能超出整数范围 37 | opt[n] = 2+min(integerReplacement(n/2),integerReplacement(n/2+1)); 38 | } 39 | else 40 | opt[n] = 1+integerReplacement(n/2); 41 | } 42 | return opt[n]; 43 | } 44 | private: 45 | unordered_map opt; 46 | }; -------------------------------------------------------------------------------- /Leetcode/Q398.cpp: -------------------------------------------------------------------------------- 1 | //398. Random Pick Index 2 | //题意:给一堆数(可能有重复),给定目标数target,每次随机输出等于target的索引,对与同一个数每次输出的概率相同 3 | //数据非常大,耗费空间会超过空间限制 4 | 5 | //把符合target的作为一个数据流不断输入,使用水塘采样 6 | 7 | class Solution 8 | { 9 | public: 10 | Solution(vector nums):nums(nums) 11 | { 12 | } 13 | 14 | int pick(int target) 15 | { 16 | int count = 0; 17 | int res = -1; 18 | for(int i=0;i nums; 28 | }; 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | /** 53 | * Your Solution object will be instantiated and called as such: 54 | * Solution obj = new Solution(nums); 55 | * int param_1 = obj.pick(target); 56 | */ 57 | 58 | class Solution { 59 | public: 60 | Solution(vector nums): v(nums) {} 61 | 62 | int pick(int target) { 63 | int cnt = 0, res = -1; 64 | for (int i = 0; i < v.size(); ++i) { 65 | if (v[i] != target) continue; 66 | ++cnt; 67 | if (rand() % cnt == 0) res = i; 68 | } 69 | return res; 70 | } 71 | private: 72 | vector v; 73 | }; -------------------------------------------------------------------------------- /Leetcode/Q4.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q4.cpp -------------------------------------------------------------------------------- /Leetcode/Q400.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int findNthDigit(int n) { 7 | int i=1; 8 | unsigned int s = 9; 9 | while(n>s*i) //(s-1)*i表示没一段的位数 10 | { 11 | n = n-s*i; 12 | cout<<"step:"< x) 16 | { 17 | result.pop_back(); 18 | k--; 19 | } 20 | result+=x; 21 | } 22 | while(k--) result.pop_back(); //如果后面没有更小的再来替换前面的,则说明后面的字母是递增的,从后往前删出直到k为0. 23 | int i = 0; 24 | while(i < result.size() && result[i] == '0') i++; //移除前导0 25 | return result.substr(i).size() > 0 ? result.substr(i) : "0" ; 26 | //return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /Leetcode/Q405.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | int a= 1; 10 | int x = ~a+1; 11 | cout<<(unsigned int)x< 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int longestPalindrome(string s) { 9 | int num[128]={0}; 10 | int result = 0; 11 | for(int i=0;i& nums) { 12 | int i = 0; 13 | int n = nums.size(); 14 | while(i < n) 15 | { 16 | while(nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i]-1]) //第一个元素存1 17 | swap(nums[i],nums[nums[i]-1]); 18 | i++; 19 | } 20 | for(i = 0;i 5 | class Solution { 6 | public: 7 | int numberOfArithmeticSlices(vector& A) { 8 | if(A.size() < 3) return 0; 9 | else 10 | { 11 | int len = 2; 12 | int diff = A[0]-A[1]; 13 | int sum = 0; 14 | for(int i=1;i= 3 ) sum+=((len-2)*(len-1)/2); 22 | len = 2; 23 | } 24 | } 25 | cout <= 3 ) sum+=((len-2)*(len-1)/2); 27 | return sum; 28 | } 29 | } 30 | }; -------------------------------------------------------------------------------- /Leetcode/Q414.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q414.cpp -------------------------------------------------------------------------------- /Leetcode/Q415.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string num1 = "1111"; 9 | string num2 = "99099"; 10 | const int len = num1.size()>num2.size() ? num1.size()+1:num2.size()+1; 11 | string result(len,'0'); 12 | cout << result << endl; 13 | int i = num1.size()-1; 14 | int j = num2.size()-1; 15 | int k = 0; 16 | while(i>=0 && j>=0) 17 | { 18 | int s = (num1[i--]-'0')+(num2[j--]-'0')+(result[k]-'0'); 19 | int m = s%10; 20 | int qu = s/10; 21 | cout << "余数" << m << " 进位" << qu << endl; 22 | result[k++] = m+'0'; 23 | result[k] = qu+'0'; 24 | } 25 | while(i>=0) 26 | { 27 | int s = (num1[i--]-'0')+(result[k]-'0'); 28 | int m = s%10; 29 | int qu = s/10; 30 | result[k++] = m+'0'; 31 | result[k] = qu+'0'; //进位; 32 | } 33 | while(j>=0) 34 | { 35 | int s = (num2[j--]-'0')+(result[k]-'0'); 36 | int m = s%10; 37 | int qu = s/10; 38 | result[k++] = m+'0'; 39 | result[k] = qu+'0'; //进位; 40 | } 41 | if(result[k--] == '0') result.erase(result.end()-1); 42 | reverse(result.begin(),result.end()); 43 | cout << result << endl; 44 | } -------------------------------------------------------------------------------- /Leetcode/Q419.cpp: -------------------------------------------------------------------------------- 1 | //battleships 2 | ......... 3 | .xxx...x. 4 | ......... 5 | ...x.xxx. 6 | .x.x..... 7 | .x.x...x. 8 | ......... 9 | ["XXX...X",".......","..X.XXX","X.X....","X.X...X"] 10 | ["XXX...","...XXX"] 11 | ["X..X","...X","...X"] 12 | //从左往右,从上往下遍历,左,上,下必须都是'.',的个数 13 | 14 | class Solution { 15 | public: 16 | int countBattleships(vector>& board) { 17 | int x = board.size(); 18 | int y = board[0].size(); 19 | int sum=0; 20 | for(int i=0;i=x) d = '.'; else d = board[i+1][j]; 26 | if(j-1<0) l = '.'; else l = board[i][j-1]; 27 | b = board[i][j]; 28 | if(b=='X' && u=='.'&& d=='.' && l=='.') sum++; 29 | } 30 | return sum; 31 | } 32 | }; -------------------------------------------------------------------------------- /Leetcode/Q423.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string originalDigits(string s) { 4 | map dict; 5 | vector re(10,0); //0~9的个数 6 | string search = "zwxghsrvin"; // 依次判别{0,2,6,8},{3,7},{4,5},{9},{1} 7 | vector number = {0,2,6,8,3,7,4,5,9,1}; 8 | 9 | //关键字母对应的数字 10 | map dictn = {{'z',0},{'w',2},{'x',6},{'g',8},{'h',3}, 11 | {'s',7},{'r',4},{'v',5},{'i',0},{'n',1}}; 12 | map dicts = {{'z',"zero"},{'w',"two"},{'x',"six"},{'g',"eight"},{'h',"three"}, 13 | {'s',"seven"},{'r',"four"},{'v',"five"},{'i',"nine"},{'n',"one"}}; 14 | 15 | 16 | 17 | for(char c:s) dict[c]++; //统计 18 | 19 | 20 | for(char sc:search) 21 | { 22 | if(dict.find(sc) != dict.end()) 23 | { 24 | for(char c:dicts[sc]) 25 | dict[c] -= dict[sc]; 26 | re[dictn[sc]] = dict[sc]; 27 | } 28 | } 29 | 30 | string result; 31 | for(int i=0;i result(num1.size()+num2.size(),0); //先用整型存储,避免多次转换成字符。 10 | reverse(num1.begin(),num1.end()); 11 | reverse(num2.begin(),num2.end()); 12 | for(int i=0;i 10) 24 | { 25 | result[tmpK+1]+=(result[tmpK])/10; 26 | result[tmpK] = result[tmpK]%10; 27 | tmpK++; 28 | } 29 | k++; 30 | } 31 | } 32 | 33 | while(result.size() > 1 && result.back() == 0) result.erase(result.end()-1); 34 | string re; 35 | for(auto rit = result.rbegin();rit!=result.rend();++rit) 36 | re.append(1,(*rit)+'0'); 37 | 38 | return re; 39 | } 40 | }; -------------------------------------------------------------------------------- /Leetcode/Q435.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一组区间,求移除最少的区间使得剩下的区间没有重叠 2 | //思路:可以转换为如何让更多的区间没有重叠。参考卜东波老师贪心章节上课区间安排的雷子。 3 | //Greedy,每次贪心选择结束区间(下课最早的),假设有最优解选择的不是结束最早的,那么把第一个改为下课最早的依然不改变最优解。 4 | //所以每次选择结束最早的区间 5 | 6 | /** 7 | * Definition for an interval. 8 | * struct Interval { 9 | * int start; 10 | * int end; 11 | * Interval() : start(0), end(0) {} 12 | * Interval(int s, int e) : start(s), end(e) {} 13 | * }; 14 | */ 15 | 16 | class Solution { 17 | public: 18 | int eraseOverlapIntervals(vector& intervals) { 19 | if(intervals.size() == 0) return 0; 20 | auto cmp = [](const Interval& iv1,const Interval&iv2){return iv1.end < iv2.end;}; 21 | sort(intervals.begin(),intervals.end(),cmp); 22 | int count = 1; 23 | int cur = 0; 24 | for(int i=1;i= intervals[cur].end) //没有重叠 27 | { 28 | count++; cur = i; 29 | } 30 | } 31 | return intervals.size()-count; 32 | } 33 | }; -------------------------------------------------------------------------------- /Leetcode/Q437.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q437.cpp -------------------------------------------------------------------------------- /Leetcode/Q441.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | class Solution { 8 | public: 9 | int arrangeCoins(int n) { 10 | int nx = (int)sqrt(n); 11 | while(true) 12 | { 13 | if(nx/2 == n/(nx+1)) return nx; 14 | else if(nx/2 < n/(nx+1)) nx++; 15 | else return nx-1; 16 | 17 | /* 18 | if(nx*(nx+1)/2 == n/(nx)) return nx; 19 | else if(nx*(nx+1)/2 < n ) 20 | { 21 | nx++; 22 | } 23 | else 24 | { 25 | if(nx*(nx+1)/2-n < nx) 26 | return nx-1; 27 | } 28 | */ 29 | } 30 | } 31 | }; -------------------------------------------------------------------------------- /Leetcode/Q442.cpp: -------------------------------------------------------------------------------- 1 | //和Q448很像,给n个数,取值在1~n,然后找重复出现的数 2 | //依然是占坑,占过了说明重复。 3 | //如果用hash,会浪费空间 4 | 5 | class Solution { 6 | public: 7 | vector findDuplicates(vector& a) { 8 | vector result; 9 | for(int i=0;i 0) 13 | { 14 | a[m] = -a[m]; 15 | } 16 | else 17 | { 18 | result.push_back(m+1); 19 | } 20 | } 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /Leetcode/Q445.cpp: -------------------------------------------------------------------------------- 1 | //给定两个链表,每个节点表示一个位 2 | //7->2->4->3 3 | //5->6->4 4 | 5 | //思路1:先按对应的位相加,存到结果中。然后在结果中把溢出的节点进位处理 6 | 7 | 8 | struct ListNode { 9 | int val; 10 | ListNode *next; 11 | ListNode(int x) : val(x), next(NULL) {} 12 | }; 13 | 14 | class Solution { 15 | public: 16 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 17 | //定位的方法:确定两个链表的长度,如果较长的那个先加到结果中 18 | int n1 = 0,n2=0,carry = 0; 19 | 20 | ListNode *cur1 = l1,*cur2 = l2; 21 | while(cur1) {n1++;cur1 = cur1->next;} 22 | while(cur2) {n2++;cur2 = cur2->next;} 23 | ListNode* res = NULL; 24 | while(n1 >0 && n2>0) 25 | { 26 | int sum = 0; 27 | if( n1 >= n2 ){ sum += curr1->val; curr1=curr1->next; n1--;} 28 | if( n2 > n1 ){ sum += curr2->val; curr2=curr2->next; n2--;} 29 | } 30 | } 31 | }; 32 | 33 | //思路2:栈/递归(天然栈) -------------------------------------------------------------------------------- /Leetcode/Q447.cpp: -------------------------------------------------------------------------------- 1 | //Number of Boomerangs 2 | //multimap 分别以x,y为主键,按y轴分层,找x,看是否构成。对x同样处理。 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int numberOfBoomerangs(vector>& points) { 10 | multimap X; //以X坐标分层 11 | multimap Y; //以Y坐标分层 12 | 13 | for(auto p : points) 14 | { 15 | X.insert(p); 16 | Y.insert(make_pair(p.second,p.first)); 17 | } 18 | 19 | //以Y为层进行统计 20 | 21 | } 22 | 23 | 24 | int main() 25 | { 26 | } 27 | -------------------------------------------------------------------------------- /Leetcode/Q448.cpp: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD 2 | //题目意思:给定一组数0~n,其中有的数出现两次,有的出现一次,问0~n中哪些数缺失 3 | //思路:物归原主,各自占坑。 4 | //每次判断该数和所在位置匹配,继续往下走 5 | //否则,取出该数,将该位置标记为-1,不断调换使得与所在位置相同. 6 | 7 | 8 | //或者用本身所在的值的正负来标记该位置是否被占用. 9 | 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int main() 15 | { 16 | vector a = {4,3,2,7,8,2,3,1}; 17 | vector result; 18 | for(int i=0;i 0 ? -a[m]:a[m]; //小于0表示位置被占 22 | } 23 | 24 | for(int i=0;i& nums) { 9 | sort(nums.begin(),nums.end()); 10 | int min = *(nums.begin()); 11 | int sum = 0; 12 | for(auto it = nums.begin()+1;it!=nums.end();++it) 13 | sum+=((*it)-min); 14 | return sum; 15 | } 16 | }; -------------------------------------------------------------------------------- /Leetcode/Q455.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q455.cpp -------------------------------------------------------------------------------- /Leetcode/Q456.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q456.cpp -------------------------------------------------------------------------------- /Leetcode/Q459.cpp: -------------------------------------------------------------------------------- 1 | //判断一个字符串是否可以通过一个重复的pattern构造 2 | //ababab 3 | class Solution { 4 | public: 5 | bool repeatedSubstringPattern(string str) { 6 | int n = str.size(); 7 | int x = n; 8 | while(x>1) 9 | { 10 | if(n%x==0) //先判断能不能分段 11 | { 12 | int len = n/x; 13 | for(int i=0;i> permute(vector& nums) { 8 | if(nums.size() == 0) return {{}}; 9 | sort(nums.begin(),nums.end()); 10 | vector res; 11 | per(nums,res); 12 | return result; 13 | } 14 | 15 | void per(vector&nums,vector&res) 16 | { 17 | if(nums.size() == 1) 18 | { 19 | res.push_back(nums[0]); 20 | result.push_back(res); 21 | } 22 | else 23 | { 24 | for(int i = 0;inext(nums); 27 | vectornextres(res); 28 | nextres.push_back(nums[i]); 29 | next.erase(next.begin()+i); 30 | per(next,nextres); 31 | } 32 | } 33 | } 34 | private: 35 | vector> result; 36 | }; -------------------------------------------------------------------------------- /Leetcode/Q462.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q462.cpp -------------------------------------------------------------------------------- /Leetcode/Q464.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q464.cpp -------------------------------------------------------------------------------- /Leetcode/Q47.cpp: -------------------------------------------------------------------------------- 1 | //题意:同46,求全排列,但是该组数据中存在相同的数 2 | //在46基础上改,应该是加入前导时判断是不是该前导已经加入过(即相邻的有相同的,则只取一个), 3 | //而不是把相同的列为一组来持续加入前导,这样11总是挨着,但112可能出现121. 4 | 5 | 6 | 7 | class Solution { 8 | public: 9 | vector> permuteUnique(vector& nums) { 10 | if(nums.size() == 0) return {{}}; 11 | sort(nums.begin(),nums.end()); 12 | vector res; 13 | per(nums,res); 14 | return result; 15 | } 16 | 17 | void per(vector&nums,vector&res) 18 | { 19 | if(nums.size() == 1) 20 | { 21 | res.push_back(nums[0]); 22 | result.push_back(res); 23 | } 24 | else 25 | { 26 | for(int i = 0;i0 && nums[i] == nums[i-1]) continue; //如果相邻的相同,那么以哪个作为前导都是同样的结果,所以相同的话不再作为前导。 29 | vectornext(nums); 30 | vectornextres(res); 31 | nextres.push_back(nums[i]); 32 | next.erase(next.begin()+i); 33 | per(next,nextres); 34 | } 35 | } 36 | } 37 | private: 38 | vector> result; 39 | }; -------------------------------------------------------------------------------- /Leetcode/Q476.cpp: -------------------------------------------------------------------------------- 1 | //给定一个正整数,要求输出这个数的补数(位取反,但是不考虑前导0) 2 | //比如5的二进制表示为 0000 0000 0000 0010。但是不考虑其前导0的情况下的补数,所以只考虑010的flip位101.其他位不变。 3 | 4 | 5 | class Solution { 6 | public: 7 | int findComplement(int num) { 8 | //处理前导0,应该找到一个mask,与前导0对应的位都是0,其余都是1. 通过&运算,前导位依然是0,其后的位保持不变。 9 | unsigned mask = ~0; 10 | while(num & mask) mask <<= 1; //不断右移,定位到前导0位置。 如maks = 1111 1110 0000 11 | return (~num) & (~mask); 12 | } 13 | }; -------------------------------------------------------------------------------- /Leetcode/Q48.cpp: -------------------------------------------------------------------------------- 1 | //题目意思:顺时针旋转一个图像 2 | //思路:先按照左上-右下对角线对称变换,然后水平方向对称变换 3 | 4 | class Solution { 5 | public: 6 | void rotate(vector>& matrix) { 7 | int n = matrix.size(); 8 | //对角线翻折 9 | for(int i=0;i 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int findMaxConsecutiveOnes(vector& nums) { 10 | 11 | int num = 0,max=0; 12 | for(int i=1;i max) max = num; 17 | num = 0; 18 | } 19 | } 20 | return max; 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode/Q486.cpp: -------------------------------------------------------------------------------- 1 | //比赛游戏,每个选手每次只能选择序列的首/尾元素,A[i,j]的第i个或第j个,Player1先选择,问Player1会不会赢。(以Player1取得最大的利益为目标) 2 | //思路: DP/Maxmin 3 | 4 | //dp(i,j) 表示序列A[i]~A[j],先手能够获得的最大的分数(两个玩家的分数之差),Player1作为先手可以选择A[i]或者A[j] 5 | //则留下的序列为A[i+1]~A[j] 或者 A[i]~A[j-1],对于留下来的序列,Player2为后手。为了让Player尽可能多得分,所以对于Player2应该尽可能小。 6 | //先手的用正数表示,后手的用负数表示。最小化Player2的分数等价于 最大化负的数。 7 | 8 | //所以:dp(i,j) = max(-dp(i+1,j)+ nums[i], -dp(i,j-1) + nums[j] ) 9 | 10 | 11 | class Solution { 12 | public: 13 | bool PredictTheWinner(vector& nums) { 14 | int n = nums.size(); 15 | return dp(nums,0,n-1) >= 0; 16 | } 17 | int dp(vector&nums,int i,int j) 18 | { 19 | if(i == j) return nums[i]; 20 | else return max(nums[i] - dp(nums,i+1,j), nums[j] - dp(nums,i,j-1)); 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode/Q49.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定字符串数组,把可以“通过变换位置”互相转换的字符串归为一组 2 | //["eat", "tea", "tan", "ate", "nat", "bat"], 3 | //eat,tea,ate为一组, nat,tan为一组,bat为一组 4 | 5 | //思路:HashTable,key为统一的元素,value为字符串集合。通过对每个元素进行排序找到原始序列。 6 | //14.04 7 | class Solution { 8 | public: 9 | vector> groupAnagrams(vector& strs) { 10 | map> dict; 11 | for(auto s: strs) 12 | { 13 | string tmp =s; 14 | sort(tmp.begin(),tmp.end()); 15 | if(dict.find(tmp) == dict.end()) //如果没有 16 | dict[tmp] = vector(1,s); 17 | else 18 | dict[tmp].push_back(s); //如果有则继续加入 19 | } 20 | vector> result; 21 | for(auto d:dict) 22 | result.push_back(d.second); 23 | return result; 24 | } 25 | }; -------------------------------------------------------------------------------- /Leetcode/Q495.cpp: -------------------------------------------------------------------------------- 1 | //题目描述: 2 | //给定一个下毒时间t,每次下毒会持续k秒,输入为一组下毒的时间,输出总的中毒的时间 3 | //下毒时间为增序 4 | //O(n) 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int findPoisonedDuration(vector& timeSeries, int duration) { 12 | int etime = 0; //表示每次结束中毒的时间 13 | int totaltime = 0; 14 | for(auto it = timeSeries.begin();it!=timeSeries.end();++it) 15 | { 16 | if(*it >= etime) 17 | { 18 | totaltime += duration; 19 | etime = *it + duration; 20 | } 21 | else 22 | { 23 | totaltime += (*it + duration - etime); 24 | etime = *it + duration; 25 | } 26 | cout << totaltime << endl; 27 | } 28 | return totaltime; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | vector test = {1,2,3,4,5,8}; 35 | int n = 3; 36 | Solution s; 37 | s.findPoisonedDuration(test,n); 38 | } -------------------------------------------------------------------------------- /Leetcode/Q50: -------------------------------------------------------------------------------- 1 | //快速求A^n,A可以是数,也可以是矩阵。 2 | //不是对A开方! 3 | //注意n可正可负 4 | 5 | 6 | double Pow(double a,int n) 7 | { 8 | if(n < 0) n = -n; 9 | int result = 1; 10 | while(n > 0) 11 | { 12 | if(n & 1 == 1) //奇数 13 | result *= a; 14 | a*=a; 15 | n >>= 1; 16 | } 17 | return result; 18 | } 19 | 20 | 21 | // 22 | 2.00000 23 | -2147483648 24 | 25 | //每次使用n= - n就要注意当n为负数最小的时候,-n表示的并不是最大。 26 | //2147483648用long能表示 27 | 28 | 29 | //矩阵快速幂乘计算Fabonacci序列 30 | // 31 | 1,1,2,3,5 32 | 用a,b表示不断递推的两个数 33 | 34 | 初始化a=1,b=1; 35 | b = a+b; 36 | a = b; 37 | 38 | [b,a]^T = [a+b,b]^T 39 | 40 | //可以推广到各种线性递推式上。 -------------------------------------------------------------------------------- /Leetcode/Q50.cpp: -------------------------------------------------------------------------------- 1 | //快速求A^n,A可以是数,也可以是矩阵。 2 | //不是对A开方! 3 | //注意n可正可负 4 | 5 | 6 | double Pow(double a,int n) 7 | { 8 | if(n < 0) n = -n; 9 | int result = 1; 10 | while(n > 0) 11 | { 12 | if(n & 1 == 1) //奇数 13 | result *= a; 14 | a*=a; 15 | n >>= 1; 16 | } 17 | return result; 18 | } 19 | 20 | 21 | // 22 | 2.00000 23 | -2147483648 24 | 25 | //每次使用n= - n就要注意当n为负数最小的时候,-n表示的并不是最大。 26 | //2147483648用long能表示 27 | 28 | 29 | //矩阵快速幂乘计算Fabonacci序列 30 | // 31 | 1,1,2,3,5 32 | 用a,b表示不断递推的两个数 33 | 34 | 初始化a=1,b=1; 35 | b = a+b; 36 | a = b; 37 | 38 | [b,a]^T = [a+b,b]^T 39 | 40 | //可以推广到各种线性递推式上。 -------------------------------------------------------------------------------- /Leetcode/Q500.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | vector findWords(vector& words) { 5 | char line[][] = {"QWERTYUIOPqwertyuiop","ASDFGHJKLasdfghjkl","ZXCVBNMzxcvbnm"}; 6 | map dict; 7 | for(int i=0;i<2;i++) 8 | for(int j=0;j!='\0';++j) 9 | { 10 | dict[line[i][j]]=i; 11 | } 12 | 13 | vector result; 14 | for(auto it=words.begin();it!=words.end();++it) 15 | { 16 | for(int k=1;k& nums, int k) { 21 | map mmap; 22 | mmap[0] = -1; 23 | int sum = 0; 24 | for(int i=0;i::iterator it = mmap.find(sum); 29 | if(it != mmap.end()) //如果之前出现过,说明两个之间的数的和肯定是k的倍数 30 | { 31 | if(i - it->second > 1) //说明序列长度至少为2 32 | return true; 33 | } 34 | else 35 | mmap[sum] = i; 36 | } 37 | return false; 38 | } 39 | }; -------------------------------------------------------------------------------- /Leetcode/Q53.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q53.cpp -------------------------------------------------------------------------------- /Leetcode/Q532.cpp: -------------------------------------------------------------------------------- 1 | //使用首尾指针 2 | //属于two-sum的变形 3 | //Array ,属于two-Pointers 4 | 5 | 6 | class Solution { 7 | public: 8 | int findPairs(vector& nums, int k) { 9 | sort(nums.begin(),nums.end()); 10 | size_t n = nums.size(); 11 | int s=0,t=1,res=0; 12 | while(s < t && t < n) 13 | { 14 | if(nums[t] - nums[s] < k) t++; //如果差值小于k,后移尾指针 15 | else 16 | { 17 | if(nums[t] - nums[s] == k) 18 | { 19 | if(s == 0 || nums[s] != nums[s-1]) res++; //确保相同的只计算一次 20 | } 21 | s++; 22 | if(s == e) e++; 23 | } 24 | } 25 | return res; 26 | } 27 | }; -------------------------------------------------------------------------------- /Leetcode/Q538.cpp: -------------------------------------------------------------------------------- 1 | //538. Convert BST to Greater Tree 2 | //把BST中的每个元素key,变为该key以及大于该key的所有元素的和 3 | 4 | //观察:比当前元素大的都有哪些?(1)父节点以及父节点右子树所有元素 5 | (2)当前节点的所有的右子树 6 | 7 | //思路:1.BST的中序遍历是有序的,则要改变的每个元素为该元素之后的所有元素之和。 8 | // 2.递归的思路可以从最右侧的元素开始,则前一个元素要变成的值直接相当于该元素加后一个改变后的元素的值 9 | // 3.(改变2的思路)中序遍历,先访问右子树,然后访问root,然后左子书。一个从大到小的顺序,则要改变的值可以顺延下去。 10 | 11 | //cur = cur->parent + cur->right -------------------------------------------------------------------------------- /Leetcode/Q54.cpp: -------------------------------------------------------------------------------- 1 | //54. Spiral Matrix 2 | //题意:给定一个矩阵m*n,按照螺旋的方式输出矩阵的元素 3 | //input 4 | [ 5 | [ 1, 2, 3 ], 6 | [ 4, 5, 6 ], 7 | [ 7, 8, 9 ] 8 | ] 9 | //output 10 | [1,2,3,6,9,8,7,4,5]. 11 | 12 | //思路:螺旋四个走向 13 | //设置四个边界,l,r,u,b分别表示当前方向可以走到的边界. 14 | //初始化:l = 0, r = n-1, u = 0, b = m-1 15 | //初始化位置 i = u,j = l 16 | //分如下四中情况: 17 | //(1) l=l: j-- ,否则b--,且(4) 20 | //(4) u=u: i-- ,否则l++,且(1) 21 | 22 | class Solution { 23 | public: 24 | vector spiralOrder(vector>& matrix) { 25 | int m = matrix.size(); 26 | if(m == 0) return {}; 27 | int n = matrix[0].size(); 28 | int l = 0, r = n-1 ,u = 0, b = m-1; 29 | vector result; 30 | while(l<=r && u<=b) 31 | { 32 | if(u <=b ) //这里是保证这个方向存在(如果宽度或者长度都为0了,该方向没意义f) 33 | { 34 | for(int j=l;j<=r;++j) result.push_back(matrix[u][j]); u++; 35 | } 36 | if(l <= r) 37 | { 38 | for(int i=u;i<=b;++i) result.push_back(matrix[i][r]); r--; 39 | } 40 | if(u <= b) 41 | { 42 | for(int j=r;j>=l;--j) result.push_back(matrix[b][j]); b--; 43 | } 44 | if(l <= r) 45 | { 46 | for(int i=b;i>=u;--i) result.push_back(matrix[i][l]); l++; 47 | } 48 | 49 | } 50 | return result; 51 | 52 | } 53 | }; -------------------------------------------------------------------------------- /Leetcode/Q541.cpp: -------------------------------------------------------------------------------- 1 | //给定一个字符串,每2k个字符,翻转前k个 2 | //如果剩下的不足k个,全部翻转,如果不足2k个但是大于等于k隔 3 | //翻转前k个 4 | 5 | //Input: s = "abcdefg", k = 2 6 | //Output: "bacdfeg" 7 | 8 | class Solution { 9 | public: 10 | string reverseStr(string s, int k) { 11 | int i = 0; 12 | for(i = 0;i& nums) { 8 | return canJump(nums,0); 9 | } 10 | bool canJump(vector&nums,int i) //i表示当前位置 11 | { 12 | if(i == nums.size()-1) return true; 13 | bool result = false; 14 | for(int k = 1;k<=nums[i];++k){ 15 | if(i+k < nums.size()) 16 | { 17 | result |= canJump(nums,i+k); 18 | if(result) break; 19 | } 20 | } 21 | return result; 22 | } 23 | }; 24 | 25 | 26 | //如果序列里没有0,一步步走肯定都能到。 27 | //所以这道题关键是0的处理,如果可以跳过0的位置,就可以规约到更小的问题上。 28 | //遍历,把每个位置最远可以到达的位置标记起来。max标记当前可以达到的最远的位置 29 | 30 | class Solution { 31 | public: 32 | bool canJump(vector& nums) { 33 | if(nums.size() <= 1) return true; 34 | int maxpos = 0; 35 | for(int i=0;i 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | struct Interval { 10 | int start; 11 | int end; 12 | Interval() : start(0), end(0) {} 13 | Interval(int s, int e) : start(s), end(e) {} 14 | }; 15 | 16 | static bool compare(const Interval&ia,const Interval& ib) 17 | { 18 | return ia.start < ib.start; 19 | } 20 | 21 | class Solution { 22 | public: 23 | vector merge(vector& intervals) { 24 | if(intervals.size() < 1) return intervals; 25 | vector result; 26 | sort(intervals.begin(),intervals.end(),compare); 27 | Interval in = intervals.front(); 28 | for(auto it = intervals.begin()+1;it!=intervals.end();++it) 29 | { 30 | if((*it).start <= in.end && (*it).end > in.end) 31 | { 32 | in.end = (*it).end; 33 | } 34 | else if((*it).start > in.end) 35 | { 36 | result.push_back(in); 37 | in.start = (*it).start; 38 | in.end = (*it).end; 39 | } 40 | } 41 | return result; 42 | 43 | } 44 | }; 45 | 46 | int main() 47 | { 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Leetcode/Q560.cpp: -------------------------------------------------------------------------------- 1 | //计算连续子数组和,是否等于目标 2 | 3 | class Solution { 4 | public: 5 | int subarraySum(vector& nums, int k) { 6 | int m = nums.size(); 7 | if(m == 0) return 0; 8 | int result = 0 ; 9 | vector presum; 10 | presum.push_back(0); 11 | for(int i = 0;i& a, int k) { 27 | map mp; 28 | mp[0]++; 29 | int s = 0, ans = 0; 30 | for (int i : a) { 31 | s += i; 32 | ans += mp[s - k]; 33 | mp[s]++; 34 | } 35 | return ans; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Leetcode/Q561.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一个数组大小为2n,把这些书两两分组,使得这n组数中每个最小值之和最大。 2 | //思路:为了让最小值之和尽可能大,直观的想法是尽可能让小的和小的在一起,这样不会拖其他大的后腿。。 3 | //sort后,取奇数位为最小。 4 | //AC -------------------------------------------------------------------------------- /Leetcode/Q563.cpp: -------------------------------------------------------------------------------- 1 | //给定二叉树,求其Tilt,Tile表示两个子数sum之差的绝对值,求这棵树所有节点的Tilt之和 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int findTilt(TreeNode* root) { 15 | int result = 0; 16 | } 17 | 18 | int sovle(TreeNode* root,int &result) 19 | { 20 | int left = 0,right = 0; 21 | if(root->left != NULL) left = solve(root->left,result); 22 | if(root->right!= NULL) right = solve(root->right,result); 23 | result += abs(left - right) 24 | return root->val+left+right; //返回的是子树的和 25 | } 26 | }; -------------------------------------------------------------------------------- /Leetcode/Q57.cpp: -------------------------------------------------------------------------------- 1 | //题目意思:给定一组没有重叠的区间,然后给定一个区间,要求插入到该区间内,合并形成一组新的区间 2 | 3 | //题目描述: 4 | //合并区间[1,3],[2,6],[8,10],[15,18] 合并为 [1,6] [8,10],[15,18] 5 | 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | struct Interval { 12 | int start; 13 | int end; 14 | Interval() : start(0), end(0) {} 15 | Interval(int s, int e) : start(s), end(e) {} 16 | }; 17 | 18 | static bool compare(const Interval&ia,const Interval& ib) 19 | { 20 | return ia.start < ib.start; 21 | } 22 | 23 | class Solution { 24 | public: 25 | vector merge(vector& intervals) { 26 | if(intervals.size() < 1) return intervals; 27 | vector result; 28 | sort(intervals.begin(),intervals.end(),compare); 29 | Interval in = intervals.front(); 30 | for(auto it = intervals.begin()+1;it!=intervals.end();++it) 31 | { 32 | if((*it).start <= in.end && (*it).end > in.end) 33 | { 34 | in.end = (*it).end; 35 | } 36 | else if((*it).start > in.end) 37 | { 38 | result.push_back(in); 39 | in.start = (*it).start; 40 | in.end = (*it).end; 41 | } 42 | } 43 | return result; 44 | 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Leetcode/Q575.cpp: -------------------------------------------------------------------------------- 1 | //题意:分糖果,给定一个数组,这个数组中每个数字代表糖果的类别,数组元素为偶数个,要求给两个人各一半, 2 | //求这两个人中分到糖果种类最多的结果。 3 | 4 | 5 | //思路:尽可能给其中一个人分配不同种类的糖果。 6 | //hashtable,统计糖果的种类k,如果种类k小于n/2,则其中一个人最多有k个 7 | //如果糖果种类k >= n/2,则最多有n/2个 8 | 9 | class Solution { 10 | public: 11 | int distributeCandies(vector& candies) { 12 | set s; 13 | for(auto ca:candies) s.insert(ca); 14 | int k = s.size(): 15 | if(k >= candies.size() / 2) return candies.size()/2; 16 | else return k; 17 | } 18 | }; -------------------------------------------------------------------------------- /Leetcode/Q6.cpp: -------------------------------------------------------------------------------- 1 | //Zig-Zag模式输出 2 | //按照每行输出 3 | //可以观察到,对于每行之间的元素之差在每次减2.比如 4 | //PAYPALISHIRING 5 | //P A H N 6 | //A P L S I I G 7 | //Y I R 8 | 9 | //考虑两个方向,往下填充,网上填充,构建一个二维数组模拟填充,耗费空间 10 | //直接根据规律填充,输出每一行 11 | //第一行之间的元素diff = 2*row - 3; 12 | //连续元素差值是变换的,对于首尾行,元素差为2*row-3 13 | //对于其他行,元素差是交替变化,diff1+diff2总和和row有关 14 | //row = 6, sum = 8 15 | //row = 5, sum = 6 16 | //row = 4, sum = 4 17 | //row = 3, sum = 2 18 | //row = 2, 只有首位行 19 | 20 | //从[1,row-1]行,起始diff从(2*row-3)逐渐减2 21 | 22 | #include 23 | using namespace std; 24 | class Solution { 25 | public: 26 | string convert(string s, int numRows) { 27 | if(numRows == 1 || s.size() < numRows) return s; 28 | 29 | string result; 30 | int diff = 2*numRows - 2; 31 | //输出第一行 i=0; 32 | int j = 0; 33 | while(j < s.size()) {result+=s[j];j+=diff;} 34 | 35 | //输出中间行 36 | int sum = 2*(numRows-1); 37 | int startdiff = diff; 38 | for(int i = 1;i2以上,树的分叉是成组的。比如最后是按找两两分组,k/2 3 | //得到的商可以得到第k/2个分组。该分组为父一级的分叉,而父一级的分叉又是以3为分组。 4 | //分组编号从0开始.通过取 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | string getPermutation(int n, int k) { 13 | vectornum; 14 | for(int i=1;i<=n;++i) num.push_back(i); 15 | vector order; 16 | k--; //编号从0开始 17 | for(int i=1;i<=n;++i) 18 | { 19 | order.push_back(k%i); //余数正是所属的分叉; 20 | //cout << k%i << endl; 21 | k = k/i; 22 | } 23 | string result=""; 24 | for(int i = order.size()-1;i>=0;--i) 25 | { 26 | result+=to_string(num[order[i]]); 27 | cout << order[i] << endl; 28 | num.erase(num.begin()+order[i]); 29 | //cout << num.size() << endl; 30 | } 31 | cout << result << endl; 32 | } 33 | }; 34 | 35 | int main() 36 | { 37 | Solution s; 38 | s.getPermutation(4,14); 39 | } -------------------------------------------------------------------------------- /Leetcode/Q62.cpp: -------------------------------------------------------------------------------- 1 | //Unique Paths 2 | //从左上走到右下,每次只能向右或者向下,有多少中不同的路径 3 | //DP 4 | //opt[i][j]表示从左上角走到(i,j)格子的路径数 5 | //opt[0][j] = 1; //横着一条 6 | //opt[i][0] = 1; //纵着一条 7 | //opt[i][j] = opt[i-1][j]+opt[i][j-1] //既可以来自上面也可以来自左侧,两种方式之和 8 | // ---------------------- 9 | // | 1 1 1 1 1 | 10 | // | 1 2 3 4 5 | 11 | // | 1 3 6 10 15 | 12 | // | 1 4 10 20 35 | 13 | // ---------------------- 14 | 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | class Solution { 20 | public: 21 | int uniquePaths(int m, int n) { 22 | int opt[n]; 23 | for(int i=0;i 5 | #include 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int uniquePathsWithObstacles(vector>& obstacleGrid) { 11 | int m = obstacleGrid.size(); 12 | int n = obstacleGrid[0].size(); 13 | 14 | int opt[n]; //不使用矩阵,用行记录即可 15 | int tmp[m]; //第一列记录,因为如果有障碍物,接下来的位置为0 16 | 17 | for(int i=0;i>& grid) { 15 | int m = grid.size(); 16 | if(m == 0) return 0; 17 | int n = grid[0].size(); 18 | vector opt(grid[0].begin(),grid[0].end()); 19 | for(int i=0;i 3 | #include 4 | using namespace std; 5 | 6 | 7 | int Sqrt(int x,int s,int t) 8 | { 9 | if(s - t == 1) return t; //递归出现s-t = 1的情况,说明找不到,此时t*t < x ,s*s > x,返回小的 10 | //if(t*t < x) return t; //说明找不到 11 | long mid = s+(t-s)/2; //乘法溢出 12 | if(mid * mid == x) 13 | return mid; 14 | else if(mid*mid > x) 15 | return Sqrt(x,s,mid-1); 16 | else 17 | return Sqrt(x,mid+1,t); 18 | } 19 | 20 | 21 | int main() 22 | { 23 | int n; 24 | while(cin >> n) 25 | cout << Sqrt(n,0,n) << endl; 26 | } -------------------------------------------------------------------------------- /Leetcode/Q7.cpp: -------------------------------------------------------------------------------- 1 | //Reverse Integer 2 | //这个问题的坑在于:反过来之后可能出现越界,如果溢出则返回0 3 | 4 | class Solution { 5 | public: 6 | int reverse(int x) { 7 | long long sum = 0; 8 | long long flag = 1; 9 | if(x < 0){ x = -x; flag = -1;} 10 | while(x>0) //注意这里的>0,另外x = -2147483648,-x依然是,有符号的最小值x,-x表示一样。 11 | { 12 | sum = sum*10 + x%10; 13 | if(sum > INT_MAX) return 0; 14 | x /= 10; 15 | } 16 | if(flag < 0) sum = -sum; 17 | return sum; 18 | } 19 | }; -------------------------------------------------------------------------------- /Leetcode/Q70.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //DP思想,转换为斐波那契数列 7 | 8 | class Solution { 9 | public: 10 | int climbStairs(int n) { 11 | if(n<=2) return n; 12 | int f1 = 1; 13 | int f2 = 2; 14 | for(int i=3;i<=n;i++) 15 | { 16 | int f3 = f1+f2; 17 | f1 = f2; 18 | f2 = f3; 19 | } 20 | return f2; 21 | } 22 | }; -------------------------------------------------------------------------------- /Leetcode/Q73.cpp: -------------------------------------------------------------------------------- 1 | //O(mn) space,记录每个为0的位置,最后把这些行列设置为0 2 | //O(m+n) space,记录为0的行,记录为0的列 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | class Solution { 8 | public: 9 | void setZeroes(vector>& matrix) { 10 | set row; 11 | set col; 12 | int m = matrix.size(); 13 | int n = matrix[0].size(); 14 | for(int i=0;i>& matrix, int target) { 12 | int i=0,j=matrix.size()-1; 13 | int k = 0; 14 | while(i < j) //i,j区间至少为2 15 | { 16 | int mid = i+(j-i)/2; 17 | if(matrix[mid][0] == target) return true; 18 | else if(matrix[mid][0] < target) //如果matrix[mid][0] < target ,要找的位置不会包含mid,因为要找的是比target大的数中最小的那个. 19 | i = mid+1; 20 | else j = mid; 21 | } 22 | //i即为要搜索的区间的下界 23 | for(int k=0;k target,要在左半边查找 ,并且左半边区间肯定不包含mid,因为不等于target呀,所以查找区间为[i,mid-1] 34 | //但是如果不满足,说明mid <= target,要在右半边查找,并且mid有可能等于target,所以把mid包含起来.所以查找区间位[mid,j] 35 | -------------------------------------------------------------------------------- /Leetcode/Q75.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | void sortColors(vector &nums) 10 | { 11 | if(nums.size() == 0) return; 12 | int begin=0,current = 0; 13 | int end = nums.size()-1; 14 | 15 | while(current <= end) 16 | { 17 | if(nums[current] == 0){ 18 | swap(nums[current] ,nums[begin]); 19 | current++;begin++; 20 | } 21 | else if(nums[current] == 1) 22 | current++; 23 | else if(nums[current] == 2){ 24 | swap(nums[current],nums[end]); 25 | end--; 26 | } 27 | } 28 | } 29 | }; 30 | 31 | int main() 32 | { 33 | vector nums={0,0,1,2,0,1,2,2,1,1,2,0,1,0,0,2}; 34 | Solution s; 35 | s.sortColors(nums); 36 | for(auto it = nums.begin();it!=nums.end();++it) 37 | cout << *it << " "; 38 | cout << endl; 39 | } 40 | -------------------------------------------------------------------------------- /Leetcode/Q76.cpp: -------------------------------------------------------------------------------- 1 | //76. Minimum Window Substring 2 | //题意:给定字符串S,T,在s中查找最短的子串,该子串能够包含T中所有的字符。 -------------------------------------------------------------------------------- /Leetcode/Q78.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q78.cpp -------------------------------------------------------------------------------- /Leetcode/Q83.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* deleteDuplicates(ListNode* head) { 12 | ListNode *p = head; 13 | while(p!=NULL && p->next!=NULL) 14 | { 15 | ListNode *q = p->next; 16 | if(p->val == q->val) 17 | { 18 | p->next = q->next; 19 | } 20 | else 21 | p = p->next; 22 | } 23 | return head; 24 | } 25 | }; -------------------------------------------------------------------------------- /Leetcode/Q86.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定链表,以及x,所有小于x的节点都排在大于x的节点之前,调整过程中不能改动之间的相对顺序 2 | // 1 4 3 2 5 2 3 | // 1 2 2 | 4 3 5 4 | 5 | //思路:定义两个链表指针,一个用来链接小于x,一个用于大于x的 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | * int val; 11 | * ListNode *next; 12 | * ListNode(int x) : val(x), next(NULL) {} 13 | * }; 14 | */ 15 | 16 | //Submit:1 AC 17 | class Solution { 18 | public: 19 | ListNode* partition(ListNode* head, int x) { 20 | ListNode*less = new ListNode(0); 21 | ListNode *gre = new ListNode(0); 22 | ListNode *l = less,*g = gre; 23 | ListNode *cur = head; 24 | while(cur) 25 | { 26 | if(cur->val < x) {less->next = cur;less = less->next;} 27 | else {gre->next = cur; gre = gre->next;} 28 | cur = cur->next; 29 | } 30 | gre->next = NULL; 31 | less->next = gre->next; 32 | return l->next; 33 | } 34 | }; -------------------------------------------------------------------------------- /Leetcode/Q9.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //可以直接把整数转换为string,比较反转后的是不是和反转前的相同. 7 | // 注意输入的为int,所以要考虑负数 8 | 9 | class Solution { 10 | public: 11 | bool isPalindrome(int x) { 12 | if(x < 0) return false; 13 | string s = to_string(x); 14 | string stmp = s; 15 | reverse(s.begin(),s.end()); 16 | if(stmp == s) 17 | return true; 18 | return false; 19 | } 20 | }; 21 | 22 | //第二遍:上一次直接使用了int转string,并直接使用reverse来判断是否相同 23 | //如何不使用额外空间呢? 24 | //参考Q7,计算int反过来的数 25 | 26 | class Solution { 27 | public: 28 | bool isPalindrome(int x) { 29 | if(x < 0) return false; 30 | int a = x; 31 | long sum = 0; 32 | while(x > 0) 33 | { 34 | sum = sum * 10 + x%10; 35 | x /= 10; 36 | } 37 | if(sum == a) return true; 38 | return false; 39 | } 40 | }; -------------------------------------------------------------------------------- /Leetcode/Q90.cpp: -------------------------------------------------------------------------------- 1 | //题意:给定一个数组,给出所有可能的子集。注意:数组中可能含相同元素,且输出结果中不能包含相同的集合。 2 | -------------------------------------------------------------------------------- /Leetcode/Q94.cpp: -------------------------------------------------------------------------------- 1 | //题意:中序遍历,inorder。递归遍历左子树,再遍历root,再遍历右子树 2 | 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | * struct TreeNode { 7 | * int val; 8 | * TreeNode *left; 9 | * TreeNode *right; 10 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | vector inorderTraversal(TreeNode* root) { 16 | vector result; 17 | inorder(root,result); 18 | return result; 19 | } 20 | void inorder(TreeNode*root,vector&result) 21 | { 22 | if(root != NULL) 23 | { 24 | inorder(root->left,result); 25 | result.push_back(root->val); 26 | inorder(root->right,result); 27 | } 28 | } 29 | }; 30 | 31 | //非递归方法,借助外部的栈 32 | class Solution { 33 | public: 34 | vector inorderTraversal(TreeNode* root) { 35 | vector result; 36 | stack s; 37 | TreeNode *cur = root; 38 | while(!s.empty() || cur) 39 | { 40 | if(cur) //不断深度遍历左子树 41 | { 42 | s.push(cur); //压栈 43 | cur = cur->left; 44 | } 45 | else 46 | { 47 | cur = s.top(); 48 | s.pop(); 49 | result.push_back(cur->val); 50 | cur = cur->right; 51 | } 52 | } 53 | return result; 54 | } 55 | }; -------------------------------------------------------------------------------- /Leetcode/Q98.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/Leetcode/Q98.cpp -------------------------------------------------------------------------------- /MoreEffectiveCPP/item13.cpp: -------------------------------------------------------------------------------- 1 | //通过引用捕获异常 2 | //通过指针捕获异常不会因为拷贝对象导致的效率下降,但是带来的问题是: 3 | //抛出的指针不能指向一个局部对象。程序员应该在全局或者堆上定义这样一个 4 | //变量才能保证不会因为scope结束而被销毁。但有带来了新的问题,捕获该异常 5 | //的用户并不知道该指针是来自于堆上的变量还是全局的,是否应该delete。如果 6 | //不是堆上建立的异常对象,则delete会不可预测 7 | 8 | 9 | //总结: 10 | //(1)值捕获一方面每次抛出发生两次拷贝,另外可能出现派生类到基类的截断现象 11 | //(2)指针捕获无法确定是否释放异常对象 12 | //(3)通过引用捕获是最靠谱的。 -------------------------------------------------------------------------------- /MoreEffectiveCPP/item14.cpp: -------------------------------------------------------------------------------- 1 | //谨慎使用异常规格(exception specifications) 2 | 3 | //这句话什么意思呢?在item10~12中的测试程序其实已经被这个问题困扰了 4 | //定义了如下函数,对每个函数指定了确定的类型参数规格 5 | //所以如果无法捕获对应的异常,缺省行为是调用terminate,而terminate调用abort 6 | //导致程序直接终止,并且异常触发的栈中的其他变量没有被释放。 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | class UnexpectedException{}; 12 | void convertUnexpected() 13 | { 14 | cout << "call own exception..." << endl; 15 | throw UnexpectedException(); 16 | } 17 | 18 | void f1() throw(double) 19 | { 20 | throw 10.0; 21 | } 22 | 23 | void f2() throw(int) 24 | { 25 | try 26 | { 27 | f1(); 28 | } 29 | catch(int x) 30 | { 31 | cout << "x" << endl; 32 | } 33 | } 34 | 35 | void f3() throw(UnexpectedException) 36 | { 37 | throw 'x'; //not in exceptino-specification 38 | //不匹配,但是把unexpected转换成了UnexpectedException自定义的 39 | } 40 | 41 | void f4() throw(int) 42 | { 43 | set_unexpected(convertUnexpected); //注释掉就会terminate了 44 | try 45 | { 46 | f3(); 47 | } 48 | catch(UnexpectedException e) 49 | { 50 | cout << "catch unexpectedException ..." << endl; 51 | } 52 | catch(...) 53 | { 54 | cout << "x" << endl; 55 | } 56 | } 57 | 58 | int main() 59 | { 60 | //f2(); 61 | //输出:terminate called after throwing an instance of 'double' 62 | f4(); 63 | } 64 | 65 | //总结:理解不够透彻 66 | //exception-specification要谨慎使用 -------------------------------------------------------------------------------- /MoreEffectiveCPP/item15.cpp: -------------------------------------------------------------------------------- 1 | /*=============================================== 2 | # Author: lzjqsdd - lzj7179@163.com 3 | # Last modified: 2017-06-02 20:49 4 | # Filename: item15.cpp 5 | # Description: 了解异常处理的系统开销 6 | ================================================*/ 7 | 8 | //异常处理开销来源: 9 | //(1)跟踪对象是否被完全构造的数据结构 10 | //(2)try块,并且为异常规格生成的代码和他们为try块生成的代码一样多 11 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item16.cpp: -------------------------------------------------------------------------------- 1 | /*=============================================== 2 | # Author: lzjqsdd - lzj7179@163.com 3 | # Last modified: 2017-06-02 21:08 4 | # Filename: item16.cpp 5 | # Description: 牢记二八原则 6 | ================================================*/ 7 | 8 | //20%的代码使用了80%的程序资源,换句话说软件的整体性能取决于代码组成中的一小部分 9 | //使用profiler程序来识别出程序瓶颈 10 | //瓶颈是IO的程序对计算代码做优化可能收效甚微,所以定位瓶颈很重要,不是简单的拼接直觉 11 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item17.cpp: -------------------------------------------------------------------------------- 1 | /*=============================================== 2 | # Author: lzjqsdd - lzj7179@163.com 3 | # Last modified: 2017-06-02 21:21 4 | # Filename: item17.cpp 5 | # Description: lazy evaluation(懒惰计算法) 6 | ================================================*/ 7 | //延迟策略就是在需要的时候才开始进行资源的创建分配,不用先不管. 8 | //联系单例模式的lazy模式 9 | //如果是读操作则可以共享变量,如果是写操作,我们就需要制作拷贝。但是如何区分读写操作成为重点? 10 | // 11 | //(1) 惰性提取:对于大型的持久对象,可以存储在数据库中,在需要时提取.而且需要什么提取什么,因为存在读取开销以及网络开销 12 | //对象中的每个字段都用指向数据的指针来表示,此时的对象就像一个空壳。 13 | //(2) 惰性表达式 14 | // 比如矩阵m3 = m1 + m2 ,在没有用到m3时候,可以不计算,通过建立一个数据结构表示m3是m1和m2的和 15 | // 而且矩阵计算中我们可能只访问了m3其中某一个元素,显然没必要计算其他元素 16 | //(3) 惰性实例化:如果当前实例没有用到,可以先不用构造 17 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item18.cpp: -------------------------------------------------------------------------------- 1 | /*=============================================== 2 | # Author: lzjqsdd - lzj7179@163.com 3 | # Last modified: 2017-06-02 22:56 4 | # Filename: item18.cpp 5 | # Description: 分期瘫痪期望的计算(over-eager evaluation)过度热情计算法 6 | ================================================*/ 7 | 8 | //举个例子,在一个容器中求最大最小值max,min 9 | //(1)如果lazy evaluation的话,直到请求max,min的时候才计算 10 | //而over-eager evaluation则是每次容器加入元素都更新max,min。只要有请求直接返回就可以 11 | //如果是频繁的调用max,min,则可以把计算开销分摊在每一步跟踪维护的开销上。 12 | //(2)caching方法,把常访问的cache起来,避免查库的开销 13 | //(3)prefetching预提取 14 | // 15 | //over-evaluation主要用在频繁请求或者计算上,所以才会通过prefetch或者caching方法提前把结果准备好。 16 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item19.cpp: -------------------------------------------------------------------------------- 1 | /*=============================================== 2 | # Author: lzjqsdd - lzj7179@163.com 3 | # Last modified: 2017-06-02 23:29 4 | # Filename: item19.cpp 5 | # Description: 理解临时对象的来源 6 | ================================================*/ 7 | 8 | #include 9 | using namespace std; 10 | 11 | void swap(int a,int b) 12 | { 13 | int tmp = a; //这里的tmp不是临时变量,而是局部对象 14 | a = b; 15 | b = tmp; 16 | } 17 | 18 | 19 | //c++中真正的临时对象是看不见的 20 | //建立未命名的非堆对象会产生零食对象: 21 | //(1)函数参数的隐式类型转换 22 | //(2)函数返回对象 23 | 24 | class A 25 | { 26 | public: 27 | A(int x):m(x){ 28 | cout << "call A ctor ..." << endl; 29 | } 30 | ~A(){ 31 | cout << "call A dstor ..." << endl; 32 | } 33 | int m; 34 | }; 35 | 36 | 37 | //如果参数是非常量引用,如果发生拷贝,函数修改的是这个临时变量的值,这不是程序员所期望的 38 | void printA(A a) //注意这里是传值或者常量引用才会发生类型转换,如果是引用则不会 39 | { 40 | cout << "A.m is " << a.m << endl; 41 | } 42 | 43 | A printB() 44 | { 45 | cout << "Test return value..." << endl; 46 | //A a(20); 47 | //return a; //关于返回值优化 48 | return A(20); 49 | } 50 | 51 | int main() 52 | { 53 | //printA(10); //这里传递参数时出现隐式转换 54 | A a = printB(); 55 | cout << "here " << endl; //输出的dstor是在这句之后 56 | } 57 | 58 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item2.cpp: -------------------------------------------------------------------------------- 1 | //四种cast类型 2 | 3 | #include 4 | using namespace std; 5 | class Base 6 | { 7 | public: 8 | Base(){} 9 | virtual void func(){} 10 | int a; 11 | }; 12 | 13 | class Child:public Base 14 | { 15 | public: 16 | Child(){} 17 | int b; 18 | }; 19 | 20 | 21 | typedef void (*FuncPtr)(); //无返回值类型 22 | 23 | int doSomething() //有返回值的一个函数 24 | { 25 | cout << "doSomething..."<(&pb); //继承关系必须满足多态(有虚函数) 34 | 35 | 36 | 37 | //reinterpter_cast在函数指针之间的转换 38 | FuncPtr funcPtrArray[10]; 39 | 40 | //想把doSomething放到funcPtrArray中 41 | funcPtrArray[0] = reinterpret_cast(&doSomething); 42 | funcPtrArray[0](); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item20.cpp: -------------------------------------------------------------------------------- 1 | /*=============================================== 2 | # Author: lzjqsdd - lzj7179@163.com 3 | # Last modified: 2017-06-03 23:14 4 | # Filename: item20.cpp 5 | # Description: 协助完成返回值优化 6 | ================================================*/ 7 | 8 | 9 | //返回值优化Named Return Value Optimization(NRVO) 10 | //返回constructor argument,直接以构造函数的方式返回所需对象,会得到编译器优化 11 | // 12 | // 13 | //ItemM21 14 | ///另外参数传递过程中出现的隐式类型转换导致的临时对象,可以重载对应的形式来完成。但是没有 15 | //必要实现大量的重载函数,除非有理由确信程序使用重载函数后整体效率会有显著的提高。 16 | // 17 | // 18 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item22.cpp: -------------------------------------------------------------------------------- 1 | /*=============================================== 2 | # Author: lzjqsdd - lzj7179@163.com 3 | # Last modified: 2017-06-03 23:40 4 | # Filename: item22.cpp 5 | # Description: 考虑用运算符的复制形式(+=,-=,op=)取代其单独形式(+,-,op) 6 | ================================================*/ 7 | 8 | #include 9 | using namespace std; 10 | template 11 | const T operator+(const T& lhs,const T&rhs) 12 | { 13 | return T(lhs) += rhs; 14 | } 15 | 16 | template 17 | const T operator-(const T& lhs,const T& rhs) 18 | { 19 | return T(lhs) -= rhs; 20 | } 21 | 22 | class A 23 | { 24 | public: 25 | A(int x):m(x){ 26 | curn = N++; 27 | cout << "call A ctor..." << curn << endl; 28 | } 29 | A(const A& a):m(a.m){ //这里参数的const 30 | curn = N++; 31 | cout << "call A copy ctor..."<< curn << endl; 32 | } 33 | 34 | A& operator+=(const A& rhs) 35 | { 36 | m += rhs.m; 37 | return *this; 38 | } 39 | A& operator-=(const A& rhs) 40 | { 41 | m -= rhs.m; 42 | return *this; 43 | } 44 | 45 | ~A(){cout << "call A dstor..."<< curn << endl;} 46 | static int N; 47 | private: 48 | int m; 49 | int curn; 50 | }; 51 | 52 | int A::N = 0; 53 | 54 | 55 | int main() 56 | { 57 | A a1(10); 58 | A a2(20); 59 | A a3 = a1 + a2; 60 | } 61 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item25.cpp: -------------------------------------------------------------------------------- 1 | //讲构造函数和非成员函数虚拟化 2 | //当有一个指针或者引用,但是不知道其只想对象的真是类型是什么时,可以通过调用虚函数来 3 | //完成特定类型的行为,这就是动态多态。 4 | //那么,虚拟构造函数什么作用呢? 虚拟构造函数是指能够根据输入数据的不同而建立不同类型的对象, 5 | //但是注意这里的虚拟构造函数不是说构造函数是虚函数,而是行为类似于构造行为的函数 6 | //虚拟拷贝构造函数:self-clone,返回调用对象的一份拷贝 7 | // 8 | // 9 | //TODO 10 | //实现虚拟的构造函数,模拟operator<<,定义虚拟函数和一个非虚拟函数来完成操作。 11 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item4.cpp: -------------------------------------------------------------------------------- 1 | //避免无用的确实参数构造 2 | // 3 | #include 4 | #include 5 | using namespace std; 6 | class A 7 | { 8 | public: 9 | A(int x){a = x;} 10 | int a; 11 | }; 12 | 13 | typedef A* PA; 14 | 15 | int main() 16 | { 17 | //method1 18 | //A array[10]; //对于有参数构造方式,非堆上构造的方式无法分配内存。 19 | A array[] = {A(1),A(2),A(3)}; //使用列表初始化,调用有参构造 20 | 21 | //method2 22 | PA parray[10]; //声明一个指针数组(指针类型属于内建类型,内存大小是确定的),但是如果是对象数组 23 | //在不调构造函数无法分配具体空间 24 | 25 | //method3 26 | PA * pp = new PA[10]; ///此时分配的都是指针类型的大小,也可以通过 27 | //但是pp中的指针并没有指向 28 | //使用for循环复制pp元素,自己要负责堆上内存的销毁。另外通过指针数组的方式增加了内存量。 29 | //既要维护指针的大小也要维护对象空间的大小 30 | for(int i=0;i<10;++i) 31 | pp[i] = new A(i); 32 | 33 | 34 | //method4 35 | A a[10](2);//这种方式也可以唉 36 | cout << a[0].a << endl; 37 | 38 | //method5 39 | //使用placenment new 40 | //方法:new(内存)type 41 | void *rawMemory = operator new[](10*sizeof(A)); ///提前分配内存 42 | A *ppa = static_cast(rawMemory); 43 | for(int i = 0;i<10;++i) 44 | new (&ppa[i])A(i); //但是仍然要提供构造参数 45 | operator delete[](rawMemory);//删除数组的方式 46 | //而delte[]ppa是未定义的,毕竟ppa内存不是new操作符分配的 47 | } 48 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/item6.cpp: -------------------------------------------------------------------------------- 1 | //--------------------------------------------------- 2 | //|自增自减操作符前缀形式和后缀形式的区别 by lzjqsdd| 3 | //--------------------------------------------------- 4 | //不论是++还是--,其前缀形式都只有一个参数,无法区分,所以c++规定了后缀形式有一个int类型的参数,传递0进去 5 | //而前缀形式没有 6 | //以下代码仅提供++的测试,--类似 7 | #include 8 | using namespace std; 9 | class A 10 | { 11 | public: 12 | A():a(0){} 13 | //++前缀,++A,返回A&是为了可以实现++(++A),返回一个左值的引用 14 | A& operator++() { 15 | cout << "call ++A" << endl; 16 | ++a;return *this; 17 | } 18 | //++后缀,首先返回的是原始的值,然后A再自增,这时候放回的是const 19 | //如果是const引用,会出现外部引用了局部变量的问题 20 | //如果返回引用会是的A++++成立,而内建类型是不允许的 21 | //而且(A++)++之后A只自增了一次,第二次是在返回的对象上自增的。与感官上不符合 22 | const A operator++(int){ 23 | cout << "call A++" << endl; 24 | A old = *this; ++this->a; return old; //而建立临时对象多了临时对象的构造和析构 25 | //所以在自定义类型是最好多使用前缀++ 26 | //参考item19:建立一个临时对象作为返回值 27 | } 28 | void printA(){cout << "value is " << a << endl;} 29 | private: 30 | int a; 31 | }; 32 | 33 | 34 | int main() 35 | { 36 | A ta; 37 | ta++; //ta = 1 38 | 39 | A b = ta++; //ta = 2; 40 | b.printA(); //b = 1; 41 | 42 | ta.printA(); 43 | ++ta; //ta = 3 44 | ta.printA(); 45 | //(ta++)++; ++(ta++); // 这两种形式都不会编译通过,试图修改const的对象 46 | (++ta)++; //ta = 5 47 | ta.printA(); 48 | ++(++(++ta)); 49 | ta.printA(); 50 | 51 | ta.operator++(0); 52 | ta.operator++(); 53 | } 54 | 55 | -------------------------------------------------------------------------------- /MoreEffectiveCPP/stack-unwinding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class A 5 | { 6 | public: 7 | A(int x):m(x){ 8 | cout << "call A ctor" << endl; 9 | } 10 | ~A() 11 | { 12 | cout << "call A dstor:" << m << endl; 13 | } 14 | private: 15 | int m; 16 | }; 17 | 18 | 19 | int func1() throw(int) 20 | { 21 | A a(1); ///a在stack-unwinding过程中被释放 22 | cout << "start func1" << endl; 23 | throw 100; 24 | cout << "end func2" << endl; 25 | } 26 | 27 | int func2() throw(int) 28 | { 29 | cout << "start func2" << endl; 30 | A a(2); 31 | func1(); 32 | cout << "end func2" << endl; 33 | } 34 | 35 | int func3() 36 | { 37 | cout << "call func1" << endl; 38 | A a(3); 39 | try{ 40 | func2(); 41 | } 42 | catch(int i) 43 | { 44 | cout << "Caught Exception: " << i << endl; 45 | } 46 | cout << "end func3" << endl; 47 | } 48 | 49 | 50 | int main() 51 | { 52 | func3(); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /POJ/poj1003.cpp: -------------------------------------------------------------------------------- 1 | /*浮点数加和求平均*/ 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | float c; 12 | while(~scanf("%f",&c) && c!=0.00) 13 | { 14 | float sum = 0; 15 | int i; 16 | for(i=1;;i++) 17 | { 18 | sum+=1.0/(i+1); 19 | if(sum > c) 20 | break; 21 | } 22 | cout< 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | float salary,sum; 10 | 11 | for(int i=0;i<12;i++) 12 | { 13 | cin>>salary; 14 | sum+=salary; 15 | } 16 | 17 | printf("$%.2f\n",sum/12.0); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /POJ/poj1045.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | result = CRW*Vs/sqrt(1+(crw)^2) 3 | */ 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | using namespace std; 11 | 12 | int main() 13 | { 14 | double vs,r,c,w; 15 | int num; 16 | cin>>vs>>r>>c>>num; 17 | while(num--) 18 | { 19 | cin>>w; 20 | double re = c*r*w; 21 | cout< 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | typedef struct seq { 13 | int index; 14 | int flag; 15 | }S; 16 | 17 | int main() 18 | { 19 | int t,n,p; 20 | 21 | 22 | cin>>t; 23 | while(t--) 24 | { 25 | int s1[50]={0}; 26 | stack s2; 27 | S tmp1,tmp2; 28 | 29 | cin>>n; 30 | for(int i=1;i<=n;i++) 31 | { 32 | cin>>p; 33 | s1[p+i]=1; 34 | } 35 | 36 | tmp1.index=0;tmp1.flag=0; 37 | int k=0; 38 | s2.push(tmp1); 39 | 40 | for(int i=1;i<=2*n;i++) 41 | { 42 | tmp1.index=i;tmp1.flag=s1[i]; 43 | 44 | tmp2 = s2.top(); 45 | if(tmp1.flag==tmp2.flag) s2.push(tmp1); 46 | else 47 | { 48 | s2.pop(); k++; 49 | cout<<(i-tmp2.index+1)/2; 50 | if(k!=n) cout<<" "; 51 | else cout< 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ; 6 | 2 [label="petal length <= 4.95\nentropy = 0.993\nsamples = 71\nvalue = [0, 32, 39]"] ; 7 | 0 -> 2 [labeldistance=2.5, labelangle=-45, headlabel="False"] ; 8 | 3 [label="petal width <= 1.65\nentropy = 0.4306\nsamples = 34\nvalue = [0, 31, 3]"] ; 9 | 2 -> 3 ; 10 | 4 [label="entropy = 0.0\nsamples = 30\nvalue = [0, 30, 0]"] ; 11 | 3 -> 4 ; 12 | 5 [label="entropy = 0.8113\nsamples = 4\nvalue = [0, 1, 3]"] ; 13 | 3 -> 5 ; 14 | 6 [label="petal length <= 5.05\nentropy = 0.1793\nsamples = 37\nvalue = [0, 1, 36]"] ; 15 | 2 -> 6 ; 16 | 7 [label="entropy = 0.8113\nsamples = 4\nvalue = [0, 1, 3]"] ; 17 | 6 -> 7 ; 18 | 8 [label="entropy = 0.0\nsamples = 33\nvalue = [0, 0, 33]"] ; 19 | 6 -> 8 ; 20 | } -------------------------------------------------------------------------------- /PythonMachineLearning/tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzjqsdd/Crack-Coding-Interview/aa2971897943a45cabe53d6ec7653b8d3abf0686/PythonMachineLearning/tree.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 本项目包含了我准备技术面试过程中的参考书籍以及代码,和大家一起分享. 2 | 3 | [English](https://github.com/lzjqsdd/Crack-Coding-Interview/blob/master/README_EN.md) 4 | 5 | ### 目录 6 | - Algorithm **包含了数论、树、动态规划** 7 | - Basic **包含了C++基本知识的案例、Boost库的使用** 8 | - CPP-Primer **整理了本书各章节相关的例子** 9 | - CrackInterview 10 | - DesignPattern **包含了每类设计模式的测试代码以及说明** 11 | - EffectiveCPP **包含本书每个章节的测试例子** 12 | - MoreEffectiveCPP **包含本书每个章节的测试例子** 13 | - Leetcode **包含了leetcode上230多道题目的题解、以及测试用例,覆盖了各类题型** 14 | - POJ 15 | - PythonMachineLearning **机器学习的案例代码** 16 | 17 | ### 参考书籍 18 | - **_c++ primer_** by Stanley B. LippmanBarbara E. Moo JoséeLaJoie 19 | - **_Insider the c++ object model_** by Houjie 20 | - **_Effective C++_** by Scott Meyers 21 | - **_More Effective C++_** by Scott Meyers 22 | - **_Effective STL_** by Scott Meyers 23 | - **_Crack the coding interview_** 24 | - **_Coding Interviews_** or **_剑指offer_** 25 | - **_https://leetcode.com/_** 26 | - **_https://www.nowcoder.com_** 27 | 28 | 29 | ### 一起分享 30 | 如果您觉得本项目有欠缺或者想贡献更多的代码进来,欢迎提交PR 31 | 32 | ### License 33 | This repository is under GNU General Public License v3.0(GPL3.0) 34 | -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 | This Repository contains all my codes for preparing interview. 2 | 3 | ### list 4 | - Algorithm **include Number,Tree,DP** 5 | - Basic **include c++ basic knowledge** 6 | - CPP-Primer 7 | - CrackInterview 8 | - DesignPattern 9 | - EffectiveCPP 10 | - MoreEffectiveCPP 11 | - Leetcode **Contains about 230+ Solutions** 12 | - POJ 13 | - PythonMachineLearning 14 | 15 | ### Reference Book 16 | - **_c++ primer_** by Stanley B. LippmanBarbara E. Moo JoséeLaJoie 17 | - **_Insider the c++ object model_** by Houjie 18 | - **_Effective C++_** by Scott Meyers 19 | - **_More Effective C++_** by Scott Meyers 20 | - **_Effective STL_** by Scott Meyers 21 | - **_Crack the coding interview_** 22 | - **_Coding Interviews_** or **_剑指offer_** 23 | - **_https://leetcode.com/_** 24 | - **_https://www.nowcoder.com_** 25 | 26 | 27 | ### Join 28 | If you have any coding suggestion or gist,you can submit your pull request to make this repository better. 29 | 30 | 31 | ### License 32 | This repository is under GNU General Public License v3.0(GPL3.0) 33 | --------------------------------------------------------------------------------