Dorothydu commited on
Commit
e345cd9
·
verified ·
1 Parent(s): e86d5e0

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. -Api_avec_python-master/ex2.py +115 -0
  2. -QuQ--master/README.md +50 -0
  3. -QuQ--master/baseClass/DMO.py +266 -0
  4. -QuQ--master/config/function.cfg +6 -0
  5. -QuQ--master/doc/Class-relation.docx +0 -0
  6. -QuQ--master/results/README.md +1 -0
  7. -QuQ--master/userCode/Teleportation.py +23 -0
  8. 0617-audio_stream-master/model/__init__.py +1 -0
  9. 0617-audio_stream-master/test.py +67 -0
  10. 0621_test-master/django_app/post/apps.py +5 -0
  11. 0621_test-master/django_app/post/models.py +9 -0
  12. 10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree3.go +24 -0
  13. 10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum.go +42 -0
  14. 10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits.py +26 -0
  15. 10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence2.go +22 -0
  16. 10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence_test.go +18 -0
  17. 10-week-algorithm-excercise-master/OneQuestionPerDay/350/intersection_of_two_arrays_ii.py +16 -0
  18. 10-week-algorithm-excercise-master/OneQuestionPerDay/387/first_unique_character_in_a_string.py +12 -0
  19. 10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz.go +19 -0
  20. 10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray.go +29 -0
  21. 10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray2.py +34 -0
  22. 10-week-algorithm-excercise-master/OneQuestionPerDay/83/remove_duplicates_from_sorted_list.py +21 -0
  23. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number.py +17 -0
  24. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number_test.go +19 -0
  25. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space.py +9 -0
  26. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF59/max_sliding_window.go +18 -0
  27. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF6/reverse_link_node.go +20 -0
  28. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF6/reverse_link_node.py +17 -0
  29. 10-week-algorithm-excercise-master/Week_01/1/two_sum.py +12 -0
  30. 10-week-algorithm-excercise-master/Week_01/11/container_with_most_water.go +18 -0
  31. 10-week-algorithm-excercise-master/Week_01/11/container_with_most_water_test.go +20 -0
  32. 10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle.go +19 -0
  33. 10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle3.go +19 -0
  34. 10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii.go +27 -0
  35. 10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii.py +22 -0
  36. 10-week-algorithm-excercise-master/Week_01/15/3sum.go +31 -0
  37. 10-week-algorithm-excercise-master/Week_01/15/3sum_test.go +22 -0
  38. 10-week-algorithm-excercise-master/Week_01/155/min_stack.py +24 -0
  39. 10-week-algorithm-excercise-master/Week_01/189/rotate_array.go +12 -0
  40. 10-week-algorithm-excercise-master/Week_01/189/rotate_array_test.go +25 -0
  41. 10-week-algorithm-excercise-master/Week_01/20/valid_parentheses.go +23 -0
  42. 10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list.go +14 -0
  43. 10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists.go +28 -0
  44. 10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum.py +31 -0
  45. 10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs2.py +51 -0
  46. 10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group.go +33 -0
  47. 10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array_test.go +21 -0
  48. 10-week-algorithm-excercise-master/Week_01/283/move_zeros_test.go +23 -0
  49. 10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water.go +27 -0
  50. 10-week-algorithm-excercise-master/Week_01/README.md +135 -0
-Api_avec_python-master/ex2.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###########
2
+ # IMPORTS #
3
+ ###########
4
+
5
+ import requests
6
+
7
+ # url va me servir à changer de page dans la boucle while
8
+ url = "https://swapi.co/api/people/"
9
+
10
+ print("Welcome to the Useless Star Wars Facts !")
11
+
12
+ # Ce tableau contient les noms de certains personnages importants de Star Wars
13
+ # qui n'apparaissent pas dans au moins 3 films, mais dont j'ai quand même envie
14
+ # d'avoir les informations
15
+ namesWeWant = ["Dooku", "Darth Maul", "Jar Jar Binks",
16
+ "Grievous", "Jango Fett", "Qui-Gon Jinn", "Lando Calrissian",
17
+ "Ackbar", "Greedo",]
18
+
19
+ # Quand il n'y a plus de "page suivante", la page "next" sera égale à None
20
+ # Donc, je boucle sur url tant qu'elle n'est pas égale à None :)
21
+ while url is not None:
22
+
23
+ ############################
24
+ # RÉCUPÉRATION DES DONNÉES #
25
+ ############################
26
+
27
+ # Je fais la requête sur la page en cours, et je récupère la data
28
+ r = requests.get(url)
29
+ data = r.json()
30
+
31
+ # C'est ici que je change l'url pour avoir la page d'après :)
32
+ url = data["next"]
33
+ # Ce tableau est la liste de tous les personnages
34
+ persosTab = data["results"]
35
+
36
+ ###########################
37
+ # UTILISATION DES DONNÉES #
38
+ ###########################
39
+
40
+ # Je fais ensuite une boucle qui parcourt tous les personnages
41
+ # et qui affiche plein d'infos sur eux :)
42
+ for perso in persosTab:
43
+ name = perso["name"]
44
+
45
+ # Si le perso en cours n'est pas un des persos du tableau namesWeWant
46
+ # et n'apparaît pas dans au moins 3 films, on le passe et on continue
47
+ if name not in namesWeWant:
48
+ if len(perso["films"]) < 3:
49
+ continue
50
+
51
+ print("")
52
+
53
+ # Petite condition pour Jar Jar Binks, notre Dieu à tous
54
+ if name == "Jar Jar Binks":
55
+ name = "The Great and Mighty Jar Jar Binks, Emperor of the World"
56
+
57
+ # Condition spéciale qui ajoute une option au cas où cette info est inconnue
58
+ eyes = perso["eye_color"]
59
+ if eyes == "unknown" or eyes == "n/a":
60
+ eyes = "no-eyed"
61
+
62
+ # Ici, je récupère le lien de la race du perso en cours, et je fais une requête dessus
63
+ # Si le perso en cours n'a pas de race précisée, je lui donne la race "thing"
64
+ if len(perso["species"]) == 1:
65
+ speciesURL = perso["species"][0]
66
+ rSpecies = requests.get(speciesURL)
67
+ species = rSpecies.json()["name"]
68
+ else:
69
+ species = "thing"
70
+
71
+ # Petite condition spéciale pour Yoda, le plus grand des maîtres Jedi
72
+ if species == "Yoda's species":
73
+ species = "Jedi Master"
74
+
75
+ # Ici, je récupere le genre du perso en cours, et lui attribue son pronom
76
+ # Pour un homme, "He", pour une femme "she"
77
+ # Et pour les inconnus et les hermaphrodites (comme Jabba, no fake), "It"
78
+ gender = perso["gender"]
79
+ if gender == "unknown" or gender == "n/a":
80
+ gender = "It"
81
+ elif gender == "male":
82
+ gender = "He"
83
+ elif gender == "female":
84
+ gender = "She"
85
+ elif gender == "hermaphrodite":
86
+ gender = "It"
87
+
88
+ # Ici, je récupère la couleur des cheveux
89
+ hair = perso["hair_color"]
90
+ if hair == "unknown" or hair == "n/a" or hair == "none":
91
+ hair = "bald"
92
+ # Petite condition spéciale pour Darth Vader, brûlé au 66e degré
93
+ if name == "Darth Vader":
94
+ hair = "burnt"
95
+
96
+ # Ici, je récupère la taille en cm
97
+ height = perso["height"]
98
+
99
+ # Ici, je récupère le poids en kg
100
+ mass = perso["mass"]
101
+ if mass == "unknown":
102
+ mass = "0"
103
+
104
+ # Ici, je récupère la planète d'origine
105
+ homeworld = requests.get(perso["homeworld"])
106
+ homeworldName = homeworld.json()["name"]
107
+ if homeworldName == "unknown":
108
+ homeworldName = "an unknown planet"
109
+
110
+ # Et enfin, je fais mon méga print avec toutes les infos ! :)
111
+ print(name + " is a " + eyes + " eyed " + species + ". "
112
+ + gender + " is " + height + "cm tall, weighs " + mass
113
+ + "kg, and has " + hair + " hair. " + gender + " comes from " + homeworldName + " ! :)")
114
+
115
+ print("")
-QuQ--master/README.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # QuanSim
2
+ **Founder:** [@quantumnewbie](https://github.com/zhangxin20121923) <br/>
3
+ **Contributors:** [@quantumnewbie](https://github.com/zhangxin20121923) <br/>
4
+ **Institution:** Key laboratory of CPS-DSC, Chongqing University
5
+ ## Introduction
6
+ QuanSim is a platform of quantum programming, which consists of a quantum simulator and a suit of quantum program language. With the support of QuanSim, we can design and implement quantum algorithms and vertify the performance of algorithms. What's more, we can design quantum programming language on this platform. If you have any questions, please contact with zhang.x\@cqu.edu.cn.
7
+ ## QuanSim
8
+ ### Architecture
9
+ QuanSim is developed by Python3 and the architecture of it is shown as follow.
10
+ ![](https://raw.githubusercontent.com/zhangxin20121923/QuanSim/master/pic/QuanSim-FrameWork.png)
11
+ We should point out that "Decohenerce Simulator", "Quantum Program Control-flow" and "Analysis and Verification of Quantum program" are still under development. And we will release them in the future.
12
+
13
+ ### Data Type
14
+ There are four kinds of data types in QuanSim: Bit, Qubit, Qubits and Circuit. Bit means one classical bit, and the value of this type is either 0 or 1. Qubit is the most basic type in quantum computing, which can be in 0 and 1 simultaneously. Qubits will be generated when Qubit is entangled with other Qubit. And Circuit is the basic executable unit. Please note that each experiment and each circuit is a one-to-one correspondence.<br/>
15
+ The relation of these data types are shown as follow.
16
+ ![](https://raw.githubusercontent.com/zhangxin20121923/QuanSim/master/pic/QuanSim-datatype.png)
17
+
18
+ ### Quantum Gate
19
+ For now, the supported quantum gates include: single-qubit gate (that is, H-gate, PauliX-gate, PauliY-gate, PauliZ-gate, S-gate, T-gate, Rx, Ry, Rz, $S^dagger$-gate and $T^dagger$-gate) and double-qubit gate (that is, CNOT). And it's clearly that the set of these gates are universal. <br/>
20
+
21
+ ## How to Use It
22
+ ### Start
23
+ You can run QuanSim in the following two ways:<br/>
24
+ * Pass the function name you want to run to *main.py*. The format of the function name should be *function()*. <br/>
25
+ * Run *main.py* without parameter, then QuanSim will give you a list of all available functions. Type the id of the function you want to execute.<br/>
26
+
27
+ ### Executive Mode
28
+ "simulator" and "theory" are two optional executive modes. The former will bring noise to experiments, but the latter will get the theoretical result of this experiment. And you can switch the mode by modifying *executeMode.cfg*.<br/>
29
+ Please note that you can choose whether execute the circuit on IBMQX when it was generated successfully. If you want, you should fill in *IBMToken.cfg* with personal information first. And the personal information can be obtained from *[IBMQX](https://quantumexperience.ng.bluemix.net/qstage/)*.
30
+
31
+ ### Design Your Own Code
32
+ Create a new file in *UserCode* folder and name it *\*\*.py*. Design an entry function in this file. Please note that the name of the entry function shouldn't be same with any existing funciton. Then add the name of the file and the entry function to *function.cfg*.
33
+
34
+ ### Package Dependency
35
+ In order to taste all the features of QuanSim, the following Python package is compulsive:<br/>
36
+ 1.*matplotlib-2.1*<br/>
37
+ 2.*numpy-1.13.3*<br/>
38
+ 3.*pillow-4.2.1*<br/>
39
+ 4.*psutil-5.4.0*<br/>
40
+ The following packsge is optional:<br/>
41
+ 1.*IBMQuantumExperience-1.8.16*
42
+
43
+ ## Development Plan
44
+ We should point out that there are still some features that haven't been developed yet:
45
+ * Due to the physical constraints, the QASM code generated by QuanSim may not be able to execute on IBMqx successfully. We should continue optimizing the code so that it satisfies the requirement.<br/>
46
+ 2017.12.4----Add the optimizing module in QuanSim, and we can execute the QASM code which is under the constraint of IBM on IBM chip.<br/>
47
+ * The analysis and verification of quantum program is an urgent requirement. <br/>
48
+ * The quantum control-flow is still under development.<br/>
49
+ * Some unknown bugs.<br/>
50
+
-QuQ--master/baseClass/DMO.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ from baseGate import *
3
+ from Gate import *
4
+ import copy
5
+ #only X,Y,Z,I,H,S,Sd,T,Td,CNOT is allowed
6
+ import re
7
+
8
+
9
+ #delay measure opertor class used in DMif
10
+ class DMO:
11
+ def __init__(self,ql,vl):
12
+ #storage the control-qubit list
13
+ self.DMOql = ql
14
+ self.split = SplitGate()
15
+ self.DMOvl = vl
16
+
17
+ #get the info about the function name and the line number
18
+ def get_curl_info(self):
19
+ try:
20
+ raise Exception
21
+ except:
22
+ f = sys.exc_info()[2].tb_frame.f_back
23
+ return [f.f_code.co_name, f.f_lineno]
24
+
25
+ #set the name of the control qubit gate:if there are 3 qubit in self.DMOql and vl = [1,0,1],
26
+ #then the full name should be c1-c0-c1-SingleQubitGate.
27
+ def __fullGName(self,gn:str,vl:list,ql:list):
28
+ name = ""
29
+ for i in range(0,len(ql)):
30
+ name += "c"
31
+ if len(vl) == 1:
32
+ j = 0
33
+ else:
34
+ j = i
35
+ if vl[j] == 0:
36
+ name += "0"
37
+ else:
38
+ name += "1"
39
+ name += "-"
40
+ cgn = name[0:len(name)-1]
41
+ return self.__setFullGName(cgn,gn)
42
+ #get the full name of the multi-controlled gate
43
+ def __setFullGName(self,cgn:str,gn:str):
44
+ return (cgn + "-" + gn)
45
+
46
+
47
+
48
+ #the "cq" is the control-qubit of the CNOT gate
49
+ def Operator(self,gateName:str,tq:Qubit,cq = None,angle = None):
50
+
51
+ ql = self.DMOql.copy()
52
+ vl = self.DMOvl.copy()
53
+
54
+ QASM = ""
55
+ if cq != None:
56
+ #CNOT gate call this function. We shoulde convert the format of CNOT
57
+ ql.append(cq)
58
+ vl.append(1)
59
+ fullGName = self.__fullGName(gateName,vl,ql)
60
+ #CNOT gate
61
+ if fullGName == "c1-X":
62
+ return CNOT(ql[0],tq)
63
+
64
+ #the return value is a list consisted of all the control-qubits and the target-qubit
65
+ if re.match(r'^(c\d-){1}.{1,2}$',fullGName) != None:
66
+ #split the CU and execute the computation
67
+ return self.split.CU(fullGName,ql[0],tq,vl,angle,True)
68
+ else:
69
+ #split the MCU and execute the computation
70
+ return self.split.MCU(fullGName,ql,tq,vl,angle,True)
71
+
72
+
73
+ def X(self,q:Qubit):
74
+ gateName = "X"
75
+ return self.Operator(gateName,q)
76
+
77
+ def Y(self,q:Qubit):
78
+ gateName = "Y"
79
+ return self.Operator(gateName,q)
80
+
81
+ def Z(self,q:Qubit):
82
+ gateName = "Z"
83
+ return self.Operator(gateName,q)
84
+
85
+ def H(self,q:Qubit):
86
+ gateName = "H"
87
+ return self.Operator(gateName,q)
88
+
89
+ def S(self,q:Qubit):
90
+ gateName = "S"
91
+ return self.Operator(gateName,q)
92
+
93
+ def Sd(self,q:Qubit):
94
+ gateName = "Sd"
95
+ return self.Operator(gateName,q)
96
+
97
+ def T(self,q:Qubit):
98
+ gateName = "T"
99
+ return self.Operator(gateName,q)
100
+
101
+ def Td(self,q:Qubit):
102
+ gateName = "Td"
103
+ return self.Operator(gateName,q)
104
+
105
+ def CNOT(self,q1:Qubit,q2:Qubit):
106
+ gateName = "X"
107
+ return self.Operator(gateName,q2,q1)
108
+
109
+ def Rz(self,phi,q:Qubit):
110
+ gateName = "Rz"
111
+ return self.Operator(gateName,q,None,phi)
112
+
113
+ def Ry(self,phi,q:Qubit):
114
+ gateName = "Ry"
115
+ return self.Operator(gateName,q,None,phi)
116
+
117
+
118
+
119
+ #measure operator class used in Mif and Qif
120
+ class MO(DMO):
121
+ def __init__(self,ql,vl):
122
+ self.MOql = ql
123
+ self.MOvl = vl
124
+ self.header = ""
125
+ bitList = self.MO(ql,vl)
126
+ self.bool = True
127
+
128
+ if len(vl) == 1:
129
+ for bit in bitList:
130
+ if bit.value != vl[0]:
131
+ self.bool = False
132
+ break
133
+ else:
134
+ for j in range(0,len(bitList)):
135
+ if bitList[j] != vl[j]:
136
+ self.bool = False
137
+ break
138
+
139
+
140
+ #this kind of measure is used in Mif;
141
+ #ql means the qubit list need be measured; and the vl stands for the target result of measurement
142
+ def MO(self,ql:list,vl:list):
143
+ if len(ql) != len(vl):
144
+ try:
145
+ raise CodeError("The element number of Qubit List should be same with Value List!")
146
+ except CodeError as ce:
147
+ info = get_curl_info()
148
+ funName = info[0]
149
+ line = info[1]
150
+ writeErrorMsg(ce,funName,line)
151
+ bitList = []
152
+ for q in ql:
153
+ bitList.append(M(q,False))
154
+
155
+ #construct the if statement
156
+ # ifstr = "if ("
157
+ # for i in range(0,len(ql)):
158
+ # c = str(ql[i].ids)
159
+ # tmp = "c[" + c + "]==" + str(vl[i])
160
+ # if i != len(ql)-1:
161
+ # tmp += " && "
162
+ # ifstr += tmp
163
+ # ifstr += "){}"
164
+ ifstr = ""
165
+ for v in vl:
166
+ ifstr += "M" + str(v) + "-"
167
+ self.header = ifstr
168
+
169
+ return bitList
170
+
171
+ def recordGate(self,gate:str,ql:list):
172
+ circuit = checkEnvironment()
173
+ maxL = 0
174
+ content = gate + " "
175
+ for i in range(0,len(ql)):
176
+ length = len(circuit.qubitExecuteList[ql[i]])
177
+ maxL = max(length,maxL)
178
+ content += str(ql[i].ids)
179
+ if i != len(ql)-1:
180
+ content += ','
181
+
182
+ for q in ql:
183
+ try:
184
+ while len(circuit.qubitExecuteList[q]) < maxL:
185
+ circuit.qubitExecuteList[q].append("NULL "+str(q.ids))
186
+ circuit.qubitExecuteList[q].append(content)
187
+ if circuit.withOD:
188
+ while len(circuit.qubitExecuteListOD[q]) < maxL:
189
+ circuit.qubitExecuteListOD[q].append("NULL "+str(q.ids))
190
+ circuit.qubitExecuteListOD[q].append(content)
191
+ except KeyError:
192
+ info = get_curl_info()
193
+ writeErrorMsg("Qubit: q" + str(q.ids) + " hasn't been stored in circuit.qubitExeucetList!\
194
+ " ,info[0],info[1])
195
+
196
+ # print(circuit.qubitExecuteList)
197
+ # print(circuit.qubitExecuteListOD)
198
+
199
+ #overwrite the operator method
200
+ def Operator(self,gateName:str,tq:Qubit,cq = None,angle = None):
201
+ if cq != None:
202
+ gateName = "c1-X"
203
+ fullGName = self.header + gateName
204
+
205
+ #no matter what's self.bool, record the Measure Operator in qubitExecuteList
206
+ if self.bool:
207
+ #if the last position of the full gate name is 1, then the gate is executed
208
+ fullGName += "1"
209
+ else:
210
+ #if the last position of the gate name is 0, then the gate isn't executed
211
+ fullGName += "0"
212
+ ql = self.MOql.copy()
213
+ if cq != None:
214
+ ql.append(cq)
215
+ ql.append(tq)
216
+ self.recordGate(fullGName,ql)
217
+
218
+ #execute the operator according to self.bool
219
+ if gateName == "c1-X":
220
+ gateName = "CNOT"
221
+ q = None
222
+ if self.bool:
223
+ #execute the gate function in Gate.py
224
+ if cq == None:
225
+ exeStr = "q = " + gateName + "(tq,False,True)"
226
+ else:
227
+ exeStr = "q = " + gateName + "(cq,tq,False,True)"
228
+ #print(exeStr)
229
+ exec(exeStr)
230
+ else:
231
+ #don't exeucte the gate
232
+ pass
233
+
234
+ return q
235
+
236
+ #the single gate operator and the double gate operator were inherited from DMO class
237
+ #def X
238
+ #def Y
239
+ #def Z
240
+ #def H
241
+ #def S
242
+ #def Sd
243
+ #def T
244
+ #def Td
245
+ #def CNOT
246
+ #def Rz
247
+ #def Ry
248
+ #def get_curl_info
249
+
250
+
251
+
252
+
253
+
254
+ #delay measure operator class used in Qwhile
255
+ class QWMO(DMO):
256
+ def __init__(self,ql,vl,angle):
257
+ DMO.__init__(ql,vl)
258
+ self.angle = angle
259
+
260
+ def end(self):
261
+ for q in ql:
262
+ Rx(angle,q)
263
+ if True:
264
+ return True
265
+ else:
266
+ return False
-QuQ--master/config/function.cfg ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {"fileName":"Grover","entryFunction":"grover()"}
2
+ {"fileName":"Teleportation","entryFunction":"teleportation()"}
3
+ {"fileName":"GroverLite","entryFunction":"groverLite()"}
4
+ {"fileName":"Test","entryFunction":"u()"}
5
+ {"fileName":"ExpWrong","entryFunction":"wrong()"}
6
+ {"fileName":"UserSWAP","entryFunction":"SWAP()"}
-QuQ--master/doc/Class-relation.docx ADDED
Binary file (22.6 kB). View file
 
-QuQ--master/results/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+
-QuQ--master/userCode/Teleportation.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+ #the flow of this algorithm is designed as follow:
3
+ #1.prepare the Bell state
4
+ #2.implement the algorithm according to Nielsen and L.Chuang
5
+ def teleportation():
6
+ c = Circuit(True)
7
+ #store the unknow quantum state, the aim of this algorithm is teleporting the state of AliceQ to BobQ
8
+ AliceQ = Qubit()
9
+ #the two qubit is entanglement with each other
10
+ AliceQ2 = Qubit()
11
+ BobQ = Qubit()
12
+ H(AliceQ2)
13
+ CNOT(AliceQ2,BobQ)
14
+ CNOT(AliceQ,AliceQ2)
15
+ H(AliceQ)
16
+ CNOT(AliceQ2,BobQ)
17
+ #######Control-Z#########
18
+ H(BobQ)
19
+ CNOT(AliceQ,BobQ)
20
+ H(BobQ)
21
+ #########################
22
+ BobQ = M(BobQ)
23
+ c.execute(1024)
0617-audio_stream-master/model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
0617-audio_stream-master/test.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from hyper import *
3
+ from model.CPD_models import CPD_VGG
4
+ from model.CPD_models import CPD_3DResNet
5
+ from dataset import *
6
+ import cv2
7
+ import torch
8
+ import torch.nn.functional as F
9
+
10
+ max = 600
11
+ name = 'model_cpd_250616_Adam_1e-05_20_BCEWithLogitsLoss_8.pth'
12
+ checkpoint = './checkpoint/cpd_0616/' + name
13
+ # checkpoint = './pre-trained/audio/model_cpd_300525_Adam_1.0000000000000002e-07_20_BCEWithLogitsLoss_29.pth'
14
+ # checkpoint = 'C:/Users/MSI-PC/Desktop/cpd_wrs_2.21_导入参数后效果很好/train_weight/vgg_dfh1k_cpd/vgg.pth.10'
15
+ model = CPD_3DResNet()
16
+ model.load_state_dict(torch.load(checkpoint))
17
+
18
+ print('\n', name, '\n')
19
+ '''
20
+ save_model = torch.load(checkpoint)
21
+ now_model = model.state_dict()
22
+ state_dict = {k: v for k, v in save_model.items() if k in now_model.keys()}
23
+ now_model.update(state_dict)
24
+ model.load_state_dict(now_model)
25
+ '''
26
+
27
+ model.cuda()
28
+ model.eval()
29
+
30
+ dir_num = 0
31
+ img_num = 0
32
+
33
+ for i in os.listdir(test_data_path):
34
+ test_frames = test_data_path + i + '/'
35
+ save_path = './test_result/' + checkpoint.split('/')[-1].split('.pth')[0] + '/' + i + '/'
36
+ if not os.path.exists(save_path):
37
+ os.makedirs(save_path)
38
+
39
+ test_loader = LoadTestData(test_frames)
40
+
41
+ for j in range(test_loader.size):
42
+ image, name, index = test_loader.load_data()
43
+
44
+ image = image.reshape(1, image.size(0), image.size(1), image.size(2))
45
+ image = image.cuda()
46
+
47
+ ress = model(image)
48
+ h = 256
49
+ w = 320
50
+
51
+ res = F.interpolate(ress, size=[h, w], mode='bilinear', align_corners=False)
52
+ res = res.sigmoid().data.cpu().numpy().squeeze()
53
+ res = (res - res.min()) / (res.max() - res.min() + 1e-8)
54
+ cv2.imwrite(save_path + name, res * 255)
55
+ img_num += 1
56
+ '''
57
+ if j == 150:
58
+ break
59
+ '''
60
+ print("===== {} finished !=====\n".format(i))
61
+ dir_num += 1
62
+ if dir_num == max:
63
+ exit(0)
64
+
65
+ print("Total test images == {} == !\n".format(img_num))
66
+
67
+
0621_test-master/django_app/post/apps.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class PostConfig(AppConfig):
5
+ name = 'post'
0621_test-master/django_app/post/models.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.auth.models import User
2
+ from django.db import models
3
+
4
+
5
+ class Post(models.Model):
6
+ author = User.objects.first()
7
+ comment = models.CharField(max_length=200)
8
+ created_date = models.DateTimeField(auto_now_add=True)
9
+ modify_date = models.DateTimeField(auto_now=True)
10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree3.go ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func maxDepth3(root *TreeNode) int {
4
+ if root == nil {
5
+ return 0
6
+ }
7
+ stack := []*TreeNode{root}
8
+ level := 0
9
+
10
+ for len(stack) > 0 {
11
+ num := len(stack)
12
+ for i := 0; i < num; i++ {
13
+ if stack[i].Left != nil {
14
+ stack = append(stack, stack[i].Left)
15
+ }
16
+ if stack[i].Right != nil {
17
+ stack = append(stack, stack[i].Right)
18
+ }
19
+ }
20
+ stack = stack[num:]
21
+ level++
22
+ }
23
+ return level
24
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/15/3sum.go ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "sort"
4
+
5
+ func threeSum(nums []int) [][]int {
6
+ sort.Ints(nums)
7
+ res := make([][]int, 0)
8
+ for i := 0; i < len(nums)-2; i++ {
9
+ if nums[i] > 0 {
10
+ break
11
+ }
12
+ if i > 0 && nums[i] == nums[i-1] {
13
+ continue
14
+ }
15
+ j, k := i+1, len(nums)-1
16
+ for j < k {
17
+ s := nums[i] + nums[j] + nums[k]
18
+ if s == 0 {
19
+ res = append(res, []int{nums[i], nums[j], nums[k]})
20
+ j++
21
+ k--
22
+ for j < k && nums[j] == nums[j-1] {
23
+ j++
24
+ }
25
+ for j < k && nums[k] == nums[k+1] {
26
+ k--
27
+ }
28
+ } else if s > 0 {
29
+ k--
30
+ for j < k && nums[k] == nums[k+1] {
31
+ k--
32
+ }
33
+ } else {
34
+ j++
35
+ for j < k && nums[j] == nums[j-1] {
36
+ j++
37
+ }
38
+ }
39
+ }
40
+ }
41
+ return res
42
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Solution:
2
+ def addDigits(self, num: int) -> int:
3
+ while num > 9:
4
+ s = 0
5
+ while num > 0:
6
+ s += num % 10
7
+ num //= 10
8
+ num = s
9
+ return num
10
+
11
+ def test(self):
12
+ for num, target in [
13
+ (0, 0),
14
+ (1, 1),
15
+ (9, 9),
16
+ (10, 1),
17
+ (11, 2),
18
+ (19, 1),
19
+ ]:
20
+ ans = self.addDigits(num)
21
+ assert ans == target, f"target: {target}, ans: {ans}"
22
+ print("well done")
23
+
24
+
25
+ if __name__ == "__main__":
26
+ Solution().test()
10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence2.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func lengthOfLIS2(nums []int) int {
4
+ tail := make([]int, 0)
5
+ for i := 0; i < len(nums); i++ {
6
+ if i == 0 || nums[i] > tail[len(tail)-1] {
7
+ tail = append(tail, nums[i])
8
+ } else {
9
+ left, right := 0, len(tail)
10
+ for left < right {
11
+ mid := (left + right) / 2
12
+ if tail[mid] < nums[i] {
13
+ left = mid + 1
14
+ } else {
15
+ right = mid
16
+ }
17
+ }
18
+ tail[left] = nums[i]
19
+ }
20
+ }
21
+ return len(tail)
22
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence_test.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ tests := []struct {
7
+ nums []int
8
+ target int
9
+ }{
10
+ {[]int{10, 9, 2, 5, 3, 7, 101, 18, 4, 8, 6, 12}, 5},
11
+ }
12
+
13
+ for _, tt := range tests {
14
+ if ans := lengthOfLIS2(tt.nums); ans != tt.target {
15
+ t.Fatalf("target: %d, ans: %d\n", tt.target, ans)
16
+ }
17
+ }
18
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/350/intersection_of_two_arrays_ii.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict
2
+ from collections import defaultdict
3
+
4
+
5
+ class Solution:
6
+ def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
7
+ counter: Dict[int, int] = defaultdict(int)
8
+ for n in nums1:
9
+ counter[n] += 1
10
+
11
+ res = []
12
+ for n in nums2:
13
+ if counter[n] > 0:
14
+ res.append(n)
15
+ counter[n] -= 1
16
+ return res
10-week-algorithm-excercise-master/OneQuestionPerDay/387/first_unique_character_in_a_string.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Solution:
2
+ def firstUniqChar(self, s: str) -> int:
3
+ arr = [0] * 26
4
+
5
+ for i, c in enumerate(s):
6
+ arr[ord(c) - ord('a')] = i
7
+
8
+ for i, c in enumerate(s):
9
+ if arr[ord(c) - ord('a')] == i:
10
+ return i
11
+ arr[ord(c) - ord('a')] = -1
12
+ return -1
10-week-algorithm-excercise-master/OneQuestionPerDay/412/fizz_buzz.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "strconv"
4
+
5
+ func fizzBuzz(n int) []string {
6
+ res := make([]string, n)
7
+ for i := 1; i <= n; i++ {
8
+ if i%15 == 0 {
9
+ res[i-1] = "FizzBuzz"
10
+ } else if i%5 == 0 {
11
+ res[i-1] = "Buzz"
12
+ } else if i%3 == 0 {
13
+ res[i-1] = "Fizz"
14
+ } else {
15
+ res[i-1] = strconv.Itoa(i)
16
+ }
17
+ }
18
+ return res
19
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray.go ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func findLength(A []int, B []int) int {
4
+ m, n := len(A), len(B)
5
+ if m == 0 || n == 0 {
6
+ return 0
7
+ }
8
+ dp := make([][]int, m+1)
9
+ for i := 0; i < m; i++ {
10
+ dp[i] = make([]int, n+1)
11
+ }
12
+ res := 0
13
+ for i := 0; i < m; i++ {
14
+ for j := 0; j < n; j++ {
15
+ if A[i] == B[j] {
16
+ dp[i+1][j+1] = dp[i][j] + 1
17
+ res = max(res, dp[i+1][j+1])
18
+ }
19
+ }
20
+ }
21
+ return res
22
+ }
23
+
24
+ func max(x, y int) int {
25
+ if x > y {
26
+ return x
27
+ }
28
+ return y
29
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray2.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def findLength(self, A: List[int], B: List[int]) -> int:
6
+ def maxLength(addA: int, addB: int, length: int) -> int:
7
+ ret = k = 0
8
+ for i in range(length):
9
+ if A[addA + i] == B[addB + i]:
10
+ k += 1
11
+ ret = max(ret, k)
12
+ else:
13
+ k = 0
14
+ return ret
15
+
16
+ n, m = len(A), len(B)
17
+ ret = 0
18
+ for i in range(n):
19
+ length = min(m, n - i)
20
+ ret = max(ret, maxLength(i, 0, length))
21
+ for i in range(m):
22
+ length = min(n, m - i)
23
+ ret = max(ret, maxLength(0, i, length))
24
+ return ret
25
+
26
+ def test(self):
27
+ a = [1, 2, 3, 2, 1]
28
+ b = [3, 2, 1, 4, 7]
29
+ ans = self.findLength(a, b)
30
+ print(ans)
31
+
32
+
33
+ if __name__ == "__main__":
34
+ Solution().test()
10-week-algorithm-excercise-master/OneQuestionPerDay/83/remove_duplicates_from_sorted_list.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Definition for singly-linked list.
2
+ class ListNode:
3
+ def __init__(self, x):
4
+ self.val = x
5
+ self.next = None
6
+
7
+
8
+ class Solution:
9
+ def deleteDuplicates(self, head: ListNode) -> ListNode:
10
+ if head is None:
11
+ return head
12
+ elments = {head.val}
13
+ prev, cur = head, head.next
14
+ while cur is not None:
15
+ if cur.val not in elments:
16
+ elments.add(cur.val)
17
+ prev, cur = cur, cur.next
18
+ else:
19
+ prev.next = cur.next
20
+ cur = cur.next
21
+ return head
10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Solution:
2
+ def getKthMagicNumber(self, k: int) -> int:
3
+ dp = [1] * k
4
+ p3 = p5 = p7 = 0
5
+
6
+ for i in range(1, k):
7
+ f3 = 3 * dp[p3]
8
+ f5 = 5 * dp[p5]
9
+ f7 = 7 * dp[p7]
10
+ dp[i] = min(f3, f5, f7)
11
+ if f3 == dp[i]:
12
+ p3 += 1
13
+ if f5 == dp[i]:
14
+ p5 += 1
15
+ if f7 == dp[i]:
16
+ p7 += 1
17
+ return dp[k - 1]
10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number_test.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ tests := []struct {
7
+ k int
8
+ target int
9
+ }{
10
+ {1, 1},
11
+ {5, 9},
12
+ }
13
+
14
+ for _, tt := range tests {
15
+ if ans := getKthMagicNumber2(tt.k); ans != tt.target {
16
+ t.Fatalf("target: %d, ans: %d\n", tt.target, ans)
17
+ }
18
+ }
19
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ class Solution:
2
+ def replaceSpace(self, s: str) -> str:
3
+ res = []
4
+ for c in s:
5
+ if c == " ":
6
+ res.append("%20")
7
+ else:
8
+ res.append(c)
9
+ return "".join(res)
10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF59/max_sliding_window.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func maxSlidingWindow(nums []int, k int) []int {
4
+ var window, res []int
5
+ for i := 0; i < len(nums); i++ {
6
+ if len(window) > 0 && window[0] <= i-k {
7
+ window = window[1:]
8
+ }
9
+ for len(window) > 0 && nums[window[len(window)-1]] < nums[i] {
10
+ window = window[:len(window)-1]
11
+ }
12
+ window = append(window, i)
13
+ if i >= k-1 {
14
+ res = append(res, nums[window[0]])
15
+ }
16
+ }
17
+ return res
18
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF6/reverse_link_node.go ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type ListNode struct {
4
+ Val int
5
+ Next *ListNode
6
+ }
7
+
8
+ func reversePrint(head *ListNode) []int {
9
+ var res []int
10
+
11
+ for head != nil {
12
+ res = append(res, head.Val)
13
+ head = head.Next
14
+ }
15
+
16
+ for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
17
+ res[i], res[j] = res[j], res[i]
18
+ }
19
+ return res
20
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF6/reverse_link_node.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class ListNode:
5
+ def __init__(self, x):
6
+ self.val = x
7
+ self.next = None
8
+
9
+
10
+ class Solution:
11
+ def reversePrint(self, head: ListNode) -> List[int]:
12
+ res = []
13
+
14
+ while head is not None:
15
+ res.append(head.val)
16
+ head = head.next
17
+ return res[::-1]
10-week-algorithm-excercise-master/Week_01/1/two_sum.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def twoSum(self, nums: List[int], target: int) -> List[int]:
6
+ cache = {}
7
+ for i, n in enumerate(nums):
8
+ m = target - n
9
+ if m in cache:
10
+ return [cache[m], i]
11
+ cache[n] = i
12
+ return []
10-week-algorithm-excercise-master/Week_01/11/container_with_most_water.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func maxArea(height []int) int {
4
+ i, j, res, v := 0, len(height)-1, 0, 0
5
+ for i < j {
6
+ if height[i] <= height[j] {
7
+ v = height[i] * (j - i)
8
+ i++
9
+ } else {
10
+ v = height[j] * (j - i)
11
+ j--
12
+ }
13
+ if v > res {
14
+ res = v
15
+ }
16
+ }
17
+ return res
18
+ }
10-week-algorithm-excercise-master/Week_01/11/container_with_most_water_test.go ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ tests := []struct {
7
+ heights []int
8
+ target int
9
+ }{
10
+ {[]int{1, 1, 1, 1}, 3},
11
+ {[]int{1, 1}, 1},
12
+ {[]int{1, 8, 6, 2, 5, 4, 8, 3, 7}, 49},
13
+ }
14
+
15
+ for _, tt := range tests {
16
+ if ans := maxArea(tt.heights); ans != tt.target {
17
+ t.Fatalf("target : %d, ans: %d\n", tt.target, ans)
18
+ }
19
+ }
20
+ }
10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type ListNode struct {
4
+ Val int
5
+ Next *ListNode
6
+ }
7
+
8
+ func hasCycle0(head *ListNode) bool {
9
+ seen := make(map[*ListNode]bool)
10
+ for head != nil {
11
+ if seen[head] {
12
+ return true
13
+ } else {
14
+ seen[head] = true
15
+ }
16
+ head = head.Next
17
+ }
18
+ return false
19
+ }
10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle3.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+
4
+ func hasCycle3(head *ListNode) bool {
5
+ if head == nil {
6
+ return false
7
+ }
8
+ prev, cur := head, head.Next
9
+ for cur != nil {
10
+ if cur == head {
11
+ return true
12
+ }
13
+ next := cur.Next
14
+ cur.Next = prev
15
+ prev = cur
16
+ cur = next
17
+ }
18
+ return false
19
+ }
10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type ListNode struct {
4
+ Val int
5
+ Next *ListNode
6
+ }
7
+
8
+ func detectCycle(head *ListNode) *ListNode {
9
+ slow := head
10
+ fast := head
11
+ for {
12
+ if fast == nil || fast.Next == nil {
13
+ return nil
14
+ }
15
+ fast = fast.Next.Next
16
+ slow = slow.Next
17
+ if fast == slow {
18
+ break
19
+ }
20
+ }
21
+ fast = head
22
+ for fast != slow {
23
+ fast = fast.Next
24
+ slow = slow.Next
25
+ }
26
+ return fast
27
+ }
10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ListNode:
2
+ def __init__(self, x):
3
+ self.val = x
4
+ self.next = None
5
+
6
+
7
+ class Solution:
8
+ def detectCycle(self, head: ListNode) -> ListNode:
9
+ fast = slow = head
10
+ while True:
11
+ if fast is None or fast.next is None:
12
+ return None
13
+ fast = fast.next.next
14
+ slow = slow.next
15
+ if fast is slow:
16
+ break
17
+ fast = head
18
+
19
+ while fast is not slow:
20
+ fast = fast.next
21
+ slow = slow.next
22
+ return fast
10-week-algorithm-excercise-master/Week_01/15/3sum.go ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "sort"
4
+
5
+ type Element struct {
6
+ a, b, c int
7
+ }
8
+
9
+ func threeSum(nums []int) [][]int {
10
+ sort.Ints(nums)
11
+ var ret [][]int
12
+ elements := make(map[Element]bool)
13
+
14
+ for i := 0; i < len(nums)-2; i++ {
15
+ a := nums[i]
16
+ cache := map[int]int{}
17
+ for j := i + 1; j < len(nums); j++ {
18
+ c := nums[j]
19
+ b := - a - c
20
+ if _, ok := cache[b]; ok {
21
+ elements[Element{a, b, c}] = true
22
+ } else {
23
+ cache[c] = 1
24
+ }
25
+ }
26
+ }
27
+ for e := range elements {
28
+ ret = append(ret, []int{e.a, e.b, e.c})
29
+ }
30
+ return ret
31
+ }
10-week-algorithm-excercise-master/Week_01/15/3sum_test.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "reflect"
5
+ "testing"
6
+ )
7
+
8
+ func Test(t *testing.T) {
9
+ tests := []struct {
10
+ nums []int
11
+ target [][]int
12
+ }{
13
+ {[]int{1,-1,-1,0}, [][]int{{-1,0,1}}},
14
+ {[]int{-1,0,1,2,-1,-4}, [][]int{{-1,-1,2},{-1,0,1}}},
15
+ }
16
+
17
+ for _, tt := range tests {
18
+ if ans := threeSum2(tt.nums); !reflect.DeepEqual(ans, tt.target) {
19
+ t.Fatalf("target: %v, ans %v\n", tt.target, ans)
20
+ }
21
+ }
22
+ }
10-week-algorithm-excercise-master/Week_01/155/min_stack.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class MinStack:
2
+
3
+ def __init__(self):
4
+ """
5
+ initialize your data structure here.
6
+ """
7
+ self.stack = []
8
+ self.min_stack = []
9
+
10
+ def push(self, x: int) -> None:
11
+ self.stack.append(x)
12
+ if len(self.min_stack) == 0 or self.min_stack[-1] >= x:
13
+ self.min_stack.append(x)
14
+
15
+ def pop(self) -> None:
16
+ v = self.stack.pop()
17
+ if v == self.min_stack[-1]:
18
+ self.min_stack.pop()
19
+
20
+ def top(self) -> int:
21
+ return self.stack[-1]
22
+
23
+ def getMin(self) -> int:
24
+ return self.min_stack[-1]
10-week-algorithm-excercise-master/Week_01/189/rotate_array.go ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func rotate1(nums []int, k int) {
4
+ if len(nums) < 2 || len(nums) == k {
5
+ return
6
+ }
7
+ for i := 0; i < k; i++ {
8
+ tail := nums[len(nums)-1]
9
+ copy(nums[1:], nums[0:len(nums)-1])
10
+ nums[0] = tail
11
+ }
12
+ }
10-week-algorithm-excercise-master/Week_01/189/rotate_array_test.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "reflect"
5
+ "testing"
6
+ )
7
+
8
+ func Test(t *testing.T) {
9
+ tests := []struct {
10
+ nums []int
11
+ k int
12
+ target []int
13
+ }{
14
+ {[]int{1}, 0, []int{1}},
15
+ {[]int{1, 2}, 1, []int{2, 1}},
16
+ {[]int{1, 2, 3, 4, 5}, 2, []int{4, 5, 1, 2, 3}},
17
+ {[]int{1, 2, 3, 4, 5}, 3, []int{3, 4, 5, 1, 2}},
18
+ }
19
+
20
+ for _, tt := range tests {
21
+ if rotate(tt.nums, tt.k); !reflect.DeepEqual(tt.nums, tt.target) {
22
+ t.Fatalf("target %v, got %v\n", tt.target, tt.nums)
23
+ }
24
+ }
25
+ }
10-week-algorithm-excercise-master/Week_01/20/valid_parentheses.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func isValid(s string) bool {
4
+ mapping := map[byte]byte{
5
+ ')': '(',
6
+ '}': '{',
7
+ ']': '[',
8
+ }
9
+ stack := make([]byte, 0)
10
+ for i := 0; i < len(s); i++ {
11
+ if v, ok := mapping[s[i]]; !ok {
12
+ stack = append(stack, s[i])
13
+ } else {
14
+ if len(stack) == 0 || stack[len(stack)-1] != v {
15
+ return false
16
+ } else {
17
+ stack = stack[:len(stack)-1]
18
+ }
19
+ }
20
+ }
21
+
22
+ return len(stack) == 0
23
+ }
10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list.go ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func reverseList0(head *ListNode) *ListNode {
4
+ if head == nil {
5
+ return head
6
+ }
7
+ headNew := head
8
+ for head.Next != nil {
9
+ next := head.Next
10
+ head.Next, next.Next = next.Next, headNew
11
+ headNew = next
12
+ }
13
+ return headNew
14
+ }
10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists.go ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type ListNode struct {
4
+ Val int
5
+ Next *ListNode
6
+ }
7
+
8
+ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
9
+ dummy := &ListNode{}
10
+ cur := dummy
11
+ for l1 != nil && l2 != nil {
12
+ if l1.Val < l2.Val {
13
+ cur.Next = l1
14
+ l1 = l1.Next
15
+ } else {
16
+ cur.Next = l2
17
+ l2 = l2.Next
18
+ }
19
+ cur = cur.Next
20
+ }
21
+
22
+ if l1 != nil {
23
+ cur.Next = l1
24
+ } else {
25
+ cur.Next = l2
26
+ }
27
+ return dummy.Next
28
+ }
10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from collections import deque
3
+
4
+
5
+ class Solution:
6
+ def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
7
+ dq = deque()
8
+ res = []
9
+ for i, n in enumerate(nums):
10
+ while dq and dq[0] <= i - k:
11
+ dq.popleft()
12
+ while dq and nums[dq[-1]] < n:
13
+ dq.pop()
14
+ dq.append(i)
15
+ if i >= k - 1:
16
+ res.append(nums[dq[0]])
17
+ return res
18
+
19
+ def test(self):
20
+ for nums, k, target in [
21
+ ([], 3, []),
22
+ ([1, 2], 1, [1, 2]),
23
+ ([1, 3, -1, -3, 5, 3, 6, 7], 3, [3, 3, 5, 5, 6, 7]),
24
+ ]:
25
+ ans = self.maxSlidingWindow(nums, k)
26
+ assert ans == target, f"target: {target}, ans: {ans}"
27
+ print("all done")
28
+
29
+
30
+ if __name__ == "__main__":
31
+ Solution().test()
10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs2.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ListNode:
2
+ def __init__(self, x):
3
+ self.val = x
4
+ self.next = None
5
+
6
+ def __repr__(self):
7
+ return f"[Node]{self.val}"
8
+
9
+
10
+ class Solution:
11
+ def swapPairs(self, head: ListNode) -> ListNode:
12
+ dummy = ListNode(0)
13
+ dummy.next = head
14
+ prev = dummy
15
+
16
+ while head is not None and head.next is not None:
17
+ prev.next = head.next
18
+ prev = head
19
+ head.next.next, head.next = head, head.next.next
20
+ head = head.next
21
+ return dummy.next
22
+
23
+ def test(self):
24
+ node1 = ListNode(1)
25
+ node2 = ListNode(2)
26
+ node3 = ListNode(3)
27
+ node4 = ListNode(4)
28
+
29
+ node2.next = node1
30
+ node3.next = node2
31
+ node4.next = node3
32
+
33
+ ans = self.swapPairs(node1)
34
+ assert ans == node1
35
+
36
+ ans = self.swapPairs(node2)
37
+ assert ans == node1
38
+ #
39
+ ans = self.swapPairs(node1)
40
+ assert ans == node2
41
+
42
+ ans = self.swapPairs(node4)
43
+ assert ans == node3
44
+
45
+ print("success")
46
+
47
+
48
+ if __name__ == "__main__":
49
+ Solution().test()
50
+
51
+
10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type ListNode struct {
4
+ Val int
5
+ Next *ListNode
6
+ }
7
+
8
+ func reverseKGroup(head *ListNode, k int) *ListNode {
9
+ dummy := &ListNode{Next: head}
10
+ prev := dummy
11
+ slow, fast := head, head
12
+ for {
13
+ cnt := 1
14
+ for fast != nil && cnt < k {
15
+ fast = fast.Next
16
+ cnt++
17
+ }
18
+ if fast == nil {
19
+ break
20
+ }
21
+ prev.Next = fast
22
+ prev = slow
23
+ next := slow.Next
24
+ prev.Next = fast.Next
25
+
26
+ for next != prev.Next {
27
+ next, next.Next, slow = next.Next, slow, next
28
+ }
29
+ slow = prev.Next
30
+ fast = prev.Next
31
+ }
32
+ return dummy.Next
33
+ }
10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array_test.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ tests := []struct {
7
+ nums []int
8
+ target int
9
+ }{
10
+ {[]int{}, 0},
11
+ {[]int{1, 1}, 1},
12
+ {[]int{1, 1, 2}, 2},
13
+ {[]int{0,1,1,1,2,2,3,3,4}, 5},
14
+ }
15
+
16
+ for _, tt := range tests {
17
+ if ans := removeDuplicates(tt.nums); ans != tt.target {
18
+ t.Fatalf("target: %d, ans: %d\n", tt.target, ans)
19
+ }
20
+ }
21
+ }
10-week-algorithm-excercise-master/Week_01/283/move_zeros_test.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "reflect"
5
+ "testing"
6
+ )
7
+
8
+ func Test(t *testing.T) {
9
+ tests := []struct {
10
+ nums []int
11
+ target []int
12
+ }{
13
+ {[]int{1, 2, 0}, []int{1, 2, 0}},
14
+ {[]int{1, 0, 0}, []int{1, 0, 0}},
15
+ {[]int{1, 0, 0, 2, 0}, []int{1, 2, 0, 0, 0}},
16
+ }
17
+
18
+ for _, tt := range tests {
19
+ if moveZeroes(tt.nums); !reflect.DeepEqual(tt.nums, tt.target) {
20
+ t.Fatalf("target: %v, nums: %v\n", tt.target, tt.nums)
21
+ }
22
+ }
23
+ }
10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func trap(height []int) int {
4
+ stack := make([]int, 0)
5
+ res := 0
6
+
7
+ for i, h := range height {
8
+ for len(stack) > 0 && height[stack[len(stack)-1]] < h {
9
+ top := stack[len(stack)-1]
10
+ stack = stack[:len(stack)-1]
11
+ if len(stack) == 0 {
12
+ break
13
+ }
14
+ left := stack[len(stack)-1]
15
+ res += (i - left - 1) * (min(h, height[left]) - height[top])
16
+ }
17
+ stack = append(stack, i)
18
+ }
19
+ return res
20
+ }
21
+
22
+ func min(x, y int) int {
23
+ if x < y {
24
+ return x
25
+ }
26
+ return y
27
+ }
10-week-algorithm-excercise-master/Week_01/README.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 学习笔记
2
+
3
+
4
+ |#|Title|Solutions|
5
+ |---|---|------|
6
+ |70|[climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs) | 递推([Go](70/climbing_stairs.go),[Py](70/climbing_stairs.py))|
7
+ |11|[container-with-most-water](https://leetcode-cn.com/problems/container-with-most-water) | 双指针([Go](11/container_with_most_water.go),[Py](11/container_with_most_water.py))|
8
+ |283|[move-zeroes](https://leetcode-cn.com/problems/move-zeroes)| 统计0的个数([Go](283/move_zeros.go),[Py](283/move_zeros.py)), 快慢指针([Go](283/move_zeros.go))|
9
+ |1|[two-sum](https://leetcode-cn.com/problems/two-sum)| 先排序后双指针夹逼([Go](1/two_sum.go)), 字典缓存差值的索引([Go](1/two_sum_2.go),[Py](1/two_sum.py))|
10
+ |15|[3sum](https://leetcode-cn.com/problems/3sum)| 先排序后双指针夹逼([Go](15/3sum_2.go),[Py](15/3sum.py)), 字典缓存差值的索引([Go](15/3sum.go))|
11
+ |206|[reverse-linked-list](https://leetcode-cn.com/problems/reverse-linked-list)| 迭代([Go](206/reverse_linked_list.go),[Py](206/reverse_linked_list.py)), 递归([Go](206/reverse_linked_list2.go),[Py](206/reverse_linked_list2.py))|
12
+ |24|[swap-nodes-in-pairs](https://leetcode-cn.com/problems/swap-nodes-in-pairs)| 迭代([Go](24/swap_nodes_in_pairs2.go),[Py](24/swap_nodes_in_pairs2.py)), 递归([Go](24/swap_nodes_in_pairs.go),[Py](24/swap_nodes_in_pairs.py))|
13
+ |21|[merge-two-sorted-lists](https://leetcode-cn.com/problems/merge-two-sorted-lists) | 迭代([Go](21/merge_two_sorted_lists.go), [Py](21/merge_two_sorted_lists.py)), 递归([Go](21/merge_two_sorted_lists2.go),[Py](21/merge_two_sorted_lists2.py))|
14
+ |141|[linked-list-cycle](https://leetcode-cn.com/problems/linked-list-cycle) | 哈希([Go](141/linked_list_cycle.go), [Py](141/linked_list_cycle.py)), 快慢指针([Go](141/linked_list_cycle2.go),[Py](141/linked_list_cycle2.py)), 翻转链表([Go](141/linked_list_cycle3.go))|
15
+ |142|[linked-list-cycle-ii](https://leetcode-cn.com/problems/linked-list-cycle-ii) | 快慢指针([Go](142/linked_list_cycle_ii.go), [Py](142/linked_list_cycle_ii.py))|
16
+ |25|[reverse-nodes-in-k-group](https://leetcode-cn.com/problems/reverse-nodes-in-k-group) | 快慢指针([Go](25/reverse_nodes_in_k_group.go), [Py](25/reverse_nodes_in_k_group.py))|
17
+ |20|[valid-parentheses](https://leetcode-cn.com/problems/valid-parentheses) | 栈([Go](20/valid_parentheses.go), [Py](20/valid_parentheses.py))|
18
+ |155|[min-stack](https://leetcode-cn.com/problems/min-stack) | 双栈([Go](155/min_stack.go), [Py](155/min_stack.py))|
19
+ |84|[largest-rectangle-in-histogram](https://leetcode-cn.com/problems/largest-rectangle-in-histogram) | 暴力法([Go](84/largest_rectangle_in_histogram.go)),暴力法优化([Go](84/largest_rectangle_in_histogram2.go)),单调栈([Go](84/largest_rectangle_in_histogram3.go), [Py](84/largest_rectangle_in_histogram3.py))|
20
+ |239|[sliding-window-maximum](https://leetcode-cn.com/problems/sliding-window-maximum) | 单调递减队列([Go](239/sliding_window_maximum.go), [Py](239/sliding_window_maximum.py))|
21
+ |641|[design-circular-deque](https://leetcode-cn.com/problems/design-circular-deque) | 双指针([Go](641/design_circular_deque.go)),双指针优化([Go](641/design_circular_deque2.go),[Py](641/design_circular_deque2.py))|
22
+ |42|[trapping-rain-water](https://leetcode-cn.com/problems/trapping-rain-water) | 单调栈([Go](42/trapping_rain_water.go),[Py](42/trapping_rain_water.py))|
23
+ |26|[remove-duplicates-from-sorted-array](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array) | 快慢指针([Go](26/remove_duplicates_from_sorted_array.go),[Py](26/remove_duplicates_from_sorted_array.py))|
24
+ |189|[rotate-array](https://leetcode-cn.com/problems/rotate-array) | 暴力法([Go](189/rotate_array.go)), 三次翻转([Go](189/rotate_array2.go),[Py](189/rotate_array2.py))|
25
+ |88|[merge-sorted-array](https://leetcode-cn.com/problems/merge-sorted-array) | 暴力法([Go](88/merge_sorted_array.go)), 双指针从后向前([Go](88/merge_sorted_array2.go),[Py](88/merge_sorted_array2.py))|
26
+
27
+
28
+
29
+ ## 题解
30
+
31
+ ### 11. Container With Most Water
32
+
33
+ 1. 暴力法:两层for循环
34
+ 2. 双指针:缩减搜索空间
35
+ 对于i,j(i < j),如果h[i] <= h[j],那么任意的j1(i < j1 < j),必定会有h[i] * (j1 -i) < h[i] * (j-i)
36
+
37
+
38
+ ### 283. move-zeroes
39
+
40
+ 1. 统计0的个数,遇到非0时 nums[i-count] = nums[i]
41
+ 2. 慢指针指向非0元素
42
+
43
+ ### 1. two-sum
44
+
45
+ 计算差值是否在字典里,如果是则已找到,否则将当前值存入字典
46
+
47
+ ### 15. 3sum
48
+
49
+ 先排序,然后快慢指指针夹逼,另外要注意去重
50
+
51
+
52
+ ### 206. reverse linked list
53
+
54
+ 1. 迭代法:使用一个指正指向最新的head
55
+ 2. 递归法:比较难以理解,`head.next.next = head; head.next = None`
56
+
57
+ ### 24. swap-nodes-in-pairs
58
+
59
+ 1. 迭代法:构造一个dummy node 当前置节点
60
+ 2. 递归法
61
+
62
+ ### 21. merge-two-sorted-lists
63
+
64
+ 1. 迭代法: 构造一个dummy node 当前置节点
65
+ 2. 递归法
66
+
67
+
68
+ ### 141. linked-list-cycle
69
+
70
+ 1. 哈希表法: 用哈希表记录是否访问过
71
+ 2. 双指针法: 慢指针一次走一步,快指针一次走两步,如果没环,快指针会先指向nil
72
+ 3. 翻转链表法: 每走一步,将Next之前前置节点,如果有环,会重新回到head节点
73
+
74
+ ### 142. linked-list-cycle-ii
75
+
76
+ 快慢指针法:
77
+ - 假设环入口长度为a,环长度为b;则走a+ n * b步时在环入口处
78
+ - 第一次相遇时慢指针走的不步数s=nb(f == 2 * s == s + nb);
79
+ - 慢指指针再走a步即可到达环入口,让快指针按步长为1从head和slow同步移动,则再次相遇时即走了a步
80
+
81
+
82
+ ### 25. reverse-nodes-in-k-group
83
+
84
+ 快慢指针法:
85
+ - 快指针先试探能否走k步
86
+ - 若能依次翻转
87
+ - 从快指针的next继续下一轮
88
+
89
+
90
+ ### 20. valid-parentheses
91
+
92
+ 哈希表存映射,栈存左括号
93
+
94
+ ### 155. min stack
95
+
96
+ 双栈法:给最小值也建个栈
97
+
98
+ ### 84. largest-rectangle-in-histogram
99
+
100
+ 1. 暴力法: 以每个bar为高度基准,找到左右边界
101
+ 2. 暴力法优化: 左边界在height[i] <= height[i-1]时 bounder[i] = bounder[i-1],右边界同理
102
+ 3. 单调栈: 栈存每个bar的索引,如果新的bar height < heights[stack[-1]]时需要出栈
103
+
104
+
105
+ ### 239. sliding-window-maximum
106
+ 队列法:
107
+ - 移除旧窗口的元素
108
+ - 移除当前窗口比新元素小的
109
+ - 新元素入队
110
+ - 更新最大窗口集
111
+
112
+ ### 641. design-circular-dequeue
113
+
114
+ 1. 双指针:建立大小为k的数据,头尾指针都指向当前插入数据的位置,并用len记录当前长度以判断是否空或满
115
+ 2. 双指针优化: 为了避免头尾指针在空队列时候的耦合,让头指针指向头元素
116
+
117
+ ### 42. trapping rain water
118
+
119
+ 单调栈: 栈存每个bar的索引,如果新的bar height > heights[stack[-1]]时需要出栈
120
+
121
+
122
+ ### 26. remove-duplicates-from-sorted-array
123
+
124
+ 快慢指针: 快指针遍历,慢指针记录当前最新不重复的数的位置,关键是如何写的优雅
125
+
126
+
127
+ ### 189. rotate-array
128
+
129
+ 1. 暴力法: 每次移动最后一个元素到队首,移动k次
130
+ 2. 三次翻转法: 先全部翻转,再翻转[0,k-1], [k, len(nums)-1]
131
+
132
+ ### 88. merge-sorted-array
133
+
134
+ 1. 暴力法: 逐个加入nums2, 插入时整体copy nums1后移
135
+ 2. 双指针法:从后向前比较num1和nums2