diff --git a/-Api_avec_python-master/.pipreqs/requirements_pipreqs.txt b/-Api_avec_python-master/.pipreqs/requirements_pipreqs.txt new file mode 100644 index 0000000000000000000000000000000000000000..f56f3fa8daeff00d4ca205e0489139748411c20c --- /dev/null +++ b/-Api_avec_python-master/.pipreqs/requirements_pipreqs.txt @@ -0,0 +1 @@ +Requests==2.32.3 diff --git a/-Api_avec_python-master/Api.py b/-Api_avec_python-master/Api.py new file mode 100644 index 0000000000000000000000000000000000000000..c492990ca90d64297e8eaaf8ef98263837300ae8 --- /dev/null +++ b/-Api_avec_python-master/Api.py @@ -0,0 +1,35 @@ +########### +# IMPORTS # +########### + +import requests + +# url va me servir de changer de page dans la boucle while +url = "https://swapi.co/api/people/" + +# Quand il n'y a plus de "page suivante", la page "next" sera egale a None +# Donc, je boucle sur url tant qu'elle n'est egale a None :) +while url is not None: + print("") + + ############################ + # RÉCUPÉRATION DES DONNÉES # + ############################ + + # Je fais la requête sur la page en cours, et je recupere la data + r = requests.get(url) + data = r.json() + + # C'est ici que je change l'url pour avoir la page d'apres :) + url = data["next"] + # Ce tableau est la liste de tous les personnages + persosTab = data["results"] + + ########################### + # UTILISATION DES DONNÉES # + ########################### + + # Je fais ensuite une boucle qui parcourt tous les personnages + # et qui affiche leur nom ! + for perso in persosTab: + print(perso["name"]) \ No newline at end of file diff --git a/-Api_avec_python-master/README.md b/-Api_avec_python-master/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c34cde763e76b5c6905f4b6b4befad6fe7e3fd75 --- /dev/null +++ b/-Api_avec_python-master/README.md @@ -0,0 +1,2 @@ +# -Api_avec_python +Différente Api avec python diff --git a/-QuQ--master/.gitignore b/-QuQ--master/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7bbc71c09205c78d790739d246bbe4f9f1881c17 --- /dev/null +++ b/-QuQ--master/.gitignore @@ -0,0 +1,101 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ diff --git a/-QuQ--master/.pipreqs/requirements_pipreqs.txt b/-QuQ--master/.pipreqs/requirements_pipreqs.txt new file mode 100644 index 0000000000000000000000000000000000000000..d448a369a6d8af062d12fbe77d6576e64320bebf --- /dev/null +++ b/-QuQ--master/.pipreqs/requirements_pipreqs.txt @@ -0,0 +1,4 @@ +IBMQuantumExperience==2.0.4 +matplotlib==3.10.1 +numpy==2.2.4 +psutil==7.0.0 diff --git a/-QuQ--master/baseClass/ControlFlow.py b/-QuQ--master/baseClass/ControlFlow.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7b767db8dab7018df9a134125d7701f70c88ed --- /dev/null +++ b/-QuQ--master/baseClass/ControlFlow.py @@ -0,0 +1,72 @@ +from baseCF import * +from Gate import * +from Circuit import * +from DMO import DMO,MO,QWMO + +#a single qubit can be used as the guard; +#if there is more the one qubit in the guard, you should pass these qubits as a list +#if the values list has only one element, the value of all the qubits should be same with the value of the element; +#otherwise the length of the values list should be same with the length of the qubits list +# class Qif(ControlFlow): +# def __init__(self,q,v): +# ControlFlow.__init__(self,q,v) +# #this function is quantum teleportation quantum if +# def __enter__(self): +# resList = [] +# for q in self.ql: +# q1 = Qubit(True) +# q2 = Qubit(True) +# H(q1,False) +# CNOT(q1,q2,False) +# CNOT(q,q1,False) +# H(q,False) +# CNOT(q1,q2,False) +# H(q2,False) +# CNOT(q,q2,False) +# H(q2,False) +# # #restore the state of the Qubit "q" +# # H(q,False) +# #destory the auxiliary qubits "q1" and "q2" +# q2 = M(q2,False) +# q1 = M(q1,False) +# resList.append(q2.value) +# if len(self.vl) == 1: +# for r in resList: +# if r != self.vl[0]: +# return False +# else: +# for i in range(0,len(resList)): +# if resList[i] != self.vl[i]: +# return False +# return True + +#in the following two methods, the qubit used as the guard can't be appeared in the executive body. +class DMif(ControlFlow): + def __init__(self,q,v): + ControlFlow.__init__(self,q,v) + + #this function is delay measure-based quantum if + def __enter__(self): + dmo = DMO(self.ql,self.vl) + return dmo + def __exit__(self,a,b,c): + return True + +class Mif(ControlFlow): + def __init__(self,q,v): + ControlFlow.__init__(self,q,v) + #this function is measure-based quantum if + def __enter__(self): + mo = MO(self.ql,self.vl) + #mo.bool stands for the control guard + return mo + + +class Qwhile(ControlFlow): + def __init__(self,q,v,angle): + ControlFlow.__init__(self,q,v) + self.angle = angle + #this function is delay measure-based quantum while + def __enter__(self): + qw = QWMO(self.ql,self.vl,self.angle) + return qw \ No newline at end of file diff --git a/-QuQ--master/baseClass/Qubit.py b/-QuQ--master/baseClass/Qubit.py new file mode 100644 index 0000000000000000000000000000000000000000..042b11118d9ccdcc65a97978045d0bbbcb9a55fb --- /dev/null +++ b/-QuQ--master/baseClass/Qubit.py @@ -0,0 +1,374 @@ +#!/usr/bin/python3 +from baseQubit import BaseQubit +import sys +sys.path.append('../tools/') +import interactCfg +import math +#from Circuit import Circuit +from Error import * +from Bit import Bit +import random +import copy + +#get the info about the function name and the line number +def get_curl_info(): + try: + raise Exception + except: + f = sys.exc_info()[2].tb_frame.f_back + return [f.f_code.co_name, f.f_lineno] + +#the init state of the qubit must be |0> +class Qubit(BaseQubit): + #mode is an argument of the class, so that all the qubit can have the same execution mode + mode = interactCfg.readCfgEM() + #use the list to store the ids, so that ID won't repeat + idList = [] + #figure out the number of the Qubit in , and the value of the parameter can only increase + totalNum = 0 + #the physical process of "preparation" is described as this function + #mode='theory' or 'simulator', the user manual introduce details of the arguments + + #if the parameter "tag" is set to True, it means that the qubit is an auxiliary qubit + + def __init__(self,tag = False,ids=None): + #BaseQubit.__init__(self) + self.matrix = [[],[]] + self.amplitude = [0,0] + self.assignmentError = 0.0 + self.singleGateError = 0.0 + #show whether the qubit was in entanglement + self.entanglement = None + if ids == None: + ids = Qubit.totalNum + 1 + #the index of the current qubit, the range is from 0 to n + if ids in Qubit.idList: + try: + raise IDRepeatError() + except IDRepeatError as ir: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg(ir,funName,line) + self.ids = ids + Qubit.totalNum += 1 + Qubit.idList.append(ids) + #set the initial value of the qubit according to the mode + if self.mode == 'simulator': + #has assignment error and gate error + error = interactCfg.readCfgER(ids) + #according to the error to product the amplitude + self.matrix[1].append(math.sqrt(error)) + self.matrix[0].append(math.sqrt(1-error)) + elif self.mode == 'theory': + #no assignment error or gate error + self.matrix[0].append(1) + self.matrix[1].append(0) + else: + try: + raise ExecuteModeError() + except ExecuteModeError as em: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg(em,funName,line) + self.setAmp() + #set the type of the qubit + if tag: + #it means that the qubit is an auxiliary Qubit + self.tag = "AX" + else: + #the qubit is an actual qubit + self.tag = "AC" + self.recordQubit() + + #overwrite the function + def getAmp(self): + if self.entanglement == None: + return self.amplitude + else: + prob = self.decideProb([self])[0] + amp = [] + for p in prob: + amp.append(math.sqrt(p)) + return amp + def getMatrix(self): + if self.entanglement == None: + return self.matrix + else: + prob = self.decideProb([self])[0] + matrix = [] + for p in prob: + matrix.append([math.sqrt(p)]) + return matrix + + #store the current qubit in the circuit instance + def recordQubit(self): + circuitInstance = checkEnvironment() + if circuitInstance == None: + #there is zero or more than one circuit instance + try: + raise EnvironmentError() + except EnvironmentError as ee: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg(ee,funName,line) + + if circuitInstance.withOD: + if self in circuitInstance.qubitExecuteList: + del circuitInstance.qubitExecuteListOD[self] + circuitInstance.qubitNumOD -= 1 + circuitInstance.qubitExecuteListOD[self] = [] + circuitInstance.qubitNumOD += 1 + + if self.tag == "AC": + if self in circuitInstance.qubitExecuteList: + del circuitInstance.qubitExecuteList[self] + circuitInstance.qubitNum -= 1 + circuitInstance.qubitExecuteList[self] = [] + circuitInstance.qubitNum += 1 + + def decideProb(self, qubitList:list = None): + #the first dimen is probability, the second dimen is state + result = [[],[]] + qs = self.entanglement + #once the qubit is in entanglement, the amplitude maybe different + if qs == None: + #print(self.getAmp()) + self.normalize() + #print(self.getAmp()) + amplitude = self.getAmp() + result[0].append((amplitude[0] * amplitude[0].conjugate()).real) + result[0].append((amplitude[1] * amplitude[1].conjugate()).real) + result[1].append("0") + result[1].append("1") + else: + if qubitList == None or len(qubitList) == 0: + try: + raise ValueError() + except ValueError: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg("ValueError: The argument qubitList has no element, it must has at least one element",funName,line) + #print(qs.getAmp()) + qs.normalize() + amplitude = qs.getAmp() + totalQubit = len(qs.qubitList) + iTH = [] + #get the index of the argument qubitList + for qubit in qubitList: + index = qs.getIndex(qubit) + if index == -1: + try: + raise ValueError("Q" + str(qubit.ids) + " is not belong to the qubits") + except ValueError as ve: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg(ve,funName,line) + iTH.append(index) + length = len(iTH) + caseNum = 2 ** length + iTH.sort() + #get the corresponding state + stateList = [] + probList = [] + for i in range(0,caseNum): + state = bin(i).split('b')[1] + #add zero to beginning of the binary + for m in range(len(state) , len(iTH)): + state = '0' + state + stateList.append(state) + for state in stateList: + #len(state) = length + indexList = [] + + for j in range(0,length): + indexList.append(2 ** (totalQubit - iTH[j] - 1)) + prob = 0 + for k in range(0,2**totalQubit): + target = True + for index in range(0,len(indexList)): + if k & indexList[index] == int(state[index]) * indexList[index]: + continue + target = False + if target: + prob += (amplitude[k] * amplitude[k].conjugate()).real + probList.append(prob) + # print(stateList) + # print(amplitudeList) + result[0] = probList + result[1] = stateList + return result + + def degenerate(self): + self.normalize() + ampList = self.getAmp() + probList = [(i*i.conjugate()).real for i in ampList] + if len(probList) != 2: + try: + raise ValueError + except ValueError: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg("ValueError: the sum of the probabilities of |0> and |1> is not 1!",funName,line) + randomNumber = random.uniform(0,1) + #the order of the state of the qubit must be 0 and 1 + if randomNumber - probList[0] > 0: + value = 1 + else: + value = 0 + bit = Bit(value,self.ids) + qs = self.entanglement + if qs != None: + qs.deleteItem([self]) + return bit + + #delete the qubit + def delete(self): + self.entanglement = None + if self.ids in Qubit.idList: + Qubit.idList.remove(self.ids) + + # def __del__(self): + # try: + # Qubit.idList.remove(self.ids) + # #the qubit is degenerated to Bit + # except KeyError as ke: + # interactCfg.writeErrorMsg("KeyError: " + str(ve) + " is not in Qubit instance!") + +class Qubits(BaseQubit): + #the init has two qubits as input, compute the tensor product of the two elements + ######################################################################################################### + #if there are some other ways to preparation entanglement, we can write another init with different input + ######################################################################################################### + def __init__(self,q1:Qubit,q2:Qubit): + #the two qubits must be not in the entanglement + if q1.entanglement != None or q2.entanglement != None: + try: + raise ValueError("The qubits must not be in the entanglement!") + except ValueError as ve: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg(ve,funName,line) + #store the number of entanglement qubits + self.number = 2 + self.matrix = [] + self.setMatrix(q1 * q2) + self.amplitude = [0] * (len(q1.getAmp())*len(q2.getAmp())) + self.qubitList = [q1,q2] + #change the variable "entanglement" of qubit to this instance + q1.entanglement = self + q2.entanglement = self + + #qs[index] + def __getitem__(self,index): + item = None + try: + item = self.qubitList[index] + except IndexError as ie: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg(ie,funName,line) + return item + + #input two matrix, then compute the tensor product of the two matrix and return the new matrix + def mulMatrix(self,matrix,newMatrix): + result = [] + for i in range(0,len(matrix)): + for j in range(0,len(newMatrix)): + item = [] + item.append(matrix[i][0] * newMatrix[j][0]) + result.append(item) + return result + + #return the index of the qubitList, if not in, return -1 + def getIndex(self,qubit:Qubit): + for i in range(0,len(self.qubitList)): + if qubit == self.qubitList[i]: + return i + return -1 + + #data can be Qubit or Qubits + def addNewItem(self,data): + if len(self.qubitList) == 0: + try: + raise ValueError() + except ValueError: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg("ValueError: There is no element in this Qubits!",funName,line) + types = type(data) + if types != Qubit and types != Qubits: + try: + raise TypeError() + except TypeError: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg("TypeError: the type should be Qubit or Qubits",funName,line) + #compute the matrix of the new qubits + newMatrix = self.mulMatrix(self.getMatrix(),data.getMatrix()) + if types == Qubit: + self.qubitList.append(data) + self.number += 1 + data.entanglement = self + else: + #the types of data is qubits + for item in data.qubitList: + self.qubitList.append(item) + self.number += 1 + item.entanglement = self + self.setMatrix(newMatrix) + return 0 + + #delete the list of qubit from current instance + def deleteItem(self,ql:list): + for q in ql: + if self.getIndex(q) == -1: + #the qubit isn't in this instance + try: + raise ValueError() + except ValueError: + info = get_curl_info() + funName = info[0] + line = info[1] + interactCfg.writeErrorMsg("ValueError: qubit(q" + str(q.ids) + ") is not in this Qubits!",funName,line) + #qlIn store the qubit which are in this Qubits and haven't been measured + qlIn = [] + for qubit in self.qubitList: + if qubit not in ql: + qlIn.append(qubit) + #change the state of the current Qubits + newMatrix = [] + if len(qlIn) == 0: + pass + else: + result = q.decideProb(qlIn) + state = result[1] + prob = result[0] + newMatrix = [] + for i in range(0,2**(len(qlIn))): + newMatrix.append([0]) + for s in range(0,len(state)): + l = len(state[s]) + sums = 0 + for index in range(0,l): + number = int(state[s][index]) * (2**(l-index-1)) + sums += number + newMatrix[sums][0] = math.sqrt(prob[s]) + #delete the measured qubit from qubits and convert the measured qubit to bit class + for q in ql: + q.delete() + for i in range(0,len(ql)): + self.number -= 1 + self.qubitList.remove(ql[i]) + self.setMatrix(newMatrix) + + diff --git a/-QuQ--master/config/errorRate.cfg b/-QuQ--master/config/errorRate.cfg new file mode 100644 index 0000000000000000000000000000000000000000..fc162d7e74dd855450d4200be051bdeb8004f781 --- /dev/null +++ b/-QuQ--master/config/errorRate.cfg @@ -0,0 +1,2 @@ +{"single":{"0":"0.00179","1":"0.00347","2":"0.00323","3":"0.00214","4":"0.00231","5":"0.00183","6":"0.00219","7":"0.00246","8":"0.00094","9":"0.00127","10":"0.00186","11":"0.00175","12":"0.00163","13":"0.00225","14":"0.00213","15":"0.0037"}} +{"multi":"0.03945"} diff --git a/-QuQ--master/doc/UserManual/userManual.pdf b/-QuQ--master/doc/UserManual/userManual.pdf new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/-QuQ--master/doc/UserManual/userManual.pdf @@ -0,0 +1 @@ + diff --git a/-QuQ--master/main/main.py b/-QuQ--master/main/main.py new file mode 100644 index 0000000000000000000000000000000000000000..0f26f7724437c13c39c518d62e15bdbad45483f7 --- /dev/null +++ b/-QuQ--master/main/main.py @@ -0,0 +1,72 @@ +import sys +sys.path.append('../userCode/') +sys.path.append('../tools/') +from interactCfg import readCfgEA +import warnings +#from Grover import grover + +if __name__ == "__main__": + #ignore the warning message + warnings.filterwarnings("ignore") + print('-' * 80) + print('') + print(' '*30 + "Welcome to QuanSim!" + " "*20) + print('') + print('-' * 80) + # import_string = "from Grover import grover" + # exec(import_string) + # grover() + funName = "" + funFile = "" + functionList = readCfgEA() + way = -1 + #there are two ways to execute the code + #1.give the function name as a parameter, the format of the parameter is xx() + #2.input the number of the function you want to run + if len(sys.argv) == 2: + way = 1 + #the first way + funName = sys.argv[1] + for function in functionList: + if funName == function[1]: + funFile = function[0] + if funFile == "": + print("Invalid parameter! The format of the function name must be xx()!") + way = 2 + elif len(sys.argv) == 1: + #the second way + way = 2 + else: + print("Invalid parameter! There can only be one parameter, and the format of it is 'xx()'!") + way = 2 + if way == 2: + #the second way + print(' '*26 + 'The following code is vaild:' + ' '*20) + + for i in range(1,len(functionList)+1): + print(str(i) + ':' + functionList[i-1][1]) + ids = input("Please enter the number of the code you want to execute:") + try: + funName = functionList[int(ids)-1][1] + funFile = functionList[int(ids)-1][0] + except ValueError: + print("ValueError: The input is not a number!") + sys.exit(0) + except KeyError: + print("KeyError: The input number is invalid! ") + sys.exit(0) + except IndexError: + print("IndexError: The input number is out of range!") + sys.exit(0) + print("The code you want to execute is :" + funFile + "." + funName) + import_string = "from " + funFile + " import " + funName.split("(")[0] + try: + exec(import_string) + exec(funName) + except ImportError as ie: + print("ImportError: " + str(ie)) + sys.exit(0) + + + + diff --git a/-QuQ--master/results/EXP2018-03-14-15.23.40/Logical-Level/QASM.txt b/-QuQ--master/results/EXP2018-03-14-15.23.40/Logical-Level/QASM.txt new file mode 100644 index 0000000000000000000000000000000000000000..61fbab90592fd914bc072f40cf05dc72413b5172 --- /dev/null +++ b/-QuQ--master/results/EXP2018-03-14-15.23.40/Logical-Level/QASM.txt @@ -0,0 +1,5 @@ +Rx(0.25*pi) q[4]; +Rx(0.25*pi) q[4]; +Rx(0.25*pi) q[4]; +Rx(0.25*pi) q[4]; +M q[4] -> c[4]; diff --git a/-QuQ--master/results/EXP2018-03-14-15.23.40/Physical-Level/QASM.txt b/-QuQ--master/results/EXP2018-03-14-15.23.40/Physical-Level/QASM.txt new file mode 100644 index 0000000000000000000000000000000000000000..191741541d16f5e742069fdb9cb7782a78e4f5b3 --- /dev/null +++ b/-QuQ--master/results/EXP2018-03-14-15.23.40/Physical-Level/QASM.txt @@ -0,0 +1,13 @@ +Rz(0.5*pi) q[4]; +Ry(-0.25*pi) q[4]; +Rz(-0.5*pi) q[4]; +Rz(0.5*pi) q[4]; +Ry(-0.25*pi) q[4]; +Rz(-0.5*pi) q[4]; +Rz(0.5*pi) q[4]; +Ry(-0.25*pi) q[4]; +Rz(-0.5*pi) q[4]; +Rz(0.5*pi) q[4]; +Ry(-0.25*pi) q[4]; +Rz(-0.5*pi) q[4]; +M q[4] -> c[4]; diff --git a/-QuQ--master/results/EXP2018-03-14-15.23.40/originalData.csv b/-QuQ--master/results/EXP2018-03-14-15.23.40/originalData.csv new file mode 100644 index 0000000000000000000000000000000000000000..6bba3add59951efd9cd91f45e7ee43152725473e --- /dev/null +++ b/-QuQ--master/results/EXP2018-03-14-15.23.40/originalData.csv @@ -0,0 +1,2 @@ +state,times +|1>,1024 diff --git a/-QuQ--master/results/EXP2018-03-14-15.23.45/Logical-Level/QASM.txt b/-QuQ--master/results/EXP2018-03-14-15.23.45/Logical-Level/QASM.txt new file mode 100644 index 0000000000000000000000000000000000000000..cf313e1c25794a6f024640dd6480c7e54bedcd2b --- /dev/null +++ b/-QuQ--master/results/EXP2018-03-14-15.23.45/Logical-Level/QASM.txt @@ -0,0 +1,19 @@ +H q[1]; +H q[2]; +X q[3]; +H q[3]; +Toffoli q[1],q[2],q[3]; +H q[1]; +H q[2]; +H q[3]; +X q[1]; +X q[2]; +H q[2]; +CNOT q[1],q[2]; +X q[1]; +H q[2]; +H q[1]; +X q[2]; +M q[1] -> c[1]; +H q[2]; +M q[2] -> c[2]; diff --git a/-QuQ--master/results/EXP2018-03-14-15.23.45/originalData.csv b/-QuQ--master/results/EXP2018-03-14-15.23.45/originalData.csv new file mode 100644 index 0000000000000000000000000000000000000000..ec54ba1a644f3da88a2aa4592f74ce21d770e02d --- /dev/null +++ b/-QuQ--master/results/EXP2018-03-14-15.23.45/originalData.csv @@ -0,0 +1,2 @@ +state,times +|11>,1024 diff --git a/-QuQ--master/tools/export.py b/-QuQ--master/tools/export.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/-QuQ--master/tools/export.py @@ -0,0 +1 @@ + diff --git a/-QuQ--master/userCode/Grover.py b/-QuQ--master/userCode/Grover.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2031851676e1e4ad668cf055a6d3fb6324ce71 --- /dev/null +++ b/-QuQ--master/userCode/Grover.py @@ -0,0 +1,93 @@ +from header import * + +def grover(): + totalElement = 4 + #the number of the qubits in theory + n = 0 + amount = 2 ** n + while amount < totalElement: + amount *= 2 + n += 1 + #the number of qubits actually used + N = 2*n - 1 + #the target element + targetE = "11" + #check the length of the target element and the totalElement + if checkE(totalElement,targetE): + c = Circuit() + qList = [] + for i in range(0,N): + q = Qubit() + qList.append(q) + + X(qList[N-1]) + for i in range(0,N): + H(qList[i]) + + #act the G operator for "times" times + times = executeTimes(totalElement) + for i in range(0,times): + G(qList,targetE) + + #measure the qubits + for i in range(0,N-1): + qList[i] = M(qList[i]) + + #execute the circuit for 1024 times + c.execute(1024) + else: + writeErrorMsg("The length of the target element isn't correspond with the number of the total elements!") + +#the parameter is the size of the database. +#and the target is supposed to one element +def executeTimes(n): + theta = math.asin(math.sqrt(1 / n)) / math.pi * 180 + times = (90 - theta) / (2 * theta) + if times > int(times) + 0.5: + return int(times) + 1 + else: + return int(times) + +def checkE(toE:int,taE:str): + if toE <= (2 ** len(taE)): + return True + else: + return False + +def G(qList:list,taE:str): + qn = len(qList) + #there are four phase in this G operator + #PH1: apply the oracle operator + vl = [] + for k in range(0,len(taE)): + vl.append(int(taE[k])) + tmp1 = [] + for j in range(0,qn-1): + tmp1.append(qList[j]) + with DMif(tmp1,vl) as dmo1: + dmo1.X(qList[qn-1]) + + #PH2: act H gates on the qubits except the last element + for i in range(0,qn-1): + H(qList[i]) + + #PH3: act the phase operator on the qubits except the last element + for i in range(0,qn-1): + X(qList[i]) + H(qList[qn-2]) + + tmp2 = [] + for j in range(0,qn-2): + tmp2.append(qList[j]) + with DMif(tmp2,1) as dmo2: + dmo2.X(qList[qn-2]) + + H(qList[qn-2]) + for i in range(0,qn-1): + X(qList[i]) + + #PH4: act the H gates on all the qubits + for i in range(0,qn): + H(qList[i]) + + diff --git a/-QuQ--master/userCode/GroverN=8theory/originalData.csv b/-QuQ--master/userCode/GroverN=8theory/originalData.csv new file mode 100644 index 0000000000000000000000000000000000000000..73b66f325ccb0794e2d37189443e23b405fc83cc --- /dev/null +++ b/-QuQ--master/userCode/GroverN=8theory/originalData.csv @@ -0,0 +1,9 @@ +state,times +|000>,126 +|001>,63 +|100>,129 +|101>,68 +|010>,131 +|011>,63 +|110>,123 +|111>,321 diff --git a/-QuQ--master/userCode/UserSWAP.py b/-QuQ--master/userCode/UserSWAP.py new file mode 100644 index 0000000000000000000000000000000000000000..efba262ebe21c25de77753ed6ef0a2446a84696b --- /dev/null +++ b/-QuQ--master/userCode/UserSWAP.py @@ -0,0 +1,15 @@ +from header import * + +def SWAP(): + c = Circuit(True) + q1 = Qubit() + q2 = Qubit() + X(q2) + ########SWAP gate######## + CNOT(q1,q2) + CNOT(q2,q1) + CNOT(q1,q2) + ######################### + M(q1) + M(q2) + c.execute(1024) \ No newline at end of file diff --git a/0617-audio_stream-master/README.md b/0617-audio_stream-master/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7d7cbc18c7764f8f81e9eb273bb84f441802ad89 --- /dev/null +++ b/0617-audio_stream-master/README.md @@ -0,0 +1 @@ +# 0617-audio_stream \ No newline at end of file diff --git a/0617-audio_stream-master/hyper.py b/0617-audio_stream-master/hyper.py new file mode 100644 index 0000000000000000000000000000000000000000..735ad88c5e6c586b557c0de47e00436a9079e62b --- /dev/null +++ b/0617-audio_stream-master/hyper.py @@ -0,0 +1,29 @@ +from datetime import datetime +from torch import nn +from mean_std import * +now = str(datetime.now()) + +epochs = 25 +batch_size = 20 +lr = 1e-3 +decay = 5 +save_hop = 2 +obj_func = nn.BCEWithLogitsLoss() +fixed = 0 +f_num = 7 +specs_stack = 7 +''' +MEAN = [ 110.63666788 / 255.0, 103.16065604 / 255.0, 96.29023126 / 255.0 ] +STD = [ 38.7568578 / 255.0, 37.88248729 / 255.0, 40.02898126 / 255.0 ] +''' +MEAN = train_specs_mean +STD = train_specs_std + +train_data_path = './Data/OP_Train_DATA/frames/' +test_data_path = './Data/OP_Test_DATA/specs/' +test_data_path1 = './Data/DAVSOD_Test_DATA/frames_and_GT_part/easy/' +# checkpoint_load = './pre-trained/model.pth.tar' +checkpoint_load = './pre-trained/model_cpd_400615_Adam_0.0001_20_BCEWithLogitsLoss_8.pth' +# checkpoint_load = './pre-trained/model_cpd_500608_Adam_1.0000000000000002e-07_20_BCEWithLogitsLoss_40.pth' +checkpoint_name = 'cpd_' + str(epochs) + now[5:7] + now[8:10] +checkpoint_save = './checkpoint/' diff --git a/0617-audio_stream-master/mean_std.py b/0617-audio_stream-master/mean_std.py new file mode 100644 index 0000000000000000000000000000000000000000..ed864a5c5525022d8029348fb4bcace558524c89 --- /dev/null +++ b/0617-audio_stream-master/mean_std.py @@ -0,0 +1,11 @@ +train_frames_mean = [0.133460, 0.121699, 0.104900] +train_frames_std = [0.198126, 0.179522, 0.164552] + +train_specs_mean = [0.252584, 0.710676, 0.641858] +train_specs_std = [0.260608, 0.099738, 0.244512] + +test_frames_mean = [0.201312, 0.201226, 0.195387] +test_frames_std = [0.222184, 0.227670, 0.225742] + +test_specs_mean = [0.279390, 0.712614, 0.621488] +test_specs_std = [0.278205, 0.101402, 0.256067] diff --git a/0617-audio_stream-master/model/ResNe3D.py b/0617-audio_stream-master/model/ResNe3D.py new file mode 100644 index 0000000000000000000000000000000000000000..9c99c9c6cd9cddf527a8559cdc019d42f57861c5 --- /dev/null +++ b/0617-audio_stream-master/model/ResNe3D.py @@ -0,0 +1,270 @@ +import torch +import numpy as np +import torch.nn as nn +import torch.nn.functional as F +from torch.autograd import Variable +import math +from functools import partial + +__all__ = [ + 'ResNet', 'resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101', + 'resnet152', 'resnet200' +] + + +def conv3x3x3(in_planes, out_planes, stride=1): + # 3x3x3 convolution with padding + return nn.Conv3d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=1, + bias=False) + + +def downsample_basic_block(x, planes, stride): + out = F.avg_pool3d(x, kernel_size=1, stride=stride) + zero_pads = torch.Tensor( + out.size(0), planes - out.size(1), out.size(2), out.size(3), + out.size(4)).zero_() + if isinstance(out.data, torch.cuda.FloatTensor): + zero_pads = zero_pads.cuda() + + out = Variable(torch.cat([out.data, zero_pads], dim=1)) + + return out + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(BasicBlock, self).__init__() + self.conv1 = conv3x3x3(inplanes, planes, stride) + self.bn1 = nn.BatchNorm3d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3x3(planes, planes) + self.bn2 = nn.BatchNorm3d(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm3d(planes) + self.conv2 = nn.Conv3d( + planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) + self.bn2 = nn.BatchNorm3d(planes) + self.conv3 = nn.Conv3d(planes, planes * 4, kernel_size=1, bias=False) + self.bn3 = nn.BatchNorm3d(planes * 4) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class ResNet(nn.Module): + + def __init__(self, + block, + layers, + sample_size, + sample_duration, + shortcut_type='B', + num_classes=400, + last_fc = True, + last_pool = True): + self.inplanes = 64 + super(ResNet, self).__init__() + self.conv1 = nn.Conv3d( + 3, + 64, + kernel_size=7, + stride=(1, 2, 2), + padding=(3, 3, 3), + bias=False) + self.bn1 = nn.BatchNorm3d(64) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=2, padding=1) + self.layer1 = self._make_layer( + block, 64, layers[0], shortcut_type) + self.layer2 = self._make_layer( + block, 128, layers[1], shortcut_type, stride=2) + self.layer3 = self._make_layer( + block, 256, layers[2], shortcut_type, stride=2) + self.layer4 = self._make_layer( + block, 512, layers[3], shortcut_type, stride=2) + last_duration = int(math.ceil(sample_duration / 16)) + last_size = int(math.ceil(sample_size / 32)) + self.avgpool = nn.AvgPool3d( + (last_duration, last_size, last_size), stride=1) + self.fc = nn.Linear(512 * block.expansion, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Conv3d): + m.weight = nn.init.kaiming_normal(m.weight, mode='fan_out') + elif isinstance(m, nn.BatchNorm3d): + m.weight.data.fill_(1) + m.bias.data.zero_() + + def _make_layer(self, block, planes, blocks, shortcut_type, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + if shortcut_type == 'A': + downsample = partial( + downsample_basic_block, + planes=planes * block.expansion, + stride=stride) + else: + downsample = nn.Sequential( + nn.Conv3d( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias=False), nn.BatchNorm3d(planes * block.expansion)) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + + x = self.layer1(x) + + x = self.layer2(x) + x1 = x + x1 = x1.reshape(x1.size(0), x1.size(1)*x1.size(2), x1.size(3), x1.size(4)) + + x = self.layer3(x) + x2 = x + x2 = x2.reshape(x2.size(0), x2.size(1) * x2.size(2), x2.size(3), x2.size(4)) + + x = self.layer4(x) + x3 = x + x3 = x3.reshape(x3.size(0), x3.size(1) * x3.size(2), x3.size(3), x3.size(4)) + # print(x.shape, x3.shape) + + return x1, x2, x3 + + +def get_fine_tuning_parameters(model, ft_begin_index): + if ft_begin_index == 0: + return model.parameters() + + ft_module_names = [] + for i in range(ft_begin_index, 5): + ft_module_names.append('layer{}'.format(i)) + ft_module_names.append('fc') + + parameters = [] + for k, v in model.named_parameters(): + for ft_module in ft_module_names: + if ft_module in k: + parameters.append({'params': v}) + break + else: + parameters.append({'params': v, 'lr': 0.0}) + + return parameters + + +def resnet10(**kwargs): + """Constructs a ResNet-18 model. + """ + model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs) + return model + + +def resnet18(**kwargs): + """Constructs a ResNet-18 model. + """ + model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) + return model + + +def resnet34(**kwargs): + """Constructs a ResNet-34 model. + """ + model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) + return model + + +def resnet50(**kwargs): + """Constructs a ResNet-50 model. + """ + model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) + return model + + +def resnet101(**kwargs): + """Constructs a ResNet-101 model. + """ + model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) + return model + + +def resnet152(**kwargs): + """Constructs a ResNet-101 model. + """ + model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) + return model + + +def resnet200(**kwargs): + """Constructs a ResNet-101 model. + """ + model = ResNet(Bottleneck, [3, 24, 36, 3], **kwargs) + return model diff --git a/0617-audio_stream-master/model/ResNet.py b/0617-audio_stream-master/model/ResNet.py new file mode 100644 index 0000000000000000000000000000000000000000..67ff16e816277f53540cac75988fe0677ccb1938 --- /dev/null +++ b/0617-audio_stream-master/model/ResNet.py @@ -0,0 +1,142 @@ +import torch.nn as nn +import math + + +def conv3x3(in_planes, out_planes, stride=1): + """3x3 convolution with padding""" + return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, + padding=1, bias=False) + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(BasicBlock, self).__init__() + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = nn.BatchNorm2d(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, + padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * 4) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class B2_ResNet(nn.Module): + # ResNet50 with two branches + def __init__(self): + # self.inplanes = 128 + self.inplanes = 64 + super(B2_ResNet, self).__init__() + + self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, + bias=False) + self.bn1 = nn.BatchNorm2d(64) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(Bottleneck, 64, 3) + self.layer2 = self._make_layer(Bottleneck, 128, 4, stride=2) + self.layer3_1 = self._make_layer(Bottleneck, 256, 6, stride=2) + self.layer4_1 = self._make_layer(Bottleneck, 512, 3, stride=2) + + self.inplanes = 512 + self.layer3_2 = self._make_layer(Bottleneck, 256, 6, stride=2) + self.layer4_2 = self._make_layer(Bottleneck, 512, 3, stride=2) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + m.weight.data.normal_(0, math.sqrt(2. / n)) + elif isinstance(m, nn.BatchNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2d(self.inplanes, planes * block.expansion, + kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(planes * block.expansion), + ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + + x = self.layer1(x) + x = self.layer2(x) + x1 = self.layer3_1(x) + x1 = self.layer4_1(x1) + + x2 = self.layer3_2(x) + x2 = self.layer4_2(x2) + + return x1, x2 diff --git a/0617-audio_stream-master/model/ResNet_18.py b/0617-audio_stream-master/model/ResNet_18.py new file mode 100644 index 0000000000000000000000000000000000000000..f264e237102813556881ac9687cc6d2b38fb6602 --- /dev/null +++ b/0617-audio_stream-master/model/ResNet_18.py @@ -0,0 +1,79 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ResidualBlock(nn.Module): + def __init__(self, inchannel, outchannel, stride=1): + super(ResidualBlock, self).__init__() + self.left = nn.Sequential( + nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False), + nn.BatchNorm2d(outchannel), + nn.ReLU(inplace=True), + nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(outchannel) + ) + self.shortcut = nn.Sequential() + if stride != 1 or inchannel != outchannel: + self.shortcut = nn.Sequential( + nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(outchannel) + ) + + def forward(self, x): + out = self.left(x) + out += self.shortcut(x) + out = F.relu(out) + return out + + +class ResNet(nn.Module): + def __init__(self, ResidualBlock, num_classes=10): + super(ResNet, self).__init__() + self.inchannel = 64 + self.conv1 = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False), + nn.BatchNorm2d(64), + nn.ReLU(), + ) + self.layer1 = self.make_layer(ResidualBlock, 64, 2, stride=1) + self.layer2 = self.make_layer(ResidualBlock, 128, 2, stride=2) + self.layer3 = self.make_layer(ResidualBlock, 256, 2, stride=2) + self.layer4 = self.make_layer(ResidualBlock, 512, 2, stride=2) + self.fc = nn.Linear(512, num_classes) + + def make_layer(self, block, channels, num_blocks, stride): + strides = [stride] + [1] * (num_blocks - 1) #strides=[1,1] + layers = [] + for stride in strides: + layers.append(block(self.inchannel, channels, stride)) + self.inchannel = channels + return nn.Sequential(*layers) + + def forward(self, x): + # torch.Size([bs, 3, 256, 320]) + + # torch.Size([8, 64, 256, 320]) + out = self.conv1(x) + + # torch.Size([8, 64, 256, 320]) + out = self.layer1(out) + + # torch.Size([8, 128, 128, 160]) + out = self.layer2(out) + + # torch.Size([8, 256, 64, 80]) + out = self.layer3(out) + + # torch.Size([8, 512, 32, 40]) + out = self.layer4(out) + + # out = F.avg_pool2d(out, 4) + # out = out.view(out.size(0), -1) + # out = self.fc(out) + + return out + + +def ResNet2_18(): + return ResNet(ResidualBlock) diff --git a/0617-audio_stream-master/model/v_a_con.py b/0617-audio_stream-master/model/v_a_con.py new file mode 100644 index 0000000000000000000000000000000000000000..58b12f4c2069585ad2720fece4251bb165363c8b --- /dev/null +++ b/0617-audio_stream-master/model/v_a_con.py @@ -0,0 +1,43 @@ +import torch +import torch.nn as nn + + +class Video_Audio_Con(nn.Module): + def __init__(self): + super(Video_Audio_Con, self).__init__() + + # f_num = 10 384 + self.conv_3 = nn.Conv2d(128, 256, 1, padding=0) + self.conv_4 = nn.Conv2d(256, 512, 1, padding=0) + self.conv_5 = nn.Conv2d(512, 512, 1, padding=0) + + def forward(self, x, y): + mix = torch.cat((x, y), 1) + + return mix + + +class Video_Audio_Con_10(nn.Module): + def __init__(self): + super(Video_Audio_Con_10, self).__init__() + + self.upsample_a1 = nn.Upsample(scale_factor=8, mode='bilinear', align_corners=False) + self.conv_last = nn.Conv2d(512, 1, 1, padding=0) + + def forward(self, x, y): + mix = torch.cat((x, y), 1) + + return mix + + +class Video_Audio_Con_audio(nn.Module): + def __init__(self): + super(Video_Audio_Con_audio, self).__init__() + + self.upsample_a1 = nn.Upsample(scale_factor=8, mode='bilinear', align_corners=False) + self.conv_last = nn.Conv2d(512, 1, 1, padding=0) + + def forward(self, x, y): + mix = torch.cat((x, y), 1) + + return mix diff --git a/0621_test-master/.gitignore b/0621_test-master/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9c36d447ee8934c52cb168fdcb660e0684446b57 --- /dev/null +++ b/0621_test-master/.gitignore @@ -0,0 +1,229 @@ +ustom +.idea/ + +# Created by https://www.gitignore.io/api/vim,macos,linux,django,python,pycharm + +### Django ### +*.log +*.pot +*.pyc +__pycache__/ +local_settings.py +db.sqlite3 +media + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +### PyCharm Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Python ### +# Byte-compiled / optimized / DLL files +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo + +# Django stuff: + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +### Vim ### +# swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-v][a-z] +[._]sw[a-p] +# session +Session.vim +# temporary +.netrwhist +# auto-generated tag files +tags + +# End of https://www.gitignore.io/api/vim,macos,linux,django,python,pycharm + diff --git a/0621_test-master/.pipreqs/requirements_pipreqs.txt b/0621_test-master/.pipreqs/requirements_pipreqs.txt new file mode 100644 index 0000000000000000000000000000000000000000..9931ccdd19807ea71be67c62a20b7b0baf4b4592 --- /dev/null +++ b/0621_test-master/.pipreqs/requirements_pipreqs.txt @@ -0,0 +1 @@ +Django==5.1.7 diff --git a/0621_test-master/django_app/config/urls.py b/0621_test-master/django_app/config/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a6a32944ca6639e025c365d8c4507f1ca55a53 --- /dev/null +++ b/0621_test-master/django_app/config/urls.py @@ -0,0 +1,22 @@ +"""test_project URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.11/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +from django.conf.urls import url, include +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), + url(r'^post/', include('post.urls')) +] diff --git a/0621_test-master/django_app/manage.py b/0621_test-master/django_app/manage.py new file mode 100644 index 0000000000000000000000000000000000000000..68141ee9e00d47db18f3598190234e8f8818dd5d --- /dev/null +++ b/0621_test-master/django_app/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django + except ImportError: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) + raise + execute_from_command_line(sys.argv) diff --git a/0621_test-master/django_app/post/urls.py b/0621_test-master/django_app/post/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..dae1056e700a7e4410960138f38f54f9ab626e0c --- /dev/null +++ b/0621_test-master/django_app/post/urls.py @@ -0,0 +1,10 @@ +from django.conf.urls import url + +from . import views + +app_name = 'post' +urlpatterns = [ + url(r'^$', views.post_list, name='post_list'), + url(r'^(?P\d+)/delete$', views.post_delete, name='post_delete'), + url(r'^(?P\d+)/modify$', views.post_modify, name='post_modify') +] \ No newline at end of file diff --git a/0621_test-master/django_app/post/views.py b/0621_test-master/django_app/post/views.py new file mode 100644 index 0000000000000000000000000000000000000000..908cbac6da86193edd81df4c04ee771acf198fa0 --- /dev/null +++ b/0621_test-master/django_app/post/views.py @@ -0,0 +1,36 @@ +from django.http import HttpResponseRedirect +from django.shortcuts import render, redirect + +from .forms import CommentForm +from .models import Post + + +def post_list(request): + posts = Post.objects.all() + context = { + 'posts': posts + } + return render(request, 'post/post_list.html', context) + + +def post_delete(request, post_pk): + if request.method == 'POST': + post = Post.objects.get(pk=post_pk) + post.delete() + return redirect('post:post_list') + + +def post_modify(request, post_pk): + if request.method == 'POST': + post = Post.objects.get(pk=post_pk) + form = CommentForm(data=request.POST) + if form.is_valid(): + comment = form.cleaned_data['comment'] + post.comment = comment + post.save() + return redirect('post:post_list') + else: + context = { + 'form': CommentForm() + } + return render(request, 'post/post_modify.html', context) diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.py new file mode 100644 index 0000000000000000000000000000000000000000..cf1e6516087fd5fd4972c9de2f1e43816de86875 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.py @@ -0,0 +1,16 @@ +class Solution: + def removeOuterParentheses(self, S: str) -> str: + counter = 0 + start = 0 + + strs = [] + for i, c in enumerate(S): + if c == "(": + counter += 1 + else: + counter -= 1 + + if counter == 0: + strs.append(S[start + 1:i]) + start = i + 1 + return "".join(strs) diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree.go new file mode 100644 index 0000000000000000000000000000000000000000..22221edae668521cc383a68dd70879bf68620e19 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree.go @@ -0,0 +1,24 @@ +package main + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func maxDepth(root *TreeNode) int { + n := -1 + var dfs func(node *TreeNode, level int) + dfs = func(node *TreeNode, level int) { + if node == nil { + if level >= n { + n = level + 1 + } + return + } + dfs(node.Left, level+1) + dfs(node.Right, level+1) + } + dfs(root, n) + return n +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree3.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree3.py new file mode 100644 index 0000000000000000000000000000000000000000..4a3182ca645822fe1db8587c590e73a2a0ba75b2 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree3.py @@ -0,0 +1,26 @@ +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + level = 0 + queue = [root] + + while queue: + n = len(queue) + level += 1 + + for i in range(n): + if queue[i].left is not None: + queue.append(queue[i].left) + if queue[i].right is not None: + queue.append(queue[i].right) + + queue = queue[n:] + return level diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.py new file mode 100644 index 0000000000000000000000000000000000000000..ec44c2473b006de92f1107e6ac060f4820e4185a --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.py @@ -0,0 +1,22 @@ +class Solution: + def addDigits(self, num: int) -> int: + if num == 0: + return 0 + return (num - 1) % 9 + 1 + + def test(self): + for num, target in [ + (0, 0), + (1, 1), + (9, 9), + (10, 1), + (11, 2), + (19, 1), + ]: + ans = self.addDigits(num) + assert ans == target, f"target: {target}, ans: {ans}" + print("well done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits_test.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1759af7170be2942c46f701a58c09e45861a5d0f --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits_test.go @@ -0,0 +1,22 @@ +package main + +import "testing" + +func Test(t *testing.T) { + tests := []struct { + num int + target int + }{ + {3, 3}, + {38, 2}, + {19, 1}, + {138, 3}, + {888, 6}, + } + + for _, tt := range tests { + if ans := addDigits(tt.num); ans != tt.target { + t.Fatalf("ans: %d, target: %d\n", tt.num, tt.target) + } + } +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.py new file mode 100644 index 0000000000000000000000000000000000000000..83b83ccab0c4333aff2956b45a7b5e00f5a37a2e --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + if len(nums) == 0: + return 0 + dp = [1] * len(nums) + for i, n in enumerate(nums): + for j in range(0, i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + return max(dp) diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.go new file mode 100644 index 0000000000000000000000000000000000000000..abf91b100ad972dcb3c1cb070f7d9a61eaec1471 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.go @@ -0,0 +1,18 @@ +package main + +func plusOne(digits []int) []int { + carry := true + for i := len(digits) - 1; i >= 0; i-- { + if digits[i] == 9 { + digits[i] = 0 + } else { + digits[i]++ + carry = false + break + } + } + if carry { + digits = append([]int{1}, digits...) + } + return digits +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray.py new file mode 100644 index 0000000000000000000000000000000000000000..75a31b759e4ff61e4ce4dee8a7b1a8eee085c1d5 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray.py @@ -0,0 +1,28 @@ +from typing import List + + +class Solution: + def findLength(self, A: List[int], B: List[int]) -> int: + m, n = len(A), len(B) + if m == 0 or n == 0: + return 0 + + dp = [[0] * (n + 1) for _ in range(m + 1)] + res = 0 + for i in range(m): + for j in range(n): + if A[i] == B[j]: + dp[i + 1][j + 1] = dp[i][j] + 1 + else: + dp[i + 1][j + 1] = 0 + return res + + def test(self): + a = [1, 2, 3, 2, 1] + b = [3, 2, 1, 4, 7] + ans = self.findLength(a, b) + print(ans) + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number.go new file mode 100644 index 0000000000000000000000000000000000000000..fbf1ae70cbfdb0104f9d335da03da0fa3c5a2020 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number.go @@ -0,0 +1,34 @@ +package main + +func getKthMagicNumber(k int) int { + dp := make([]int, k) + dp[0] = 1 + three := 0 + five := 0 + seven := 0 + + for i := 1; i < k; i++ { + dp[i] = min3(3*dp[three], 5*dp[five], 7*dp[seven]) + if 3*dp[three] == dp[i] { + three++ + } + if 5*dp[five] == dp[i] { + five++ + } + if 7*dp[seven] == dp[i] { + seven++ + } + } + return dp[k-1] +} + +func min3(x, y, z int) int { + return min(x, min(y, z)) +} + +func min(x, y int) int { + if x < y { + return x + } + return y +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.py b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.py new file mode 100644 index 0000000000000000000000000000000000000000..bea7c4a29fea3a1e713feeda28348db38970c54e --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.py @@ -0,0 +1,19 @@ +import heapq + + +class Solution: + def getKthMagicNumber(self, k: int) -> int: + h = [1] + heapq.heapify(h) + visited = {1: True} + i = 0 + n = 1 + while i < k: + i += 1 + n = heapq.heappop(h) + for f in [3, 5, 7]: + m = f * n + if m not in visited: + heapq.heappush(h, m) + visited[m] = True + return n diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space.go b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space.go new file mode 100644 index 0000000000000000000000000000000000000000..0386101daf64715ec9f58fc69698a41cb8376935 --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space.go @@ -0,0 +1,15 @@ +package main + +import "strings" + +func replaceSpace(s string) string { + var sb strings.Builder + for i := 0;i< len(s);i++ { + if s[i] == ' ' { + sb.WriteString("%20") + } else { + sb.WriteByte(s[i]) + } + } + return sb.String() +} diff --git a/10-week-algorithm-excercise-master/OneQuestionPerDay/README.md b/10-week-algorithm-excercise-master/OneQuestionPerDay/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2cb5192462a44628845d7e48fe3c06f9e65d3ebe --- /dev/null +++ b/10-week-algorithm-excercise-master/OneQuestionPerDay/README.md @@ -0,0 +1,79 @@ +每日一题 + + +|Day|Number|Title|Solutions| +|---|---|---|------| +|1|70|[climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs) | 递推([Go](../Week_01/70/climbing_stairs.go),[Py](../Week_01/70/climbing_stairs.py))| +|2|66|[plus-one](https://leetcode-cn.com/problems/plus-one) | O(n)遍历([Go](66/plus_one.go),[Py](66/plus_one.py))| +|3|1|[two-sum](https://leetcode-cn.com/problems/two-sum) | 先排序后双指针夹逼([Go](../Week_01/1/two_sum.go)), 字典缓存差值的索引([Go](../Week_01/1/two_sum_2.go),[Py](../Week_01/1/two_sum.py))| +|4|24|[swap-nodes-in-pairs](https://leetcode-cn.com/problems/swap-nodes-in-pairs)| 迭代([Go](../Week_01/24/swap_nodes_in_pairs2.go),[Py](../Week_01/24/swap_nodes_in_pairs2.py)), 递归([Go](../Week_01/24/swap_nodes_in_pairs.go),[Py](../Week_01/24/swap_nodes_in_pairs.py))| +|5|21|[merge-two-sorted-lists](https://leetcode-cn.com/problems/merge-two-sorted-lists) | 迭代([Go](../Week_01/21/merge_two_sorted_lists.go), [Py](../Week_01/21/merge_two_sorted_lists.py)), 递归([Go](../Week_01/21/merge_two_sorted_lists2.go),[Py](../Week_01/21/merge_two_sorted_lists2.py))| +|6|299|[bulls-and-cows](https://leetcode-cn.com/problems/bulls-and-cows) | 数组记录可能的cows([Go](299/bulls_and_cows.go), [Py](299/bulls_and_cows.go))| +|7|641|[design-circular-deque](https://leetcode-cn.com/problems/design-circular-deque) | 双指针([Go](../Week_01/641/design_circular_deque.go)),双指针优化([Go](../Week_01/641/design_circular_deque2.go),[Py](../Week_01/641/design_circular_deque2.py))| +|8|350|[intersection-of-two-arrays-ii](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii) | 哈希表计数([Go](350/intersection_of_two_arrays_ii.go),[Py](350/intersection_of_two_arrays_ii.py)))| +|9|LCOF59|[mac-sliding-window](https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/) | 单调递减队列([Go](LCOF59/max_sliding_window.go),[Py](LCOF59/max_sliding_window.go)))| +|10|1021|[remove-outermost-parentheses](https://leetcode-cn.com/problems/remove-outermost-parentheses) | 双指针记录有效括号的起止([Go](1021/remove_outermost_parentheses.go),[Py](1021/remove_outermost_parentheses.py)))| +|11|412|[fizz-buzz](https://leetcode-cn.com/problems/fizz-buzz) | 遍历([Go](412/fizz_buzz.go),[Py](412/fizz_buzz.py)))| +|12|258|[add-digits](https://leetcode-cn.com/problems/add-digits) | 迭代([Go](258/add_digits.go),[Py](258/add_digits.py))), 取余([Go](258/add_digits2.go),[Py](258/add_digits2.py)))| +|13|104|[maximum-depth-of-binary-tree](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree) | 递归([Go](104/maximum_depth_of_binary_tree2.go),[Py](104/maximum_depth_of_binary_tree2.py))), 队列([Go](104/maximum_depth_of_binary_tree3.go),[Py](104/maximum_depth_of_binary_tree3.go)))| +|14|283|[move-zeroes](https://leetcode-cn.com/problems/move-zeroes) | 统计0的个数([Go](../Week_01/283/move_zeros.go),[Py](../Week_01/283/move_zeros.py)), 快慢指针([Go](../Week_01/283/move_zeros.go))| +|15|94|[binary-tree-inorder-traversal](https://leetcode-cn.com/problems/binary-tree-inorder-traversal) | 递归([Go](../Week_02/94/binary_tree_inorder_traversal.go),[Py](../Week_02/94/binary_tree_inorder_traversal.py)),栈([Go](../Week_02/94/binary_tree_inorder_traversal2.go),[Py](../Week_02/94/binary_tree_inorder_traversal2.py)), Morris遍历([Go](../Week_02/94/binary_tree_inorder_traversal3.go),[Py](../Week_02/94/binary_tree_inorder_traversal3.py))| +|16|LCOF5|[replace-space](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) | 新建一个buff([Go](LCOF5/replace_space.go),[Py](LCOF5/replace_space.go))| +|17|LCOF6|[reverse-print](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof) | 遍历([Go](LCOF6/reverse_link_node.go),[Py](LCOF6/reverse_link_node.py))| +|18|236|[lowest-common-ancestor-of-a-binary-tree](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree) | 递归([Go](../Week_03/236/lowest_common_ancestor_of_a-binary_tree.go),[Py](LCOF6/reverse_link_node.py))| +|19|1|[two-sum](https://leetcode-cn.com/problems/two-sum) | 字典存num-index键值对([Go](1/two_sum.go),[Py](1/two_sum.py))| +|20|15|[3sum](https://leetcode-cn.com/problems/3sum) | 双指针夹逼([Go](15/3sum.go),[Py](15/3sum.py))| +|21|LCCI17|[get-kth-magic-number-lcci](https://leetcode-cn.com/problems/get-kth-magic-number-lcci) | 三指针([Go](LCCI17/get_kth_magic_number.go),[Py](LCCI17/get_kth_magic_number.py)), 小顶堆([Go](LCCI17/get_kth_magic_number2.go),[Py](LCCI17/get_kth_magic_number2.py))| +|22|46|[permutations](https://leetcode-cn.com/problems/permutations) | 递归+回溯([Go](../Week_03/46/permutations.go),[Py](../Week_03/46/permutations.py))| +|23|70|[climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs) | 递推([Go](../Week_01/70/climbing_stairs.go),[Py](../Week_01/70/climbing_stairs.py))| +|24|122|[best-time-to-buy-and-sell-stock-ii](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii) | 贪心([Go](../Week_04/122/best_time_to_buy_and_sell_stock_ii.go),[Py](../Week_04/122/best_time_to_buy_and_sell_stock_ii.py))| +|25|860|[lemonade-change](https://leetcode-cn.com/problems/lemonade-change) | 贪心([Go](../Week_04/860/lemonade_change.go),[Py](../Week_04/860/lemonade_change.py))| +|26|200|[numbers-of-islands](https://leetcode-cn.com/problems/numbers-of-islands) | 深度优先([Go](../Week_04/200/number_of_islands.go),[Py](../Week_04/200/number_of_islands.py))| +|27|367|[valid-perfect-square](https://leetcode-cn.com/problems/valid-perfect-square) | 二分查找([Go](../Week_04/367/valid_perfect_square.go),[Py](../Week_04/367/valid_perfect_square.go))| +|28|169|[majority-element](https://leetcode-cn.com/problems/majority-element) | 哈希表([Go](../Week_03/169/majority_element.go),[Py](../Week_03/169/majority_element.py)),计数投票([Go](../Week_03/169/majority_element2.go),[Py](../Week_03/169/majority_element2.py))| +|29|127|[word-ladder](https://leetcode-cn.com/problems/word-ladder) | 广度优先([Go](../Week_04/127/word_ladder.go)),双向广度优先([Go](../Week_04/127/word_ladder2.go),[Py](../Week_04/127/word_ladder2.py))| +|30|1|[two-sum](https://leetcode-cn.com/problems/two-sum) | 先排序后双指针夹逼([Go](../Week_01/1/two_sum.go)), 字典缓存差值的索引([Go](../Week_01/1/two_sum_2.go),[Py](../Week_01/1/two_sum.py))| +|31|874|[walking-robot-simulation](https://leetcode-cn.com/problems/walking-robot-simulation) | 迭代([Go](../Week_04/874/walking_robot_simulation.go),[Py](../Week_04/874/walking_robot_simulation.py))| +|32|53|[maximum-subarray](https://leetcode-cn.com/problems/maximum-subarray) | 迭代([Go](53/maximum_subarray.go),[Py](53/maximum_subarray.py)),分治([Go](53/maximum_subarray2.go),[Py](53/maximum_subarray2.py))| +|33|1143|[longest-common-subsequence](https://leetcode-cn.com/problems/longest-common-subsequence) | 递归([Go](../Week_06/1143/longest_common_subsequence.go),[Py](../Week_06/1143/longest_common_subsequence.py)),动态规划([Go](../Week_06/1143/longest_common_subsequence2.go),[Py](../Week_06/1143/longest_common_subsequence2.py)),动态规划2([Go](../Week_06/1143/longest_common_subsequence3.go),[Py](../Week_06/1143/longest_common_subsequence3.py))| +|34|74|[search-a-2d-matrix](https://leetcode-cn.com/problems/search-a-2d-matrix) | 二分查找([Go](../Week_04/74/search_a_2d_matrix.go),[Py](../Week_04/74/search_a_2d_matrix.py))| +|35|LCOF5|[replace-space](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) | 新建一个buff([Go](LCOF5/replace_space.go),[Py](LCOF5/replace_space.go))| +|36|64|[minimum-path-sum](https://leetcode-cn.com/problems/minimum-path-sum) | 动态规划([Go](../Week_09/64/minimum_path_sum.go),[Py](../Week_09/64/minimum_path_sum.py))| +|37|322|[coin-change](https://leetcode-cn.com/problems/coin-change) | 递推([Go](../Week_04/322/coin_change.go),[Py](../Week_04/322/coin_change.py)),递归([Go](../Week_04/322/coin_change2.go),[Py](../Week_04/322/coin_change2.py))| +|38|213|[house-robber-ii](https://leetcode-cn.com/problems/house-robber-ii) | 动态规划([Go](../Week_06/213/house_robber_ii.go),[Py](../Week_06/213/house_robber_ii.go))| +|39|589|[n-ary-tree-preorder-traversal](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal) | 递归([Go](../Week_02/589/n_ary_tree_preorder_traversal.go),[Py](../Week_02/589/n_ary_tree_preorder_traversal.go)),栈([Go](../Week_02/589/n_ary_tree_preorder_traversal2.go),[Py](../Week_02/589/n_ary_tree_preorder_traversal2.go))| +|40|363|[max-sum-of-rectangle-no-larger-than-k](https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k) | TODO| +|41|33|[search-in-rotated-sorted-array](https://leetcode-cn.com/problems/search-in-rotated-sorted-array) | 二分查找([Go](../Week_04/33/search_in_rotated_sorted_array.go),[Py](../Week_04/33/search_in_rotated_sorted_array.py))| +|42|212|[word-search-ii](https://leetcode-cn.com/problems/word-search-ii) | 前缀树+回溯([Go](../Week_07/212/word_search_ii.go),[Py](../Week_07/212/word_search_ii.py))| +|43|74|[search-a-2d-matrix](https://leetcode-cn.com/problems/search-a-2d-matrix) | 二分查找([Go](../Week_04/74/search_a_2d_matrix.go),[Py](../Week_04/74/search_a_2d_matrix.py))| +|44|208|[implement-trie-prefix-tree](https://leetcode-cn.com/problems/implement-trie-prefix-tree) | 前缀树([Go](../Week_07/208/implement_trie_prefix_tree.go),[Py](../Week_07/208/implement_trie_prefix_tree.py))| +|45|200|[numbers-of-islands](https://leetcode-cn.com/problems/numbers-of-islands) | 深度优先([Go](../Week_04/200/number_of_islands.go),[Py](../Week_04/200/number_of_islands.py))| +|46|53|[maximum-subarray](https://leetcode-cn.com/problems/maximum-subarray) | 迭代([Go](../Week_06/53/maximum_subarray.go),[Py](../Week_06/53/maximum_subarray.py)),分治([Go](../Week_06/53/maximum_subarray2.go),[Py](../Week_06/53/maximum_subarray2.py))| +|47|127|[word-ladder](https://leetcode-cn.com/problems/word-ladder) | 广度优先([Go](../Week_04/127/word_ladder.go)),双向广度优先([Go](../Week_04/127/word_ladder2.go),[Py](../Week_04/127/word_ladder2.py))| +|48|15|[3sum](https://leetcode-cn.com/problems/3sum) | 双指针夹逼([Go](15/3sum.go),[Py](15/3sum.py))| +|49|91|[decode-ways](https://leetcode-cn.com/problems/decode-ways) | 动态规划([Go](../Week_06/91/decode_ways.go),[Py](../Week_06/91/decode_ways.py))| +|50|547|[friend-circles](https://leetcode-cn.com/problems/friend-circles) | 深度优先([Go](../Week_07/547/friend_circles.go),[Py](../Week_07/547/friend_circles.py)),并查集([Go](../Week_07/547/friend_circles2.go),[Py](../Week_07/547/friend_circles2.py))| +|51|367|[valid-perfect-square](https://leetcode-cn.com/problems/valid-perfect-square) | 二分查找([Go](../Week_04/367/valid_perfect_square.go),[Py](../Week_04/367/valid_perfect_square.go))| +|52|198|[house-robber](https://leetcode-cn.com/problems/house-robber) | 动态规划([Go](../Week_06/198/house_robber.go),[Py](../Week_06/198/house_robber.py))| +|53|190|[reverse_bits](https://leetcode-cn.com/problems/reverse_bits) | 迭代([Go](../Week_08/190/reverse_bits.go),[Py](../Week_08/190/reverse_bits.py)),分治位运算([Go](../Week_08/190/reverse_bits2.go),[Py](../Week_08/190/reverse_bits2.py))| +|54|24|[swap-nodes-in-pairs](https://leetcode-cn.com/problems/swap-nodes-in-pairs)| 迭代([Go](../Week_01/24/swap_nodes_in_pairs2.go),[Py](../Week_01/24/swap_nodes_in_pairs2.py)), 递归([Go](../Week_01/24/swap_nodes_in_pairs.go),[Py](../Week_01/24/swap_nodes_in_pairs.py))| +|55|1122|[relative-sort-array](https://leetcode-cn.com/problems/relative-sort-array)| 计数排序([Go](../Week_08/1122/relative_sort_array.go),[Py](../Week_08/1122/relative_sort_array.py))| +|56|718|[maximum-length-of-repeated-subarray](https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray)| 动态规划([Go](718/maximum_length_of_repeated_subarray.go),[Py](718/maximum_length_of_repeated_subarray.py)),滑动窗口([Go](718/maximum_length_of_repeated_subarray2.go),[Py](718/maximum_length_of_repeated_subarray2.py))| +|57|387|[first-unique-character-in-a-string](https://leetcode-cn.com/problems/first-unique-character-in-a-string)| 迭代([Go](387/first_unique_character_in_a_string.go),[Py](387/first_unique_character_in_a_string.py))| +|58|62|[unique-paths](https://leetcode-cn.com/problems/unique-paths) | 动态规划([Go](../Week_06/62/unique_paths.go),[Py](../Week_06/62/unique_paths.py))| +|59|541|[reverse-string-ii](https://leetcode-cn.com/problems/reverse-string-ii) | 迭代([Go](../Week_09/541/reverse_string_ii.go),[Py](../Week_09/541/reverse_string_ii.py))| +|60|300|[longest-increasing-subsequence](https://leetcode-cn.com/problems/longest-increasing-subsequence) | 动态规划([Go](300/longest_increasing_subsequence.go),[Py](300/longest_increasing_subsequence.py)),贪心+二分搜索([Go](300/longest_increasing_subsequence2.go),[Py](300/longest_increasing_subsequence2.py))| +|61|15|[3sum](https://leetcode-cn.com/problems/3sum) | 双指针夹逼([Go](15/3sum.go),[Py](15/3sum.py))| +|62|680|[valid-palindrome-ii](https://leetcode-cn.com/problems/valid-palindrome-ii) | 双指针夹逼([Go](../Week_09/680/valid_palindrome_ii.go),[Py](../Week_09/680/valid_palindrome_ii.py))| +|63|32|[longest-valid-parentheses](https://leetcode-cn.com/problems/longest-valid-parentheses) | 动态规划([Go](../Week_09/32/longest_valid_parentheses.go),[Py](../Week_09/32/longest_valid_parentheses.py)),栈([Go](../Week_09/32/longest_valid_parentheses2.go),[Py](../Week_09/32/longest_valid_parentheses2.py)),贪心([Go](../Week_09/32/longest_valid_parentheses3.go),[Py](../Week_09/32/longest_valid_parentheses3.py))| +|64|83|[remove-duplicates-from-sorted-list](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list) | 迭代([Go](83/remove_duplicates_from_sorted_list.go),[Py](83/remove_duplicates_from_sorted_list.py))| +|65|120|[triangle](https://leetcode-cn.com/problems/triangle) | 动态规划([Go](../Week_06/120/triangle.go),[Py](../Week_06/120/triangle.py))| +|66|127|[word-ladder](https://leetcode-cn.com/problems/word-ladder) | 广度优先([Go](../Week_04/127/word_ladder.go)),双向广度优先([Go](../Week_04/127/word_ladder2.go),[Py](../Week_04/127/word_ladder2.py))| +|67|46|[permutations](https://leetcode-cn.com/problems/permutations) | 递归([Go](../Week_03/46/permutations.go),[Py](../Week_03/46/permutations.py))| +|68|122|[best-time-to-buy-and-sell-stock-ii](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii) | 贪心([Go](../Week_04/122/best_time_to_buy_and_sell_stock_ii.go),[Py](../Week_04/122/best_time_to_buy_and_sell_stock_ii.py))| +|69|238|[product-of-array-except-self](https://leetcode-cn.com/problems/product-of-array-except-self) | 迭代([Go](238/product_of_array_except_self.go),[Py](238/product_of_array_except_self.py))| +|70|239|[sliding-window-maximum](https://leetcode-cn.com/problems/sliding-window-maximum) | 单调递减队列([Go](../Week_01/239/sliding_window_maximum.go), [Py](../Week_01/239/sliding_window_maximum.py))| + +## 题解 + +### diff --git a/10-week-algorithm-excercise-master/Week_01/1/two_sum.go b/10-week-algorithm-excercise-master/Week_01/1/two_sum.go new file mode 100644 index 0000000000000000000000000000000000000000..44d1db432d88e1b26bf9c18069d9a7c3756b9c5e --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/1/two_sum.go @@ -0,0 +1,44 @@ +package main + +import ( + "sort" +) + +type NumIndex [][2]int + +func (n NumIndex) Len() int { + return len(n) +} + +func (n NumIndex) Less(i, j int) bool { + if n[i][0] <= n[j][0] { + return true + } + return false +} + +func (n NumIndex) Swap(i, j int) { + n[i], n[j] = n[j], n[i] +} + +func twoSum(nums []int, target int) []int { + var numIndex NumIndex + for i, n := range nums { + numIndex = append(numIndex, [2]int{n, i}) + } + sort.Sort(numIndex) + //fmt.Println(numIndex) + i, j := 0, len(numIndex)-1 + for i < j { + s := numIndex[i][0] + numIndex[j][0] + //fmt.Println(i, j, s) + if s == target { + return []int{numIndex[i][1], numIndex[j][1]} + } else if s < target { + i++ + } else { + j-- + } + } + return nil +} diff --git a/10-week-algorithm-excercise-master/Week_01/1/two_sum_2.go b/10-week-algorithm-excercise-master/Week_01/1/two_sum_2.go new file mode 100644 index 0000000000000000000000000000000000000000..61e1828958a2d9239f62d9f4fa875c3b280d4659 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/1/two_sum_2.go @@ -0,0 +1,13 @@ +package main + +func twoSum2(nums []int, target int) []int { + cache := map[int]int{} + for i, n := range nums { + m := target - n + if j, ok := cache[m]; ok { + return []int{j, i} + } + cache[n] = i + } + return nil +} diff --git a/10-week-algorithm-excercise-master/Week_01/11/container_with_most_water.py b/10-week-algorithm-excercise-master/Week_01/11/container_with_most_water.py new file mode 100644 index 0000000000000000000000000000000000000000..9ddbf05281277cc611d0ec747d1f8c4faab29571 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/11/container_with_most_water.py @@ -0,0 +1,29 @@ +from typing import List + + +class Solution: + def maxArea(self, height: List[int]) -> int: + i, j, res = 0, len(height) - 1, 0 + while i < j: + if height[i] <= height[j]: + v = height[i] * (j - i) + i += 1 + else: + v = height[j] * (j - i) + j -= 1 + res = max(res, v) + return res + + def test(self): + for height, target in [ + ([1, 1], 1), + ([1, 1, 2, 3], 3), + ([1, 8, 6, 2, 5, 4, 8, 3, 7], 49), + + ]: + ans = self.maxArea(height) + assert ans == target, f"target {target}, ans {ans}" + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.go b/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.go new file mode 100644 index 0000000000000000000000000000000000000000..36da74af8770f2f2a66e84c5b3aa5b1837656696 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.go @@ -0,0 +1,16 @@ +package main + +func hasCycle(head *ListNode) bool { + if head == nil || head.Next == nil { + return false + } + fast, slow := head.Next, head + for fast != nil && fast.Next != nil { + if fast == slow { + return true + } + fast = fast.Next.Next + slow = slow.Next + } + return false +} diff --git a/10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii_test.go b/10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii_test.go new file mode 100644 index 0000000000000000000000000000000000000000..92e661de3478ebcd5f399da93fa1cd1f9492d346 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii_test.go @@ -0,0 +1,24 @@ +package main + +import "testing" + +func Test(t *testing.T) { + n1 := &ListNode{1, nil} + n2 := &ListNode{2, n1} + n3 := &ListNode{3, n2} + n4 := &ListNode{4, n3} + n5 := &ListNode{5, n4} + n6 := &ListNode{6, n5} + + if detectCycle(n1) != nil { + t.Fatalf("failed") + } + + if detectCycle(n6) != nil { + t.Fatalf("failed") + } + n1.Next = n4 + if detectCycle(n5) != n4 { + t.Fatalf("failed") + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/15/3sum.py b/10-week-algorithm-excercise-master/Week_01/15/3sum.py new file mode 100644 index 0000000000000000000000000000000000000000..a4e22da8b5f02869d5e65a32bd35cf581f96a6b5 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/15/3sum.py @@ -0,0 +1,43 @@ +from typing import List + + +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + nums.sort() + res = [] + for i, a in enumerate(nums[:-2]): + if a > 0: + break + if i > 0 and nums[i - 1] == a: + continue + l, r = i + 1, len(nums) - 1 + while l < r: + s = nums[i] + nums[l] + nums[r] + if s == 0: + res.append([nums[i], nums[l], nums[r]]) + l += 1 + r -= 1 + while l < r and nums[l] == nums[l - 1]: + l += 1 + while l < r and nums[r] == nums[r + 1]: + r -= 1 + elif s < 0: + l += 1 + while l < r and nums[l] == nums[l - 1]: + l += 1 + else: + r -= 1 + while l < r and nums[r] == nums[r + 1]: + r -= 1 + return res + + def test(self): + for nums, target in [ + ([1, 0, -1, -1], [[-1, 0, 1]]), + ]: + ans = self.threeSum(nums) + assert ans == target, f"target: {target}, ans: {ans}" + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/155/min_stack.go b/10-week-algorithm-excercise-master/Week_01/155/min_stack.go new file mode 100644 index 0000000000000000000000000000000000000000..a83d6afdf758d38ea4b4f4ab677efd1e25ec3541 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/155/min_stack.go @@ -0,0 +1,43 @@ +package main + +type MinStack struct { + stack []int + minStack []int +} + +/** initialize your data structure here. */ +func Constructor() MinStack { + return MinStack{} +} + +func (this *MinStack) Push(x int) { + if len(this.minStack) == 0 || this.minStack[len(this.minStack)-1] >= x { + this.minStack = append(this.minStack, x) + } + this.stack = append(this.stack, x) +} + +func (this *MinStack) Pop() { + v := this.stack[len(this.stack)-1] + this.stack = this.stack[:len(this.stack)-1] + if v == this.minStack[len(this.minStack)-1] { + this.minStack = this.minStack[:len(this.minStack)-1] + } +} + +func (this *MinStack) Top() int { + return this.stack[len(this.stack)-1] +} + +func (this *MinStack) GetMin() int { + return this.minStack[len(this.minStack)-1] +} + +/** + * Your MinStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.GetMin(); + */ diff --git a/10-week-algorithm-excercise-master/Week_01/155/min_stack_test.go b/10-week-algorithm-excercise-master/Week_01/155/min_stack_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ff849da6cb831d07a163e1b680f5b9c17dfe3ee7 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/155/min_stack_test.go @@ -0,0 +1,36 @@ +package main + +import ( + "testing" +) + +func Test(t *testing.T) { + stack := Constructor() + stack.Push(3) + if stack.GetMin() != 3 { + t.Fatalf("epected GetMin() 3, got %d\n", stack.GetMin()) + } + stack.Push(1) + stack.Push(-1) + stack.Push(-1) + stack.Push(2) + if stack.GetMin() != -1 { + t.Fatalf("epected GetMin() -1, got %d\n", stack.GetMin()) + } + if stack.Top() != 2 { + t.Fatalf("epected Top 2, got %d\n", stack.Top()) + } + stack.Pop() + stack.Pop() + if stack.GetMin() != -1 { + t.Fatalf("epected GetMin() -1, got %d\n", stack.GetMin()) + } + stack.Pop() + if stack.GetMin() != 1 { + t.Fatalf("epected GetMin() 1, got %d\n", stack.GetMin()) + } + stack.Pop() + if stack.GetMin() != 3 { + t.Fatalf("epected GetMin() 3, got %d\n", stack.GetMin()) + } +} \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/Week_01/189/rotate_array2.go b/10-week-algorithm-excercise-master/Week_01/189/rotate_array2.go new file mode 100644 index 0000000000000000000000000000000000000000..cb0182a379223b69f2cb487a3b3a97d927304fbe --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/189/rotate_array2.go @@ -0,0 +1,19 @@ +package main + +func rotate(nums []int, k int) { + n := len(nums) + k = k % n + + reverse(nums, 0, n-1) + reverse(nums, 0, k-1) + reverse(nums, k, n-1) + +} + +func reverse(nums []int, start, end int) { + for start < end { + nums[start], nums[end] = nums[end], nums[start] + start++ + end-- + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/20/valid_parentheses_test.go b/10-week-algorithm-excercise-master/Week_01/20/valid_parentheses_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f75ed7dacfae8faf9c6a4fefca4c0e3613d7229 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/20/valid_parentheses_test.go @@ -0,0 +1,22 @@ +package main + +import "testing" + +func Test(t *testing.T) { + tests := []struct { + s string + target bool + }{ + {"{", false}, + {"[{", false}, + {"[{}", false}, + {"{}", true}, + {"[{]}", false}, + } + + for _, tt := range tests { + if ans := isValid(tt.s); ans != tt.target { + t.Fatalf("failed! s: %s\n", tt.s) + } + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list2.py b/10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list2.py new file mode 100644 index 0000000000000000000000000000000000000000..00ce1e3cc509cea2031d4def4af23bfb8028d4e0 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/206/reverse_linked_list2.py @@ -0,0 +1,42 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + cur = self.reverseList(head.next) + head.next.next = head + head.next = None + return cur + + def test(self): + node1 = ListNode(1) + node2 = ListNode(2) + node3 = ListNode(3) + node4 = ListNode(4) + + node2.next = node1 + node3.next = node2 + node4.next = node3 + + ans = self.reverseList(node1) + assert ans == node1 + + ans = self.reverseList(node2) + assert ans == node1 + + ans = self.reverseList(node1) + assert ans == node2 + + ans = self.reverseList(node4) + assert ans == node1 + + print("success") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists2.py b/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists2.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae156ad3d4cd2e40ade28872fe21307c48c4f7b --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists2.py @@ -0,0 +1,18 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + if l1 is None: + return l2 + elif l2 is None: + return l1 + elif l1.val < l2.val: + l1.next = self.mergeTwoLists(l1.next, l2) + return l1 + else: + l2.next = self.mergeTwoLists(l2.next, l1) + return l2 diff --git a/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists_test.go b/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists_test.go new file mode 100644 index 0000000000000000000000000000000000000000..39f82404b3155f91e00cc65f0fcc61340d587dd5 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/21/merge_two_sorted_lists_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "testing" +) + +func Test(t *testing.T) { + l4 := &ListNode{Val: 4, Next: nil} + l3 := &ListNode{Val: 3, Next: l4} + l2 := &ListNode{Val: 2, Next: l3} + l1 := &ListNode{Val: 1, Next: l2} + r5 := &ListNode{Val: 5} + r3 := &ListNode{Val: 3, Next: r5} + r1 := &ListNode{Val: 1, Next: r3} + head := mergeTwoLists2(l1, r1) + + for head != nil { + fmt.Printf("%d --> ", head.Val) + head = head.Next + } + fmt.Println() +} diff --git a/10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum.go b/10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum.go new file mode 100644 index 0000000000000000000000000000000000000000..4df5f83f5895190041e50e72e8c7613ef2868dfa --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum.go @@ -0,0 +1,21 @@ +package main + +func maxSlidingWindow(nums []int, k int) []int { + var res, windows []int + + for i, n := range nums { + if len(windows) > 0 && windows[0] <= i-k { + windows = windows[1:] + } + + for len(windows) > 0 && nums[windows[len(windows)-1]] < n { + windows = windows[:len(windows)-1] + } + windows = append(windows, i) + + if i >= k-1 { + res = append(res, nums[windows[0]]) + } + } + return res +} diff --git a/10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum_test.go b/10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8c23f53a050b6aab92ae7e3ed522a7af7e52f278 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/239/sliding_window_maximum_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "reflect" + "testing" +) + +func Test(t *testing.T) { + tests := []struct { + nums []int + k int + target []int + }{ + {[]int{}, 3, nil}, + {[]int{1, 2, 3}, 3, []int{3}}, + {[]int{1, 3, -1, -3, 5, 3, 6, 7}, 3, []int{3, 3, 5, 5, 6, 7}}, + } + + for _, tt := range tests { + if ans := maxSlidingWindow(tt.nums, tt.k); !reflect.DeepEqual(ans, tt.target) { + t.Fatalf("target: %v, ans: %v\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs_test.go b/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs_test.go new file mode 100644 index 0000000000000000000000000000000000000000..539e1ff72164862a0019c48b4b5cee2720481215 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/24/swap_nodes_in_pairs_test.go @@ -0,0 +1,26 @@ +package main + +import "testing" + +func Test(t *testing.T) { + node1 := ListNode{Val: 1} + node2 := ListNode{Val: 2, Next: &node1} + node3 := ListNode{Val: 3, Next: &node2} + node4 := ListNode{Val: 4, Next: &node3} + node5 := ListNode{Val: 5, Next: &node4} + if ans := swapPairs(&node1); ans != &node1 { + t.Fatalf("failed, got %v\n", (*ans).Val) + } + + if ans := swapPairs(&node2); ans != &node1 { + t.Fatalf("failed, got %v\n", (*ans).Val) + } + + if ans := swapPairs(&node1); ans != &node2 { + t.Fatalf("failed, got %v\n", (*ans).Val) + } + + if ans := swapPairs(&node5); ans != &node4 { + t.Fatalf("failed, got %v\n", (*ans).Val) + } +} \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group.py b/10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group.py new file mode 100644 index 0000000000000000000000000000000000000000..4926341bd62874b9151df15facb2186e8ee7c902 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/25/reverse_nodes_in_k_group.py @@ -0,0 +1,56 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def reverseKGroup(self, head: ListNode, k: int) -> ListNode: + dummpy = ListNode(0) + dummpy.next = head + prev = dummpy + fast = slow = head + + while True: + cnt = 1 + + while cnt < k and fast is not None: + fast = fast.next + cnt += 1 + + if fast is None: + break + + prev.next = fast + prev = slow + next_ = slow.next + prev.next = fast.next + + while next_ is not prev.next: + next_.next, next_, slow = slow, next_.next, next_ + + fast = slow = prev.next + + return dummpy.next + + def test(self): + n1 = ListNode(1) + n2 = ListNode(2) + n3 = ListNode(3) + n4 = ListNode(4) + n5 = ListNode(5) + n1.next = n2 + n2.next = n3 + n3.next = n4 + n4.next = n5 + + k = 3 + head = self.reverseKGroup(n1, k) + + while head is not None: + print(f"{head.val}-->", end="") + head = head.next + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array.go b/10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array.go new file mode 100644 index 0000000000000000000000000000000000000000..25074fcf32312bef25e9ed97130f8e0d835f01e4 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array.go @@ -0,0 +1,18 @@ +package main + +func removeDuplicates(nums []int) int { + if len(nums) < 2 { + return len(nums) + } + + preVal := nums[0] + idx := 1 + for i := 1; i < len(nums); i++ { + if nums[i] != preVal { + nums[idx] = nums[i] + idx++ + preVal = nums[i] + } + } + return idx +} diff --git a/10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array.py b/10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array.py new file mode 100644 index 0000000000000000000000000000000000000000..5a8c89b9a7f8b44ebc66d88b566a85bf049f89a0 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/26/remove_duplicates_from_sorted_array.py @@ -0,0 +1,31 @@ +from typing import List + + +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + if not nums: + return 0 + i = 0 + for j in range(1, len(nums)): + if nums[j] != nums[i]: + i += 1 + nums[i] = nums[j] + return i + 1 + + def test(self): + for nums, target in [ + ([], 0), + ([0], 1), + ([0, 0], 1), + ([0, 0, 1], 2), + ([0, 0, 1, 2], 3), + ([0, 0, 1, 2, 2, 2, 3, 4, 4], 5), + ]: + ans = self.removeDuplicates(nums) + assert ans == target, f"target: {target}, ans: {ans}" + + print("all done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_01/283/move_zeros.go b/10-week-algorithm-excercise-master/Week_01/283/move_zeros.go new file mode 100644 index 0000000000000000000000000000000000000000..153c6dbebe5961e8bed3f31dd20ef374dc663842 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/283/move_zeros.go @@ -0,0 +1,22 @@ +package main + +func moveZeroes(nums []int) { + count := 0 + for i, n := range nums { + if n == 0 { + count++ + } else if count > 0 { + nums[i-count], nums[i] = nums[i], 0 + } + } +} + +func moveZeroes2(nums []int) { + j := 0 + for i, n := range nums { + if n != 0 { + nums[i], nums[j] = nums[j], nums[i] + j++ + } + } +} \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/Week_01/283/move_zeros.py b/10-week-algorithm-excercise-master/Week_01/283/move_zeros.py new file mode 100644 index 0000000000000000000000000000000000000000..fd6a23a8e71c2aa67f6ac45e37a106b61c6835d3 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/283/move_zeros.py @@ -0,0 +1,17 @@ +from typing import List + + +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + + count = 0 + for i in range(len(nums)): + if nums[i] == 0: + count += 1 + elif count > 0: + nums[i - count], nums[i] = nums[i], 0 + + diff --git a/10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water_test.go b/10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5b98c96143684ab02efeea831ec1830765ed743d --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/42/trapping_rain_water_test.go @@ -0,0 +1,20 @@ +package main + +import "testing" + +func Test(t *testing.T) { + tests := []struct { + heights []int + target int + }{ + {[]int{0}, 0}, + {[]int{0, 1}, 0}, + {[]int{1, 0, 1}, 1}, + {[]int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}, 6}, + } + for _, tt := range tests { + if ans := trap(tt.heights); ans != tt.target { + t.Fatalf("target: %d, ans: %d\n", tt.target, ans) + } + } +} diff --git a/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque.go b/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque.go new file mode 100644 index 0000000000000000000000000000000000000000..2f7e328241d73a3584f7bc92d2e11e79b16368aa --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque.go @@ -0,0 +1,96 @@ +package main + +type MyCircularDeque0 struct { + size int + len int + head int + tail int + queue []int +} + +/** Initialize your data structure here. Set the size of the deque to be k. */ +func Constructor0(k int) MyCircularDeque0 { + return MyCircularDeque0{ + size: k, + queue: make([]int, k), + } +} + +/** Adds an item at the front of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque0) InsertFront(value int) bool { + if this.IsFull() { + return false + } + this.queue[this.head] = value + this.len++ + this.head = (this.head + 1) % this.size + if this.len == 1 { + this.tail = (this.tail + this.size - 1) % this.size + } + return true +} + +/** Adds an item at the rear of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque0) InsertLast(value int) bool { + if this.IsFull() { + return false + } + this.queue[this.tail] = value + this.len++ + this.tail = (this.tail + this.size - 1) % this.size + if this.len == 1 { + this.head = (this.head + 1) % this.size + } + return true +} + +/** Deletes an item from the front of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque0) DeleteFront() bool { + if this.IsEmpty() { + return false + } + this.head = (this.head + this.size - 1) % this.size + this.len-- + if this.len == 0 { + this.tail = (this.tail + 1) % this.size + } + return true +} + +/** Deletes an item from the rear of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque0) DeleteLast() bool { + if this.IsEmpty() { + return false + } + this.tail = (this.tail + 1) % this.size + this.len-- + if this.len == 0 { + this.head = (this.head + this.size - 1) % this.size + } + return true +} + +func (this *MyCircularDeque0) GetFront() int { + if this.len == 0 { + return -1 + } + return this.queue[(this.head+this.size-1)%this.size] +} + +/** Get the last item from the deque. */ +func (this *MyCircularDeque0) GetRear() int { + if this.len == 0 { + return -1 + } + return this.queue[(this.tail+1)%this.size] +} + +/** Checks whether the circular deque is empty or not. */ +func (this *MyCircularDeque0) IsEmpty() bool { + return this.len == 0 +} + +/** Checks whether the circular deque is full or not. */ +func (this *MyCircularDeque0) IsFull() bool { + return this.len == this.size +} diff --git a/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque2.go b/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque2.go new file mode 100644 index 0000000000000000000000000000000000000000..6b3fabacd661e2ceb6422e7385660b002d1a6dfd --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/641/design_circular_deque2.go @@ -0,0 +1,85 @@ +package main + +type MyCircularDeque struct { + size int + len int + head int + tail int + queue []int +} + +/** Initialize your data structure here. Set the size of the deque to be k. */ +func Constructor(k int) MyCircularDeque { + return MyCircularDeque{ + size: k, + queue: make([]int, k), + } +} + +/** Adds an item at the front of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque) InsertFront(value int) bool { + if this.IsFull() { + return false + } + this.len++ + this.head = (this.head + 1) % this.size + this.queue[this.head] = value + return true +} + +/** Adds an item at the rear of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque) InsertLast(value int) bool { + if this.IsFull() { + return false + } + this.len++ + this.queue[this.tail] = value + this.tail = (this.tail + this.size - 1) % this.size + return true +} + +/** Deletes an item from the front of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque) DeleteFront() bool { + if this.IsEmpty() { + return false + } + this.head = (this.head + this.size - 1) % this.size + this.len-- + return true +} + +/** Deletes an item from the rear of Deque. Return true if the operation is successful. */ +func (this *MyCircularDeque) DeleteLast() bool { + if this.IsEmpty() { + return false + } + this.tail = (this.tail + 1) % this.size + this.len-- + return true +} + +/** Get the front item from the deque. */ +func (this *MyCircularDeque) GetFront() int { + if this.len == 0 { + return -1 + } + return this.queue[this.head] +} + +/** Get the last item from the deque. */ +func (this *MyCircularDeque) GetRear() int { + if this.len == 0 { + return -1 + } + return this.queue[(this.tail+1)%this.size] +} + +/** Checks whether the circular deque is empty or not. */ +func (this *MyCircularDeque) IsEmpty() bool { + return this.len == 0 +} + +/** Checks whether the circular deque is full or not. */ +func (this *MyCircularDeque) IsFull() bool { + return this.len == this.size +} diff --git a/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram3.py b/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram3.py new file mode 100644 index 0000000000000000000000000000000000000000..e8a5db46b973ee1027f2f14d27b869663ef4f2f7 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_01/84/largest_rectangle_in_histogram3.py @@ -0,0 +1,29 @@ +from typing import List + + +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + res = 0 + stack = [] + heights = [0] + heights + [0] + + for i, h in enumerate(heights): + while len(stack) > 1 and h < heights[stack[-1]]: + idx = stack.pop() + res = max(res, heights[idx] * (i - stack[-1] - 1)) + stack.append(i) + return res + + def test(self): + for heights, target in [ + ([], 0), + ([2, 1, 5, 6, 2, 3], 10), + ]: + ans = self.largestRectangleArea(heights) + assert ans == target, f"target: {target}, ans {ans}" + + print("all done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal.py b/10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal.py new file mode 100644 index 0000000000000000000000000000000000000000..5092e734ec4b4c2a4ad0acf39bc3266604edc41f --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal.py @@ -0,0 +1,38 @@ +from typing import List + + +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + res = [] + + def pre_order(node: TreeNode): + if node is not None: + res.append(node.val) + pre_order(node.left) + pre_order(node.right) + + pre_order(root) + return res + + def test(self): + n1 = TreeNode(1) + n2 = TreeNode(2) + n3 = TreeNode(3) + + n1.right = n2 + n2.left = n3 + + ans = self.preorderTraversal(n1) + assert ans == [1, 2, 3], f"ans: {ans}" + print("well done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal2.go b/10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal2.go new file mode 100644 index 0000000000000000000000000000000000000000..4f3d60baa84c2c32c242fd95547da1e28963388f --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/144/binary_tree_preorder_traversal2.go @@ -0,0 +1,21 @@ +package main + +func preorderTraversal2(root *TreeNode) []int { + res := make([]int, 0) + + stack := []*TreeNode{root} + for len(stack) > 0 { + node := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if node != nil { + res = append(res, node.Val) + if node.Right != nil { + stack = append(stack, node.Right) + } + if node.Left != nil { + stack = append(stack, node.Left) + } + } + } + return res +} diff --git a/10-week-algorithm-excercise-master/Week_02/242/valid_anagram.go b/10-week-algorithm-excercise-master/Week_02/242/valid_anagram.go new file mode 100644 index 0000000000000000000000000000000000000000..747364b1e10cff2ec01f19a664a7a12f1af3c8de --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/242/valid_anagram.go @@ -0,0 +1,19 @@ +package main + +func isAnagram(s string, t string) bool { + counter := make([]int, 26) + + for _, c := range s { + counter[c-'a']++ + } + for _, c := range t { + counter[c-'a']-- + } + + for _, i := range counter { + if i != 0 { + return false + } + } + return true +} \ No newline at end of file diff --git a/10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii.go b/10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii.go new file mode 100644 index 0000000000000000000000000000000000000000..681b8c497b5b5eaa1c646bc6c8fa4ba879ed83ba --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii.go @@ -0,0 +1,43 @@ +package main + +import "container/heap" + +type IntHeap []int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } + +func (h *IntHeap) Push(x interface{}) { + // Push and Pop use pointer receivers because they modify the slice's length, + // not just its contents. + *h = append(*h, x.(int)) +} + +func (h *IntHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +func nthUglyNumber(n int) int { + intHeap := &IntHeap{1} + heap.Init(intHeap) + + curr := 1 + seen := map[int]bool{1: true} + factors := []int{2, 3, 5} + for i := 0; i < n; i++ { + curr = heap.Pop(intHeap).(int) + for _, f := range factors { + num := f * curr + if _, ok := seen[num]; !ok { + heap.Push(intHeap, num) + seen[num] = true + } + } + } + return curr +} diff --git a/10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii.py b/10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii.py new file mode 100644 index 0000000000000000000000000000000000000000..a89f48bb6a1d9b854680dc39c3a66cf07c629519 --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/264/ugly_number_ii.py @@ -0,0 +1,31 @@ +import heapq + + +class Solution: + def nthUglyNumber(self, n: int) -> int: + nums = [] + heapq.heappush(nums, 1) + curr = 1 + seen = {1} + for i in range(n): + curr = heapq.heappop(nums) + for f in (2, 3, 5): + n = f * curr + if n not in seen: + seen.add(n) + heapq.heappush(nums, n) + + return curr + + def test(self): + for n, target in [ + (1, 1), + (10, 12), + ]: + ans = self.nthUglyNumber(n) + assert ans == target, f"n: {n}, target: {target}" + print("well done") + + +if __name__ == "__main__": + Solution().test() diff --git a/10-week-algorithm-excercise-master/Week_02/README.md b/10-week-algorithm-excercise-master/Week_02/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4cd25c09f7b97d7fba87eb584978363c336c90cd --- /dev/null +++ b/10-week-algorithm-excercise-master/Week_02/README.md @@ -0,0 +1,72 @@ +学习笔记 + +|#|Title|Solutions| +|---|---|------| +|242|[valid-anagram](https://leetcode-cn.com/problems/anagram) | 数组计数([Go](242/valid_anagram.go),[Py](242/valid_anagram.py))| +|49|[group-anagrams](https://leetcode-cn.com/problems/group-anagrams) | 计数分类([Go](49/group_anagrams.go),[Py](49/group_anagrams.py))| +|94|[binary-tree-inorder-traversal](https://leetcode-cn.com/problems/binary-tree-inorder-traversal) | 递归([Go](94/binary_tree_inorder_traversal.go),[Py](94/binary_tree_inorder_traversal.py)),栈([Go](94/binary_tree_inorder_traversal2.go),[Py](94/binary_tree_inorder_traversal2.py)), Morris遍历([Go](94/binary_tree_inorder_traversal3.go),[Py](94/binary_tree_inorder_traversal3.py))| +|144|[binary-tree-preorder-traversal](https://leetcode-cn.com/problems/binary-tree-preorder-traversal) | 递归([Go](144/binary_tree_preorder_traversal.go),[Py](144/binary_tree_preorder_traversal.py)),栈([Go](144/binary_tree_preorder_traversal2.go),[Py](144/binary_tree_preorder_traversal2.py)), Morris遍历([Go](144/binary_tree_preorder_traversal3.go),[Py](144/binary_tree_preorder_traversal3.py))| +|590|[n-ary-tree-postorder-traversal](https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal) | 递归([Go](590/n_ary_tree_postorder_traversal.go),[Py](590/n_ary_tree_postorder_traversal.go)),栈([Go](590/n_ary_tree_postorder_traversal2.go),[Py](590/n_ary_tree_postorder_traversal2.go))| +|589|[n-ary-tree-preorder-traversal](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal) | 递归([Go](589/n_ary_tree_preorder_traversal.go),[Py](589/n_ary_tree_preorder_traversal.go)),栈([Go](589/n_ary_tree_preorder_traversal2.go),[Py](589/n_ary_tree_preorder_traversal2.go))| +|429|[n-ary-tree-level-order-traversal](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal) | 递归([Go](429/n_ary_tree_level_order_traversal.go),[Py](429/n_ary_tree_level_order_traversal.py)),栈([Go](429/n_ary_tree_level_order_traversal2.go),[Py](429/n_ary_tree_level_order_traversal2.py))| +|LCOF40|[top-k](https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/) | 大顶堆([Go](LCOF40/least_numbers.go),[Py](LCOF40/least_numbers.py)),快速搜索([Go](LCOF40/least_numbers2.go),[Py](LCOF40/least_numbers2.py))| +|264|[ugly-number-ii](https://leetcode-cn.com/problems/ugly-number-ii) | 小顶堆([Go](264/ugly_number_ii.go),[Py](264/ugly_number_ii.py)), 三指针([Go](264/ugly_number_ii2.go),[Py](264/ugly_number_ii2.py))| +|347|[top-k-frequent-elements](https://leetcode-cn.com/problems/top-k-frequent-elements) | 小顶堆([Go](347/top_k_frequent_elements.go),[Py](347/top_k_frequent_elements.go)), 快速搜索([Go](347/top_k_frequent_elements2.go))| + + + +## 题解 + +### 242. valid-anagram + +使用长度为26的数组计数,s++, t-- + + +### 49. group-anagrams + +使用长度为26的数组计数, 相同的即在同一组 + + +### 94. binary-tree-inorder-traversal + +1. 递归 +2. 栈:将所有left和left.left先进栈,pop出最新的一个作为当前节点,再切换到当前节点的right +3. 如果无left,只直接切换到right,否则让root当left的最右子节点的右节点 + +### 144. binary-tree-prorder-traversal + +1. 递归 +2. 栈:right进栈 +3. 如果无left,只直接切换到right,否则让right当left的最右子节点的右节点 + +### 590. n-ary-tree-postorder-traversal + +1. 递归 +2. 栈:先前序后翻转 + +### 589. n-ary-tree-preorder-traversal + +1. 递归 +2. 栈 + +### 429. n-ary-tree-level-order-traversal + +1. 递归 +2. 栈 + + +### LCOF40. top-k + +1. 大顶堆:取前k个数构建大顶堆,后续元素若小于heap[0],则替换之并shift down +2. 快速搜索:利用快排思想,当partition==k时即满足条件 + +### 264. ugly-number-ii + +1. 小顶堆:依次弹出堆顶元素,如果之前没有入堆,则加入堆,第n次弹出的元素即为结果 +2. 三指针:用三个指针依次记录2,3,5因子当前指向的丑数, + + +### 347. top-k-frequent-elements + +1. 小顶堆:取前k个数构建小顶堆,后续元素若大于heap[0],则替换之并shift down +2. 快速搜索:利用快排思想,当partition==k时arr[:k]即结果