From cbe2f3b64eef3ac5419e76a477dda32b5135a593 Mon Sep 17 00:00:00 2001 From: zipingguo Date: Thu, 18 Aug 2016 19:04:44 +0800 Subject: [PATCH 001/274] Create BeEncryptedtoOthers.py --- EasyPractice/BeEncryptedtoOthers.py | 93 +++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 EasyPractice/BeEncryptedtoOthers.py diff --git a/EasyPractice/BeEncryptedtoOthers.py b/EasyPractice/BeEncryptedtoOthers.py new file mode 100644 index 0000000..cf5aa69 --- /dev/null +++ b/EasyPractice/BeEncryptedtoOthers.py @@ -0,0 +1,93 @@ +''' +有一种技巧可以对数据进行加密,它使用一个单词作为它的密匙。 +下面是它的工作原理: +首先,选择一个单词作为密匙,如TRAILBLAZERS。 +如果单词中包含有重复的字母,只保留第1个,其余几个丢弃。 +现在,修改过的那个单词死于字母表的下面,如下所示: +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z +T R A I L B Z E S C D F G H J K M N O P Q U V W X Y +上面其他用字母表中剩余的字母填充完整。 +在对信息进行加密时,信息中的每个字母被固定于顶上那行, +并用下面那行的对应字母一一取代原文的字母(字母字符的大小写状态应该保留)。 +因此,使用这个密匙,Attack AT DAWN(黎明时攻击)就会被加密为Tpptad TP ITVH。 +请实现下述接口,通过指定的密匙和明文得到密文。 +详细描述: +接口说明 +原型: +voidencrypt(char * key,char * data,char * encrypt); +输入参数: + char * key:密匙 + char * data:明文 +输出参数: + char * encrypt:密文 +返回值: + void +''' + +#源码如下: +# -*- coding: utf-8 -*- + +keep = {'A','B','C','D','E','F','G', + 'H','I','J','K','L','M','N', + 'O','P','Q','R','S','T','U', + 'V','W','X','Y','Z'} + + +def bekeyed(key,getdata): + key2 = key.upper() + key3 = key2 + print key3 + getdata2 =getdata.upper() + + letters ={} + i =0 + for l in key3: + kl = letters.values() + if l in kl: + continue + else: + letters[chr(ord('A')+i)] = l + i+=1 + print letters + others = [] + losletter=[] + for qwe in keep: + losletter.append(qwe) + #去除已有的字典的值里面含有的字 + for ls in losletter: + if ls in (letters[w] for w in letters): + continue + else: + others.append(ls) + print others + sequenced =sorted(others) + print sequenced + j=0 + for ls in sorted(keep): + kl = sorted(letters.keys()) + if ls in kl: + continue + else: + letters[ls] =sequenced[j] + j+=1 + print letters + begot=[] + bestring="" + for data in getdata2: + begot.append(letters[data]) + bestring+=letters[data] + print begot + print bestring + return bestring + +def main(): + key = raw_input() + getdata = raw_input() + # key2 = key.upper() + # key3 = key2.split() + # print key3 + encrypt = bekeyed(key,getdata) + print encrypt + +if __name__=='__main__': + main() From 4b6caa53a5e76a71cdfc0cea01d88c184f2495b9 Mon Sep 17 00:00:00 2001 From: zipingguo Date: Thu, 18 Aug 2016 19:14:53 +0800 Subject: [PATCH 002/274] Create LengthOfLastString.py --- EasyPractice/LengthOfLastString.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 EasyPractice/LengthOfLastString.py diff --git a/EasyPractice/LengthOfLastString.py b/EasyPractice/LengthOfLastString.py new file mode 100644 index 0000000..a79c693 --- /dev/null +++ b/EasyPractice/LengthOfLastString.py @@ -0,0 +1,24 @@ +''' +计算字符串最后一个单词的长度,单词以空格隔开。 +知识点 字符串,循环 +运行时间限制 0M +内存限制 0 +输入 +一行字符串,长度小于128。 +输出 +整数N,最后一个单词的长度。 +样例输入 hello world +样例输出 5 +''' + +#源码为: +def countnum(s): + q = s.split(' ')[-1] + return len(q) + +def main(): + s = raw_input() + print countnum(s) + +if __name__ == '__main__': + main() From 2f88ef7bcf79dcf499ab74fd6c3c70d75f2ed57d Mon Sep 17 00:00:00 2001 From: zipingguo Date: Thu, 18 Aug 2016 19:26:14 +0800 Subject: [PATCH 003/274] Create ReverseString.py --- EasyPractice/ReverseString.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 EasyPractice/ReverseString.py diff --git a/EasyPractice/ReverseString.py b/EasyPractice/ReverseString.py new file mode 100644 index 0000000..aaa684d --- /dev/null +++ b/EasyPractice/ReverseString.py @@ -0,0 +1,18 @@ +''' +将一个字符串str的内容颠倒过来,并输出。str的长度不超过100个字符。 +如:输入“I am a student”,输出“tneduts a ma I”。 + +输入参数: +inputString:输入的字符串 +返回值: +输出转换好的逆序字符串 +''' + +#源码如下: + +def main(): + str = raw_input() + print str[::-1] + +if __name__ == '__main__': + main() From 182ab1f846bb632084f32475d38bb2b5bdb15668 Mon Sep 17 00:00:00 2001 From: zipingguo Date: Tue, 6 Sep 2016 23:57:12 +0800 Subject: [PATCH 004/274] Create old.py --- What-I-had/old.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 What-I-had/old.py diff --git a/What-I-had/old.py b/What-I-had/old.py new file mode 100644 index 0000000..0e3cc2a --- /dev/null +++ b/What-I-had/old.py @@ -0,0 +1,3 @@ +''' +for tomorrow +''' From d07bdc5d998330e32b30d9f7d0a4068c8ea22216 Mon Sep 17 00:00:00 2001 From: zipingguo Date: Wed, 7 Sep 2016 00:00:18 +0800 Subject: [PATCH 005/274] I had done last time~ --- What-I-had/Findseven.py | 26 ++++++ What-I-had/Judgesubnet.py | 19 +++++ What-I-had/LCM.py | 21 +++++ What-I-had/ReoranginizePic.py | 13 +++ What-I-had/bekeyed-readme.txt | 24 ++++++ What-I-had/bekeyed.py | 66 +++++++++++++++ What-I-had/cornumpy.py | 9 ++ What-I-had/countmang.py | 71 ++++++++++++++++ What-I-had/countstr.py | 25 ++++++ What-I-had/cuberoot.py | 9 ++ What-I-had/encryanddecry.py | 58 +++++++++++++ What-I-had/framepy.py | 10 +++ What-I-had/getaverage.py | 14 ++++ What-I-had/getcount.py | 38 +++++++++ What-I-had/keybesort.py | 53 ++++++++++++ What-I-had/legalip.py | 20 +++++ What-I-had/snakearry.py | 28 +++++++ What-I-had/studyenglish.py | 64 ++++++++++++++ What-I-had/studyenglishtwo.py | 84 +++++++++++++++++++ ...0\344\270\252\351\225\277\345\272\246.txt" | 10 +++ ...6\344\270\262\351\200\206\345\272\217.txt" | 7 ++ ...1\345\255\227\347\254\246\344\270\262.txt" | 10 +++ 22 files changed, 679 insertions(+) create mode 100644 What-I-had/Findseven.py create mode 100644 What-I-had/Judgesubnet.py create mode 100644 What-I-had/LCM.py create mode 100644 What-I-had/ReoranginizePic.py create mode 100644 What-I-had/bekeyed-readme.txt create mode 100644 What-I-had/bekeyed.py create mode 100644 What-I-had/cornumpy.py create mode 100644 What-I-had/countmang.py create mode 100644 What-I-had/countstr.py create mode 100644 What-I-had/cuberoot.py create mode 100644 What-I-had/encryanddecry.py create mode 100644 What-I-had/framepy.py create mode 100644 What-I-had/getaverage.py create mode 100644 What-I-had/getcount.py create mode 100644 What-I-had/keybesort.py create mode 100644 What-I-had/legalip.py create mode 100644 What-I-had/snakearry.py create mode 100644 What-I-had/studyenglish.py create mode 100644 What-I-had/studyenglishtwo.py create mode 100644 "What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" create mode 100644 "What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" create mode 100644 "What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" diff --git a/What-I-had/Findseven.py b/What-I-had/Findseven.py new file mode 100644 index 0000000..fc29c12 --- /dev/null +++ b/What-I-had/Findseven.py @@ -0,0 +1,26 @@ +def processnum(benum): + countnum = 0 + qms = 0 + if benum < 7: + return countnum + else: + while qms <= benum: + if (qms%7 == 0): + countnum+=1 + elif(qms%10 == 7): + countnum+=1 + elif ((qms/10)%10==7): + countnum+=1 + elif ((qms/100)%10==7): + countnum+=1 + elif ((qms/1000)%10==7): + countnum+=1 + qms+=1 + return countnum-1 + +def main(): + getnum = int(raw_input()) + print processnum(getnum) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/Judgesubnet.py b/What-I-had/Judgesubnet.py new file mode 100644 index 0000000..8bb359c --- /dev/null +++ b/What-I-had/Judgesubnet.py @@ -0,0 +1,19 @@ +def chgngebin(subnet): + subto = [] + qwe = subnet.split('.') + for qas in qwe: + subto.append(bin(int(qas))) + print subto + return 1 + + +def main(): + subnet = raw_input() + # ipadone = raw_input() + # ipadtwo = raw_input() + print judge(subnet,ipadone,ipadtwo) + + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/LCM.py b/What-I-had/LCM.py new file mode 100644 index 0000000..c81474a --- /dev/null +++ b/What-I-had/LCM.py @@ -0,0 +1,21 @@ +def getlcm(numone,numtwo): + befirst =0 + if numone > numtwo: + befirst =numone + else: + befirst = numtwo + while(True): + if (befirst % numone)==0 and (befirst % numtwo)==0: + itis = befirst + break + else: + befirst+=1 + return itis + +def main(): + numone = int(raw_input()) + numtwo = int(raw_input()) + print getlcm(numone,numtwo) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/ReoranginizePic.py b/What-I-had/ReoranginizePic.py new file mode 100644 index 0000000..5ef9eb5 --- /dev/null +++ b/What-I-had/ReoranginizePic.py @@ -0,0 +1,13 @@ +def main(): + inputstr = raw_input() + tobelist = [] + bms = '' + for qsp in inputstr: + tobelist.append(qsp) + tobelist.sort() + for qma in tobelist: + bms = bms + qma + print bms + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/bekeyed-readme.txt b/What-I-had/bekeyed-readme.txt new file mode 100644 index 0000000..ceb4f9b --- /dev/null +++ b/What-I-had/bekeyed-readme.txt @@ -0,0 +1,24 @@ + +有一种技巧可以对数据进行加密,它使用一个单词作为它的密匙。 +下面是它的工作原理: +首先,选择一个单词作为密匙,如TRAILBLAZERS。 +如果单词中包含有重复的字母,只保留第1个,其余几个丢弃。 +现在,修改过的那个单词死于字母表的下面,如下所示: +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z +T R A I L B Z E S C D F G H J K M N O P Q U V W X Y +上面其他用字母表中剩余的字母填充完整。 +在对信息进行加密时,信息中的每个字母被固定于顶上那行, +并用下面那行的对应字母一一取代原文的字母(字母字符的大小写状态应该保留)。 +因此,使用这个密匙,Attack AT DAWN(黎明时攻击)就会被加密为Tpptad TP ITVH。 +请实现下述接口,通过指定的密匙和明文得到密文。 +详细描述: +接口说明 +原型: +voidencrypt(char * key,char * data,char * encrypt); +输入参数: + char * key:密匙 + char * data:明文 +输出参数: + char * encrypt:密文 +返回值: + void \ No newline at end of file diff --git a/What-I-had/bekeyed.py b/What-I-had/bekeyed.py new file mode 100644 index 0000000..e41281f --- /dev/null +++ b/What-I-had/bekeyed.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- + +keep = {'A','B','C','D','E','F','G', + 'H','I','J','K','L','M','N', + 'O','P','Q','R','S','T','U', + 'V','W','X','Y','Z'} + + +def bekeyed(key,getdata): + key2 = key.upper() + key3 = key2 + print key3 + getdata2 =getdata.upper() + + letters ={} + i =0 + for l in key3: + kl = letters.values() + if l in kl: + continue + else: + letters[chr(ord('A')+i)] = l + i+=1 + print letters + others = [] + losletter=[] + for qwe in keep: + losletter.append(qwe) + #去除已有的字典的值里面含有的字 + for ls in losletter: + if ls in (letters[w] for w in letters): + continue + else: + others.append(ls) + print others + sequenced =sorted(others) + print sequenced + j=0 + for ls in sorted(keep): + kl = sorted(letters.keys()) + if ls in kl: + continue + else: + letters[ls] =sequenced[j] + j+=1 + print letters + begot=[] + bestring="" + for data in getdata2: + begot.append(letters[data]) + bestring+=letters[data] + print begot + print bestring + return bestring + +def main(): + key = raw_input() + getdata = raw_input() + # key2 = key.upper() + # key3 = key2.split() + # print key3 + encrypt = bekeyed(key,getdata) + print encrypt + +if __name__=='__main__': + main() \ No newline at end of file diff --git a/What-I-had/cornumpy.py b/What-I-had/cornumpy.py new file mode 100644 index 0000000..3f492e2 --- /dev/null +++ b/What-I-had/cornumpy.py @@ -0,0 +1,9 @@ + + +def main(): + str = raw_input() + print str[::-1] + +#nixuzifuchuan +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/countmang.py b/What-I-had/countmang.py new file mode 100644 index 0000000..863faaa --- /dev/null +++ b/What-I-had/countmang.py @@ -0,0 +1,71 @@ + +def make_wo_dict(s): + words = list(s) + d = {} + for w in words : + if w in d : + d[w]+= 1 + else : + d[w] = 1 + return d + +def becomenum(m,qsmt): + # m = int(qsmt[0])+1 + i=0 + qse ={} + qmses = [] + countw = 0 + while i < m : + qse[i]=qsmt[i] + dgt2 = make_wo_dict(qse[i]) + dgt3 = getevercount(dgt2) + for w in qse[i]: + countw = countw + dgt3[w] + qmses.append(countw) + i+=1 + countw = 0 + return qmses + +def getevercount(done): + lst = [(done[w],w) for w in done] + lst.sort() + lst.reverse() + whut = len(done.keys()) + dtwo ={} + i = 1 + p = 26 + for count,word in lst[:whut]: + dtwo[word]=p + i+=1 + p-=1 + return dtwo + + +def getnum(s): + s = s.lower() + qsm = s.split( ) + i = 1 + qsr = "" + m = int(qsm[0])+1 + while i < m : + qsr = qsr + qsm[i] + i+=1 + return make_wo_dict(qsr) + + +def main(): + str = raw_input() + counstr = int(str) + istr = 0 + onely = [] + while istr < counstr : + onely.append(raw_input()) + istr += 1 + qsms = onely + listf = becomenum(counstr,onely) + for w in listf: + print w + + +if __name__ == '__main__': + main() diff --git a/What-I-had/countstr.py b/What-I-had/countstr.py new file mode 100644 index 0000000..2c8f9cd --- /dev/null +++ b/What-I-had/countstr.py @@ -0,0 +1,25 @@ +def countstrnum(gets): + list =[0,0,0,0] + for w in gets: + if (w>='a' and w<='z')|(w>='A'and w<='Z'): + list[0]+=1 + elif w ==' ': + list[1]+=1 + elif w>='0' and w<='9': + list[2]+=1 + else: + list[3]+=1 + + return list + + + + +def main(): + getstr = raw_input() + listr = countstrnum(getstr) + for qs in listr: + print qs + +if __name__ =='__main__': + main() \ No newline at end of file diff --git a/What-I-had/cuberoot.py b/What-I-had/cuberoot.py new file mode 100644 index 0000000..ffe060c --- /dev/null +++ b/What-I-had/cuberoot.py @@ -0,0 +1,9 @@ +import math +def main(): + getstr = raw_input() + getnum = float(getstr) + qs =('%.1f' % math.pow(getnum,1.0/3)) + print qs + +if __name__ =='__main__': + main() \ No newline at end of file diff --git a/What-I-had/encryanddecry.py b/What-I-had/encryanddecry.py new file mode 100644 index 0000000..91cb1c2 --- /dev/null +++ b/What-I-had/encryanddecry.py @@ -0,0 +1,58 @@ +def encry(strone): + beencry = [] + for w in strone: + if w>='a'and w <='z': + if w =='z': + w ='A' + else: + w = chr(ord(w.upper())+1) + elif w>='A'and w <='Z': + if w =='Z': + w ='a' + else: + w = chr(ord(w.lower())+1) + elif w>='0'and w <='9': + if w == '9': + w ='0' + else: + w = str(int(w)+1) + beencry.append(w) + return beencry + +def deencry(strtwo): + bedecry = [] + for qs in strtwo: + if qs>='a'and qs<='z': + if qs =='a': + qs ='Z' + else: + qs =chr(ord(qs.upper())-1) + elif qs>='A' and qs<='Z': + if qs =='A': + qs ='z' + else: + qs =chr(ord(qs.lower())-1) + elif qs>='0'and qs<='9': + if qs =='0': + qs ='9' + else: + qs = str(int(qs)-1) + bedecry.append(qs) + return bedecry + +def main(): + strone = raw_input() + strtwo = raw_input() + sone ='' + stwo ='' + for wqs in encry(strone): + sone = sone+wqs + #sone=sone+'\0' + for wps in deencry(strtwo): + stwo = stwo+wps + #stwo = stwo+'\0' + print sone + print stwo + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/framepy.py b/What-I-had/framepy.py new file mode 100644 index 0000000..49f134e --- /dev/null +++ b/What-I-had/framepy.py @@ -0,0 +1,10 @@ +def countnum(s): + q = s.split(' ')[-1] + return len(q) + +def main(): + s = raw_input() + print countnum(s) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/getaverage.py b/What-I-had/getaverage.py new file mode 100644 index 0000000..8bf740c --- /dev/null +++ b/What-I-had/getaverage.py @@ -0,0 +1,14 @@ + +def main(): + all = int(raw_input()) + i=0 + qm=0 + while i=0): + echo.append(strone[mtwo:aqw+mtwo]) + aqw-=1 + mtwo+=1 + + pmb = 0 + for w in echo: + pma =0 + if w in strtwo: + pma = len(w) + pmc = echo.index(w) + if pma > pmb : + pmb = pma + pmd = pmc + if pmb>0: + print len(echo[pmd]) + else: + print 0 + +if __name__ == '__main__': + main() diff --git a/What-I-had/keybesort.py b/What-I-had/keybesort.py new file mode 100644 index 0000000..ce34eb6 --- /dev/null +++ b/What-I-had/keybesort.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +keep = {'A','B','C','D','E','F','G', + 'H','I','J','K','L','M','N', + 'O','P','Q','R','S','T','U', + 'V','W','X','Y','Z'} + +def bekeyed(key,getdata): + key3 = key.upper() + getdata2 =getdata.upper() + + letters ={} + i =0 + for l in key3: + kl = letters.values() + if l in kl: + continue + else: + letters[chr(ord('A')+i)] = l + i+=1 + others = [] + losletter=[] + for qwe in keep: + losletter.append(qwe) + for ls in losletter: + if ls in (letters[w] for w in letters): + continue + else: + others.append(ls) + sequenced =sorted(others) + j=0 + for ls in sorted(keep): + kl = sorted(letters.keys()) + if ls in kl: + continue + else: + letters[ls] =sequenced[j] + j+=1 + begot=[] + bestring="" + for data in getdata2: + begot.append(letters[data]) + bestring+=letters[data] + return bestring.lower() + +def main(): + key = raw_input() + getdata = raw_input() + encrypt = bekeyed(key,getdata) + print encrypt + +if __name__=='__main__': + main() \ No newline at end of file diff --git a/What-I-had/legalip.py b/What-I-had/legalip.py new file mode 100644 index 0000000..890e3ef --- /dev/null +++ b/What-I-had/legalip.py @@ -0,0 +1,20 @@ + +def main(): + getip=raw_input() + iplist=getip.split('.') + ipint =[0,0,0,0] + i=0 + m=0 + while i< 4: + ipint[i] = int(iplist[i]) + i+=1 + for qs in ipint: + if qs>=0 and qs<=255: + m+=1 + if m == 4: + print 'YES' + else: + print 'NO' + +if __name__ =='__main__': + main() \ No newline at end of file diff --git a/What-I-had/snakearry.py b/What-I-had/snakearry.py new file mode 100644 index 0000000..aeea5e6 --- /dev/null +++ b/What-I-had/snakearry.py @@ -0,0 +1,28 @@ +import sys + +def putoutsa(intnum): + sort =0 + row = 0 + while sort 0: + return ntoedicone[intnum] + else: + return '' + elif intnum<100 : + return ntoedictwo[intnum / 10] +' '+ processnum(intnum % 10) + elif intnum<1000: + return ntoedicone[intnum/100]+ntoeunit[1]+' '+addandtranslate(intnum%100) + elif intnum<1000000: + return processnum(intnum/1000)+ntoeunit[2]+' '+addandtranslate(intnum%1000) + elif intnum<1000000000: + return processnum(intnum/1000000)+ntoeunit[3]+' '+addandtranslate(intnum%1000000) + elif intnum<10000000000: + return processnum(intnum/1000000000)+ntoeunit[4]+' '+addandtranslate(intnum%1000000000) + else: + return u'\u201c'+'error'+u'\u201d' + + + +def addandtranslate(othernum): + if othernum <20: + if othernum>9: + return 'and '+ntoedicone[othernum] + elif othernum>0: + return 'and '+ ntoedicone[othernum] + else: + return '' + elif othernum <100: + return 'and '+ntoedictwo[othernum / 10] +' '+ ntoedicone[othernum % 10] + elif othernum <1000: + return ntoedicone[othernum/100]+ntoeunit[1] + ' '+addandtranslate(othernum%100) + elif othernum <1000000: + return processnum(othernum/1000)+ntoeunit[2] +' '+ processnum(othernum % 1000) + + +def translatenum(getnum): + for qs in getnum: + if qs < '0' or qs > '9': + return u'\u201c'+'error'+u'\u201d' + intnum = int(getnum) + return processnum(intnum) + + +def main(): + getnum = raw_input() + print translatenum(getnum) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/What-I-had/studyenglishtwo.py b/What-I-had/studyenglishtwo.py new file mode 100644 index 0000000..0b0c181 --- /dev/null +++ b/What-I-had/studyenglishtwo.py @@ -0,0 +1,84 @@ +ntoedicone ={0:'zero',1:'one',2:'two',3:'three',4:'four', + 5:'five',6:'six',7:'seven',8:'eight', + 9:'nine',10:'ten',11:'eleven',12:'twelve', + 13:'thirteen',14:'fourteen',15:'fifteen', + 16:'sixteen',17:'seventeen',18:'eighteen', + 19:'nineteen'} + +ntoedictwo = {2:'twenty',3:'thirty',4:'forty',5:'fifty', + 6:'sixty',7:'seventy',8:'eighty',9:'ninety'} + +ntoeunit = {0:'',1:' hundred',2:' thousand',3:' million',4:' billion',5:'and'} + +def processnum(intnum): + if intnum <20: + if intnum >0: + return ntoedicone[intnum] + else: + return '' + elif intnum<100 : + if (intnum %10)==0: + return ntoedictwo[intnum / 10] + else: + return ntoedictwo[intnum / 10] +' '+ processnum(intnum % 10) + elif intnum<1000: + if (intnum%100)==0: + return ntoedicone[intnum/100]+ntoeunit[1] + else: + return ntoedicone[intnum/100]+ntoeunit[1]+' and '+addandtranslate(intnum%100) + elif intnum<1000000: + if (intnum%1000)==0: + return processnum(intnum/1000)+ntoeunit[2] + else: + return processnum(intnum/1000)+ntoeunit[2]+' '+addandtranslate(intnum%1000) + elif intnum<1000000000: + if (intnum%1000000)==0: + return processnum(intnum/1000000)+ntoeunit[3] + else: + return processnum(intnum/1000000)+ntoeunit[3]+' '+addandtranslate(intnum%1000000) + elif intnum<10000000000: + if (intnum%1000000000)==0: + return processnum(intnum/1000000000)+ntoeunit[4] + else: + return processnum(intnum/1000000000)+ntoeunit[4]+' '+addandtranslate(intnum%1000000000) + else: + return u'\u201c'+'error'+u'\u201d' + + + +def addandtranslate(othernum): + if othernum <20: + if othernum>9: + return ntoedicone[othernum] + elif othernum>0: + return ntoedicone[othernum] + else: + return '' + elif othernum <100: + if (othernum%10)==0: + return ntoedictwo[othernum / 10] + else: + return ntoedictwo[othernum / 10] +' '+ ntoedicone[othernum % 10] + elif othernum <1000: + if (othernum%100)==0: + return ntoedicone[othernum/100]+ntoeunit[1] + else: + return ntoedicone[othernum/100]+ntoeunit[1] + ' and '+addandtranslate(othernum%100) + elif othernum <1000000: + return processnum(othernum/1000)+ntoeunit[2] +' '+ processnum(othernum % 1000) + + +def translatenum(getnum): + for qs in getnum: + if qs < '0' or qs > '9': + return u'\u201c'+'error'+u'\u201d' + intnum = int(getnum) + return processnum(intnum) + +def main(): + getnum = raw_input() + print translatenum(getnum) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git "a/What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" "b/What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" new file mode 100644 index 0000000..7d70ed6 --- /dev/null +++ "b/What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" @@ -0,0 +1,10 @@ +计算字符串最后一个单词的长度,单词以空格隔开。 +知识点 字符串,循环 +运行时间限制 0M +内存限制 0 +输入 +一行字符串,长度小于128。 +输出 +整数N,最后一个单词的长度。 +样例输入 hello world +样例输出 5 \ No newline at end of file diff --git "a/What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" "b/What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" new file mode 100644 index 0000000..ceab91c --- /dev/null +++ "b/What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" @@ -0,0 +1,7 @@ +将一个字符串str的内容颠倒过来,并输出。str的长度不超过100个字符。 +如:输入“I am a student”,输出“tneduts a ma I”。 + +输入参数: +inputString:输入的字符串 +返回值: +输出转换好的逆序字符串 \ No newline at end of file diff --git "a/What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" "b/What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" new file mode 100644 index 0000000..c891c86 --- /dev/null +++ "b/What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" @@ -0,0 +1,10 @@ +计算两个字符串的最大公共字串的长度,字符不区分大小写 +详细描述: +接口说明 +原型: +int getCommonStrLength(char * pFirstStr, char * pSecondStr); +输入参数: + + char * pFirstStr //第一个字符串 + + char * pSecondStr//第二个字符串 \ No newline at end of file From 93ee226f98fa130faf82c6452e49f5b1b3601679 Mon Sep 17 00:00:00 2001 From: zipingguo Date: Wed, 7 Sep 2016 10:58:26 +0800 Subject: [PATCH 006/274] Create one.py --- hsd/one.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 hsd/one.py diff --git a/hsd/one.py b/hsd/one.py new file mode 100644 index 0000000..82f4272 --- /dev/null +++ b/hsd/one.py @@ -0,0 +1,47 @@ + +# coding: utf8 + +''' +大家知道,Microsoft的Excel的列编号是字符编号: +a, b, c, ... z, aa, ab, ac ... az, ba...zz, aaa, aab, aac..等, +而其对应的数字编号是1, 2, 3...26, 27, 28, 29 .... +请实现转换算法,输入字符编号,输出数字编号。 + + +Created on 2016年9月7日 + +@author: hust +''' + + +# +# +# +def ProcessStr(mystr): + + def StrtoNum(ones): + if ones < 'a' or ones >'z': + return '' + else: + return int(ord(ones)-96) + + mystr =mystr.lower() + lengthS = len(mystr) + tempr = 0 + lastcome=0 + hostm =[] + hostm = list(mystr) + while(tempr Date: Wed, 7 Sep 2016 10:58:49 +0800 Subject: [PATCH 007/274] Create two.py --- hsd/two.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 hsd/two.py diff --git a/hsd/two.py b/hsd/two.py new file mode 100644 index 0000000..09c9a56 --- /dev/null +++ b/hsd/two.py @@ -0,0 +1,29 @@ +def main(): + captery = raw_input() + liststr = captery.split(' ') + allnum = str(liststr[1]) + allnum = int(allnum) + print allnum + + statem = 0 + carnum = 0 + while(statem==0): + strms=raw_input() + if strms =="end": + break + elif strms =="in": + if(carnum 0: + carnum=carnum-1 + else: + carnum=0 + + +if __name__=="__main__": + main() From cba677aedabbb05b1e13f29f0ee77321699f5489 Mon Sep 17 00:00:00 2001 From: zipingguo Date: Wed, 7 Sep 2016 10:59:12 +0800 Subject: [PATCH 008/274] Create third.py --- hsd/third.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 hsd/third.py diff --git a/hsd/third.py b/hsd/third.py new file mode 100644 index 0000000..551eae6 --- /dev/null +++ b/hsd/third.py @@ -0,0 +1,40 @@ +# coding: utf8 + +''' +Created on 2016��9��7�� + +@author: hust +''' + +def main(): + yourstr = raw_input() + mylist = [] + mylist = list(yourstr) + length = len(yourstr) + laststr = [] + nums =0 + statem =0 + for qre in mylist: + if qre =='*': + nums+=1 + if statem==0: + laststr.append(qre) + else: + continue + + else: + laststr.append(qre) + + statem+=1 + + + if mylist[length-1]=='*': + laststr.append('*') + ms ='' + for agf in laststr: + ms=ms+agf + print ms + + +if __name__=='__main__': + main() From c396132e04b7a57b7104d6b8d94ddae4b2f5ea8d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Jan 2018 20:19:09 +0800 Subject: [PATCH 009/274] Upload some algorithms about disk scheduling FCFS,SSTF,SCAN,CSCAN --- Disk Scheduling Algorithm/readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Disk Scheduling Algorithm/readme.md diff --git a/Disk Scheduling Algorithm/readme.md b/Disk Scheduling Algorithm/readme.md new file mode 100644 index 0000000..b718dac --- /dev/null +++ b/Disk Scheduling Algorithm/readme.md @@ -0,0 +1,13 @@ +## Disk Scheduling Algorithm + +The file named **FcfsAlgo.java** is about FCFS(First Come First Serve) Algorithm + +The file named **SstfAlgo.java** is about SSTF(Shortest Seek Time First) Algorithm + +The file named **ScanAlgo.java** is about SCAN Algorithm +It can be discribed like this picture : +![SCAN Algorithm](http://osaussnqu.bkt.clouddn.com/image/system/scanAlgo.png) + +The file named **CscanAlgo.java** is about CSCAN Algorithm +It can be discribed like this picture : +![CSCAN Algorithm](http://osaussnqu.bkt.clouddn.com/image/system/cscanAlgo.png) From 9234a34ae8109d1551093de484460ae39a92b778 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Jan 2018 20:20:55 +0800 Subject: [PATCH 010/274] Upload four algorithm about disk scheduling --- Disk Scheduling Algorithm/CscanAlgo.java | 109 ++++++++++++++++++++++ Disk Scheduling Algorithm/FcfsAlgo.java | 54 +++++++++++ Disk Scheduling Algorithm/ScanAlgo.java | 110 +++++++++++++++++++++++ Disk Scheduling Algorithm/SstfAlgo.java | 70 +++++++++++++++ 4 files changed, 343 insertions(+) create mode 100644 Disk Scheduling Algorithm/CscanAlgo.java create mode 100644 Disk Scheduling Algorithm/FcfsAlgo.java create mode 100644 Disk Scheduling Algorithm/ScanAlgo.java create mode 100644 Disk Scheduling Algorithm/SstfAlgo.java diff --git a/Disk Scheduling Algorithm/CscanAlgo.java b/Disk Scheduling Algorithm/CscanAlgo.java new file mode 100644 index 0000000..c635659 --- /dev/null +++ b/Disk Scheduling Algorithm/CscanAlgo.java @@ -0,0 +1,109 @@ +package System; + +public class CscanAlgo { + public static void main(String[] args){ + + int[] fixedataA = {29,84,8,89,1,94}; + int fixedcurrent = 42; + System.out.println("当前磁道位置:"+fixedcurrent); + for(int i=0;idataA[tj]){ + tempd = dataA[ti]; + dataA[ti] = dataA[tj]; + dataA[tj] = tempd; + } + } + } + //判断当前磁头所在位置 + for(int ti=0;ticurrent){ + sortIndex = ti; + break; + }else if(ti == processlen-1){ + sortIndex = processlen; + } + //否则当前磁头位置最小 + } + int allcount=0; + int step=0; + int countnum=0; + //若磁道位置不在开头也不在结尾 + if(sortIndex!=0 && sortIndex!=processlen){ + if(direction == 0){ + //先小后大 从大到小 + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + for(int ts =processlen-1;ts>=sortIndex;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else{ + //先大后小 + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + + for(int ts=0;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + }else if(sortIndex==0 ||sortIndex==processlen){ + //若磁头在位置开头或者在位置结尾 + if(direction == 0){ + for(int ts=processlen-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else{ + for(int ts =0;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } +} diff --git a/Disk Scheduling Algorithm/FcfsAlgo.java b/Disk Scheduling Algorithm/FcfsAlgo.java new file mode 100644 index 0000000..e0e588b --- /dev/null +++ b/Disk Scheduling Algorithm/FcfsAlgo.java @@ -0,0 +1,54 @@ +package System; + +import java.util.Random; + +public class FcfsAlgo { + public static void main(String[] args){ +// int maxran = 100; +// int minran =1; +// int totalnum = 6; +// int tempdata =0; +// int[] dataArray = new int[6]; +// Random trandom = new Random(); +// int currentdata = trandom.nextInt(maxran)%(maxran-minran+1) + minran; +//// 生成初始磁道位置 +// System.out.println("当前磁道位置:"+currentdata); +// for(int i=0;i"+dataA[0]+" 移动"+step+"次"); + allcount = allcount+step; + for(int i=0;i"+dataA[i+1]+" 移动"+step+"次"); + allcount+= step; + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } +} diff --git a/Disk Scheduling Algorithm/ScanAlgo.java b/Disk Scheduling Algorithm/ScanAlgo.java new file mode 100644 index 0000000..e81826b --- /dev/null +++ b/Disk Scheduling Algorithm/ScanAlgo.java @@ -0,0 +1,110 @@ +package System; + +public class ScanAlgo { + public static void main(String[] args){ + + int[] fixedataA = {29,84,8,89,1,94}; + int fixedcurrent = 42; +// int[] fixedataA = {65,68,49,28,100,170,160,48,194}; +// int fixedcurrent = 110; + System.out.println("当前磁道位置:"+fixedcurrent); + for(int i=0;idataA[tj]){ + tempd = dataA[ti]; + dataA[ti] = dataA[tj]; + dataA[tj] = tempd; + } + } + } + //判断当前磁头所在位置 + for(int ti=0;ticurrent){ + sortIndex = ti; + break; + }else if(ti == processlen-1){ + sortIndex = processlen; + } + //否则当前磁头位置最小 + } + int allcount=0; + int step=0; + int countnum=0; + //若磁道位置不在开头也不在结尾 + if(sortIndex!=0 && sortIndex!=processlen){ + if(direction == 0){ + //先小后大 + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else{ + //先大后小 + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + }else if(sortIndex==0){ + //若磁头在位置开头 + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else if(sortIndex==processlen){ + //若磁道在位置结尾 + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } +} diff --git a/Disk Scheduling Algorithm/SstfAlgo.java b/Disk Scheduling Algorithm/SstfAlgo.java new file mode 100644 index 0000000..a88afd8 --- /dev/null +++ b/Disk Scheduling Algorithm/SstfAlgo.java @@ -0,0 +1,70 @@ +package System; + +import java.util.Random; + +public class SstfAlgo { + public static void main(String[] args){ +// int maxran = 100; +// int minran =1; +// int totalnum = 6; +// int tempdata =0; +// int[] dataArray = new int[totalnum]; +// Random trandom = new Random(); +// int currentdata = trandom.nextInt(maxran)%(maxran-minran+1) + minran; +//// 生成初始磁道位置 +// System.out.println("当前磁道位置:"+currentdata); +// for(int i=0;i Math.abs(dataA[j]-current)){ + tempmove = dataA[j]; + ChosedIndex = j; + } + } + } + accessList[i] = tempmove; + step = Math.abs(tempmove - current); + System.out.println(i+1+": "+ current+"---->"+tempmove+" 移动"+step+"次"); + allcount+= step; + dataA[ChosedIndex] = -1; + current = tempmove; + tempmove = 1000; + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } + +} From 1c7d6a5865758725ebbae1e6934961db6dabb72e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Jan 2018 20:42:06 +0800 Subject: [PATCH 011/274] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E7=9A=84=E6=8F=8F=E8=BF=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8518353..a4e25d6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,4 @@ -# HuaWeiOJAlgorithm -Some algorithms from learning HuaWeiOJ +# Algorithm Prictice + +This project was originally set up to practice the algorithms on the OJ platform, and then summarized some understanding and connection about algorithms. + From 68c0ad48fcac27af770766c692b650023e1ddd3d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Jan 2018 20:45:45 +0800 Subject: [PATCH 012/274] Create LICENSE --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d197a26 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 SkylineBin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From de8ebbb987c4190a3fd50fdbd7059df6b10a0546 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 3 Aug 2018 14:47:55 +0800 Subject: [PATCH 013/274] move some files to the HuaWeiOJAlgorithms files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将部分 Python 实现的OJ 平台算法移动到 HuaWeiOJ Algorithms 文件夹中 --- .../EasyPractice}/BeEncryptedtoOthers.py | 0 .../EasyPractice}/LengthOfLastString.py | 0 .../EasyPractice}/ReverseString.py | 0 .../What-I-had}/Findseven.py | 0 .../What-I-had}/Judgesubnet.py | 0 {What-I-had => HuaWeiOJ Algorithms/What-I-had}/LCM.py | 0 .../What-I-had}/ReoranginizePic.py | 0 .../What-I-had}/bekeyed-readme.txt | 0 .../What-I-had}/bekeyed.py | 0 .../What-I-had}/cornumpy.py | 0 .../What-I-had}/countmang.py | 0 .../What-I-had}/countstr.py | 0 .../What-I-had}/cuberoot.py | 0 .../What-I-had}/encryanddecry.py | 0 .../What-I-had}/framepy.py | 0 .../What-I-had}/getaverage.py | 0 .../What-I-had}/getcount.py | 0 .../What-I-had}/keybesort.py | 0 .../What-I-had}/legalip.py | 0 {What-I-had => HuaWeiOJ Algorithms/What-I-had}/old.py | 0 .../What-I-had}/snakearry.py | 0 .../What-I-had}/studyenglish.py | 0 .../What-I-had}/studyenglishtwo.py | 0 ...\344\270\200\344\270\252\351\225\277\345\272\246.txt" | 0 ...\347\254\246\344\270\262\351\200\206\345\272\217.txt" | 0 ...\345\205\261\345\255\227\347\254\246\344\270\262.txt" | 0 {hsd => HuaWeiOJ Algorithms/hsd}/one.py | 0 {hsd => HuaWeiOJ Algorithms/hsd}/third.py | 0 {hsd => HuaWeiOJ Algorithms/hsd}/two.py | 0 README.md | 9 ++++++++- 30 files changed, 8 insertions(+), 1 deletion(-) rename {EasyPractice => HuaWeiOJ Algorithms/EasyPractice}/BeEncryptedtoOthers.py (100%) rename {EasyPractice => HuaWeiOJ Algorithms/EasyPractice}/LengthOfLastString.py (100%) rename {EasyPractice => HuaWeiOJ Algorithms/EasyPractice}/ReverseString.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/Findseven.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/Judgesubnet.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/LCM.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/ReoranginizePic.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/bekeyed-readme.txt (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/bekeyed.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/cornumpy.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/countmang.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/countstr.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/cuberoot.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/encryanddecry.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/framepy.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/getaverage.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/getcount.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/keybesort.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/legalip.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/old.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/snakearry.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/studyenglish.py (100%) rename {What-I-had => HuaWeiOJ Algorithms/What-I-had}/studyenglishtwo.py (100%) rename "What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" => "HuaWeiOJ Algorithms/What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" (100%) rename "What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" => "HuaWeiOJ Algorithms/What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" (100%) rename "What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" => "HuaWeiOJ Algorithms/What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" (100%) rename {hsd => HuaWeiOJ Algorithms/hsd}/one.py (100%) rename {hsd => HuaWeiOJ Algorithms/hsd}/third.py (100%) rename {hsd => HuaWeiOJ Algorithms/hsd}/two.py (100%) diff --git a/EasyPractice/BeEncryptedtoOthers.py b/HuaWeiOJ Algorithms/EasyPractice/BeEncryptedtoOthers.py similarity index 100% rename from EasyPractice/BeEncryptedtoOthers.py rename to HuaWeiOJ Algorithms/EasyPractice/BeEncryptedtoOthers.py diff --git a/EasyPractice/LengthOfLastString.py b/HuaWeiOJ Algorithms/EasyPractice/LengthOfLastString.py similarity index 100% rename from EasyPractice/LengthOfLastString.py rename to HuaWeiOJ Algorithms/EasyPractice/LengthOfLastString.py diff --git a/EasyPractice/ReverseString.py b/HuaWeiOJ Algorithms/EasyPractice/ReverseString.py similarity index 100% rename from EasyPractice/ReverseString.py rename to HuaWeiOJ Algorithms/EasyPractice/ReverseString.py diff --git a/What-I-had/Findseven.py b/HuaWeiOJ Algorithms/What-I-had/Findseven.py similarity index 100% rename from What-I-had/Findseven.py rename to HuaWeiOJ Algorithms/What-I-had/Findseven.py diff --git a/What-I-had/Judgesubnet.py b/HuaWeiOJ Algorithms/What-I-had/Judgesubnet.py similarity index 100% rename from What-I-had/Judgesubnet.py rename to HuaWeiOJ Algorithms/What-I-had/Judgesubnet.py diff --git a/What-I-had/LCM.py b/HuaWeiOJ Algorithms/What-I-had/LCM.py similarity index 100% rename from What-I-had/LCM.py rename to HuaWeiOJ Algorithms/What-I-had/LCM.py diff --git a/What-I-had/ReoranginizePic.py b/HuaWeiOJ Algorithms/What-I-had/ReoranginizePic.py similarity index 100% rename from What-I-had/ReoranginizePic.py rename to HuaWeiOJ Algorithms/What-I-had/ReoranginizePic.py diff --git a/What-I-had/bekeyed-readme.txt b/HuaWeiOJ Algorithms/What-I-had/bekeyed-readme.txt similarity index 100% rename from What-I-had/bekeyed-readme.txt rename to HuaWeiOJ Algorithms/What-I-had/bekeyed-readme.txt diff --git a/What-I-had/bekeyed.py b/HuaWeiOJ Algorithms/What-I-had/bekeyed.py similarity index 100% rename from What-I-had/bekeyed.py rename to HuaWeiOJ Algorithms/What-I-had/bekeyed.py diff --git a/What-I-had/cornumpy.py b/HuaWeiOJ Algorithms/What-I-had/cornumpy.py similarity index 100% rename from What-I-had/cornumpy.py rename to HuaWeiOJ Algorithms/What-I-had/cornumpy.py diff --git a/What-I-had/countmang.py b/HuaWeiOJ Algorithms/What-I-had/countmang.py similarity index 100% rename from What-I-had/countmang.py rename to HuaWeiOJ Algorithms/What-I-had/countmang.py diff --git a/What-I-had/countstr.py b/HuaWeiOJ Algorithms/What-I-had/countstr.py similarity index 100% rename from What-I-had/countstr.py rename to HuaWeiOJ Algorithms/What-I-had/countstr.py diff --git a/What-I-had/cuberoot.py b/HuaWeiOJ Algorithms/What-I-had/cuberoot.py similarity index 100% rename from What-I-had/cuberoot.py rename to HuaWeiOJ Algorithms/What-I-had/cuberoot.py diff --git a/What-I-had/encryanddecry.py b/HuaWeiOJ Algorithms/What-I-had/encryanddecry.py similarity index 100% rename from What-I-had/encryanddecry.py rename to HuaWeiOJ Algorithms/What-I-had/encryanddecry.py diff --git a/What-I-had/framepy.py b/HuaWeiOJ Algorithms/What-I-had/framepy.py similarity index 100% rename from What-I-had/framepy.py rename to HuaWeiOJ Algorithms/What-I-had/framepy.py diff --git a/What-I-had/getaverage.py b/HuaWeiOJ Algorithms/What-I-had/getaverage.py similarity index 100% rename from What-I-had/getaverage.py rename to HuaWeiOJ Algorithms/What-I-had/getaverage.py diff --git a/What-I-had/getcount.py b/HuaWeiOJ Algorithms/What-I-had/getcount.py similarity index 100% rename from What-I-had/getcount.py rename to HuaWeiOJ Algorithms/What-I-had/getcount.py diff --git a/What-I-had/keybesort.py b/HuaWeiOJ Algorithms/What-I-had/keybesort.py similarity index 100% rename from What-I-had/keybesort.py rename to HuaWeiOJ Algorithms/What-I-had/keybesort.py diff --git a/What-I-had/legalip.py b/HuaWeiOJ Algorithms/What-I-had/legalip.py similarity index 100% rename from What-I-had/legalip.py rename to HuaWeiOJ Algorithms/What-I-had/legalip.py diff --git a/What-I-had/old.py b/HuaWeiOJ Algorithms/What-I-had/old.py similarity index 100% rename from What-I-had/old.py rename to HuaWeiOJ Algorithms/What-I-had/old.py diff --git a/What-I-had/snakearry.py b/HuaWeiOJ Algorithms/What-I-had/snakearry.py similarity index 100% rename from What-I-had/snakearry.py rename to HuaWeiOJ Algorithms/What-I-had/snakearry.py diff --git a/What-I-had/studyenglish.py b/HuaWeiOJ Algorithms/What-I-had/studyenglish.py similarity index 100% rename from What-I-had/studyenglish.py rename to HuaWeiOJ Algorithms/What-I-had/studyenglish.py diff --git a/What-I-had/studyenglishtwo.py b/HuaWeiOJ Algorithms/What-I-had/studyenglishtwo.py similarity index 100% rename from What-I-had/studyenglishtwo.py rename to HuaWeiOJ Algorithms/What-I-had/studyenglishtwo.py diff --git "a/What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" "b/HuaWeiOJ Algorithms/What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" similarity index 100% rename from "What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" rename to "HuaWeiOJ Algorithms/What-I-had/\345\255\227\347\254\246\344\270\262\346\234\200\345\220\216\344\270\200\344\270\252\351\225\277\345\272\246.txt" diff --git "a/What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" "b/HuaWeiOJ Algorithms/What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" similarity index 100% rename from "What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" rename to "HuaWeiOJ Algorithms/What-I-had/\345\255\227\347\254\246\344\270\262\351\200\206\345\272\217.txt" diff --git "a/What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" "b/HuaWeiOJ Algorithms/What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" similarity index 100% rename from "What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" rename to "HuaWeiOJ Algorithms/What-I-had/\350\256\241\347\256\227\345\205\254\345\205\261\345\255\227\347\254\246\344\270\262.txt" diff --git a/hsd/one.py b/HuaWeiOJ Algorithms/hsd/one.py similarity index 100% rename from hsd/one.py rename to HuaWeiOJ Algorithms/hsd/one.py diff --git a/hsd/third.py b/HuaWeiOJ Algorithms/hsd/third.py similarity index 100% rename from hsd/third.py rename to HuaWeiOJ Algorithms/hsd/third.py diff --git a/hsd/two.py b/HuaWeiOJ Algorithms/hsd/two.py similarity index 100% rename from hsd/two.py rename to HuaWeiOJ Algorithms/hsd/two.py diff --git a/README.md b/README.md index a4e25d6..e34a437 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,11 @@ # Algorithm Prictice -This project was originally set up to practice the algorithms on the OJ platform, and then summarized some understanding and connection about algorithms. +This project was originally set up to practice the algorithms on the OJ platform, and then summarized some understanding and connection about algorithms. + + +# HuaWeiOJ Algorithms + +Some algorithms solved by Python2.7 from HuaWeiOJ Projects + + From a156be4023204e7046b6b3e7106ddd346b24aa50 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 20 Aug 2018 16:51:11 +0800 Subject: [PATCH 014/274] add Stack Structure with JavaScript --- DataStructures/README.md | 7 +++ DataStructures/Stack/CreateStack.js | 51 +++++++++++++++++++++ DataStructures/Stack/UseES6Stack.js | 22 +++++++++ DataStructures/Stack/UseStack.js | 71 +++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+) create mode 100644 DataStructures/README.md create mode 100644 DataStructures/Stack/CreateStack.js create mode 100644 DataStructures/Stack/UseES6Stack.js create mode 100644 DataStructures/Stack/UseStack.js diff --git a/DataStructures/README.md b/DataStructures/README.md new file mode 100644 index 0000000..d4d6469 --- /dev/null +++ b/DataStructures/README.md @@ -0,0 +1,7 @@ +# DataStructures + +This contents includes Stack, Tickets.... + +## Stack + +Using JavaScript to create the Stack Structure \ No newline at end of file diff --git a/DataStructures/Stack/CreateStack.js b/DataStructures/Stack/CreateStack.js new file mode 100644 index 0000000..a8b9618 --- /dev/null +++ b/DataStructures/Stack/CreateStack.js @@ -0,0 +1,51 @@ + +/** + * @author SkylineBin + * @Time 2018-8-20 + * @function Create a Stack Structure + */ + module.exports = class Stack { + + constructor () { + // using a Array items to store Stack Datas + this.items = []; + } + + // push a element data into this stack + push(element) { + this.items.push(element); + } + + // pop a data from this stack then return this data + pop () { + return this.items.pop(); + } + + // return the stack top data + peek () { + return this.items[this.items.length - 1]; + } + + // check this stack is empty + isEmpty () { + return this.items.length == 0; + } + + // get the length of this stack + size () { + return this.items.length; + } + + // clear this stack + clear () { + this.items = []; + } + + // print this stack + print () { + console.log(this.items.toString()); + } + + + +} diff --git a/DataStructures/Stack/UseES6Stack.js b/DataStructures/Stack/UseES6Stack.js new file mode 100644 index 0000000..dedc992 --- /dev/null +++ b/DataStructures/Stack/UseES6Stack.js @@ -0,0 +1,22 @@ +/** + * @author SkylineBin + * @time 2018-8-20 + * @function Using Stack with Es6 + */ + +var Stack = require('./CreateStack'); + +console.log(Stack); + +var stack = new Stack(); +console.log(stack.isEmpty()); + +// push data into this stack +stack.push(5); +stack.push(8); + +console.log(stack.peek()); + +stack.push(7); +console.log(stack.size()); +console.log(stack.isEmpty()); \ No newline at end of file diff --git a/DataStructures/Stack/UseStack.js b/DataStructures/Stack/UseStack.js new file mode 100644 index 0000000..0f4c620 --- /dev/null +++ b/DataStructures/Stack/UseStack.js @@ -0,0 +1,71 @@ + +/** + * @author SkylineBin + * @time 2018-8-20 + * @function Using Stack + */ + +function Stack () { + var items = []; + + // push a element data into this stack + this.push = function (element) { + items.push(element); + } + + // pop a data from this stack then return this data + this.pop = function () { + return items.pop(); + } + + // return the stack top data + this.peek = function () { + return items[items.length - 1]; + } + + // check this stack is empty + this.isEmpty = function () { + return items.length == 0; + } + + // get the length of this stack + this.size = function () { + return items.length; + } + + // clear this stack + this.clear = function () { + items = []; + } + + // print this stack + this.print = function () { + console.log(items.toString()); + } +} + +// console.log(Stack); + +// init one Stack Class +let stack = new Stack(); +console.log(stack.isEmpty()); + +// push data into this stack +stack.push(5); +stack.push(8); + +console.log(stack.peek()); + +stack.push(7); +console.log(stack.size()); +console.log(stack.isEmpty()); + +stack.push(9); + +stack.print(); + +stack.pop(); +stack.pop(); +console.log(stack.size()); +stack.print(); + From 21e5b0acf1b46044f6e019262af43dc277ecedac Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 20 Aug 2018 17:00:18 +0800 Subject: [PATCH 015/274] Using ES6 Symbol to Create a Stack Structure --- DataStructures/Stack/ES6Pros/SymbolStack.js | 53 +++++++++++++++++++ .../Stack/ES6Pros/UseSymbolStack.js | 22 ++++++++ 2 files changed, 75 insertions(+) create mode 100644 DataStructures/Stack/ES6Pros/SymbolStack.js create mode 100644 DataStructures/Stack/ES6Pros/UseSymbolStack.js diff --git a/DataStructures/Stack/ES6Pros/SymbolStack.js b/DataStructures/Stack/ES6Pros/SymbolStack.js new file mode 100644 index 0000000..0aa8a71 --- /dev/null +++ b/DataStructures/Stack/ES6Pros/SymbolStack.js @@ -0,0 +1,53 @@ +/** + * @author SkylineBin + * @Time 2018-8-20 + * @function Create a Stack Structure using Symbol + */ + +let _items = Symbol(); + +module.exports = class Stack { + + constructor() { + // using a Array items to store Stack Datas + this[_items] = []; + } + + // push a element data into this stack + push(element) { + this[_items].push(element); + } + + // pop a data from this stack then return this data + pop() { + return this[_items].pop(); + } + + // return the stack top data + peek() { + return this[_items][this[_items].length - 1]; + } + + // check this stack is empty + isEmpty() { + return this[_items].length == 0; + } + + // get the length of this stack + size() { + return this[_items].length; + } + + // clear this stack + clear() { + this[_items] = []; + } + + // print this stack + print() { + console.log(this[_items].toString()); + } + + + +} diff --git a/DataStructures/Stack/ES6Pros/UseSymbolStack.js b/DataStructures/Stack/ES6Pros/UseSymbolStack.js new file mode 100644 index 0000000..ef91147 --- /dev/null +++ b/DataStructures/Stack/ES6Pros/UseSymbolStack.js @@ -0,0 +1,22 @@ +/** + * @author SkylineBin + * @time 2018-8-20 + * @function Using Stack with Es6 Symbol + */ + +var Stack = require('./SymbolStack'); + +console.log(Stack); + +var stack = new Stack(); +console.log(stack.isEmpty()); + +// push data into this stack +stack.push(5); +stack.push(8); + +console.log(stack.peek()); + +stack.push(7); +console.log(stack.size()); +console.log(stack.isEmpty()); \ No newline at end of file From 4d09418d9cf0a3a7882837ebf340285470e3cee1 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 20 Aug 2018 17:12:40 +0800 Subject: [PATCH 016/274] add BUG testing of Symbols Stack --- DataStructures/Stack/ES6Pros/UseSymbolStack.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/DataStructures/Stack/ES6Pros/UseSymbolStack.js b/DataStructures/Stack/ES6Pros/UseSymbolStack.js index ef91147..515a702 100644 --- a/DataStructures/Stack/ES6Pros/UseSymbolStack.js +++ b/DataStructures/Stack/ES6Pros/UseSymbolStack.js @@ -19,4 +19,19 @@ console.log(stack.peek()); stack.push(7); console.log(stack.size()); -console.log(stack.isEmpty()); \ No newline at end of file +console.log(stack.isEmpty()); +stack.print(); + + + +// The BUG of using Symbols to Create Stack + +// get all properties of this stack class +let objectSymbols = Object.getOwnPropertySymbols(stack); +console.log(objectSymbols.length); +console.log(objectSymbols); +console.log(objectSymbols[0]); +stack[objectSymbols[0]].push(1); +stack.print(); + +// End of testing BUG From aeecbfebbf2000109bcff22e8b11cfeb96c1af95 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 22 Aug 2018 19:29:50 +0800 Subject: [PATCH 017/274] add ES6 WeakMap to finish a Stack Structure --- .../Stack/ES6Pros/UseWeakMapStack.js | 18 +++++ DataStructures/Stack/ES6Pros/WeakMapStack.js | 69 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 DataStructures/Stack/ES6Pros/UseWeakMapStack.js create mode 100644 DataStructures/Stack/ES6Pros/WeakMapStack.js diff --git a/DataStructures/Stack/ES6Pros/UseWeakMapStack.js b/DataStructures/Stack/ES6Pros/UseWeakMapStack.js new file mode 100644 index 0000000..e12049b --- /dev/null +++ b/DataStructures/Stack/ES6Pros/UseWeakMapStack.js @@ -0,0 +1,18 @@ +/** + * @author SkylineBin + * @time 2018-8-22 + * @function Using Stack with Es6 WeakMap + */ + + var Stack = require('./WeakMapStack'); + + console.log(Stack); + + var stack = new Stack(); + console.log(stack.isEmpty()); + + // push data into this stack + stack.push(5); + stack.push(8); + + console.log(stack.peek()); \ No newline at end of file diff --git a/DataStructures/Stack/ES6Pros/WeakMapStack.js b/DataStructures/Stack/ES6Pros/WeakMapStack.js new file mode 100644 index 0000000..909b286 --- /dev/null +++ b/DataStructures/Stack/ES6Pros/WeakMapStack.js @@ -0,0 +1,69 @@ +/** + * @author SkylineBin + * @Time 2018-8-22 + * @function Use WeakMap to create s Stack Structure + * + */ + + const items = new WeakMap(); + + module.exports = class Stack { + constructor () { + items.set(this, []); + } + + push(element) { + let s = items.get(this); + s.push(element); + } + + pop() { + let s = items.get(this); + let r = s.pop(); + return r; + } + + // return the stack top data + peek() { + let s = items.get(this); + return s[s.length - 1]; + } + + // check this stack is empty + isEmpty() { + let s = items.get(this); + return s.length == 0; + } + + // get the length of this stack + size() { + return this[_items].length; + } + + // clear this stack + clear() { + items.set(this, []); + } + + // print this stack + print() { + let s = items.get(this); + console.log(s.toString()); + } + } + + +/* + use closure to make sure wo can touch WeakMap +*/ + + let Stack = (function () { + const items = new WeakMap(); + class Stack { + constructor () { + items.set(this, []); + } + // other function + } + }) + From 20613451ff3ac6f9bbb408864d605f703ad43e22 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 22 Aug 2018 19:50:38 +0800 Subject: [PATCH 018/274] Using Stack to solve binary conversion --- .../Stack/SolveProblem/BinaryConversion.js | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 DataStructures/Stack/SolveProblem/BinaryConversion.js diff --git a/DataStructures/Stack/SolveProblem/BinaryConversion.js b/DataStructures/Stack/SolveProblem/BinaryConversion.js new file mode 100644 index 0000000..849d7ba --- /dev/null +++ b/DataStructures/Stack/SolveProblem/BinaryConversion.js @@ -0,0 +1,65 @@ +/** + * @author SkylineBin + * @time 2018-8-22 + * @function Using Stack to finish binary conversion + * + */ + +// import the Stack stucture created by Array +var Stack = require('../CreateStack'); + +// ten to bin +function divideBy2(decNumber) { + var remStack = new Stack(), + rem, + binaryString = ''; + + while (decNumber > 0) { + rem = Math.floor(decNumber % 2); + remStack.push(rem); + decNumber = Math.floor(decNumber / 2); + } + + while (!remStack.isEmpty()) { + binaryString += remStack.pop().toString(); + } + return binaryString; +} + +console.log(10,divideBy2(10)); +console.log(233,divideBy2(233)); +console.log(1000,divideBy2(1000)); + +// 10 '1010' +// 233 '11101001' +// 1000 '1111101000' + +console.log('-----------------------------------'); + +// ten to base +function baceConverter(decNumber, base) { + var remStack = new Stack(), + rem, + baseString = '', + digits = '0123456789ABCDEF'; + // base less than 16 + + while (decNumber > 0) { + rem = Math.floor(decNumber % base); + remStack.push(rem); + decNumber = Math.floor(decNumber / base); + } + + while (!remStack.isEmpty()) { + baseString += digits[remStack.pop()]; + } + return baseString; +} + +console.log(101567,'to',2,':',baceConverter(101567, 2)); +console.log(101567,'to',8,':',baceConverter(101567, 8)); +console.log(101567,'to',16,':',baceConverter(101567, 16)); + +// 101567 'to' 2 ':' '11000110010111111' +// 101567 'to' 8 ':' '306277' +// 101567 'to' 16 ':' '18CBF' \ No newline at end of file From d956a4097c40154fe70f7b132cd45b9d1de50c3b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 22 Aug 2018 20:35:16 +0800 Subject: [PATCH 019/274] add balance symbols by stack --- .../Stack/SolveProblem/SymbolsBalance.js | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 DataStructures/Stack/SolveProblem/SymbolsBalance.js diff --git a/DataStructures/Stack/SolveProblem/SymbolsBalance.js b/DataStructures/Stack/SolveProblem/SymbolsBalance.js new file mode 100644 index 0000000..9e02c76 --- /dev/null +++ b/DataStructures/Stack/SolveProblem/SymbolsBalance.js @@ -0,0 +1,52 @@ +/** + * @author SkylineBin + * @time 2018-8-22 + * @function Using Stack to solve this problem of balancing symbols + * + */ + + // import the Stack stucture created by Array + const Stack = require('../CreateStack'); + +// Check Symbols Balance +function checkSymbolBance(symbolString) { + let stack = new Stack(), + balanced = true, + index =0, + symbol, top, + opens = "([{", + closers = ")]}"; + + while (index < symbolString.length && balanced) { + symbol = symbolString.charAt(index); + if (opens.indexOf(symbol) >= 0) { + stack.push(symbol); + console.log('open symbol - stacking :', symbol); + } else { + console.log('close symbol : ', symbol); + if (stack.isEmpty()){ + balanced = false; + console.log('Stack is empty, no more symbols to pop or compare'); + } else { + top = stack.pop(); + if (!(opens.indexOf(top) === closers.indexOf(symbol))) { + balanced = false; + console.log('poping symbol ',top,' - is not a match compared to ',symbol); + } else { + console.log('poping symbol ', top, ' - is a match compared to ', symbol); + } + } + } + index++; + } + if (balanced && stack.isEmpty()) { + return true; + } + return false; +} + +console.log('({[][]})' ,checkSymbolBance('({[][]})')); +console.log('--------------------------'); +console.log('({[)(])]})', checkSymbolBance('({[)(])]})')); +console.log('--------------------------'); +console.log('({[]()[]{}})', checkSymbolBance('({[]()[]{}})')); \ No newline at end of file From 9d92aa370d087ccc06eea58ec1ce514d5c4b96c4 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 22 Aug 2018 21:39:58 +0800 Subject: [PATCH 020/274] add Queue Data Structure by JavaScript --- DataStructures/Queue/CreateQueue.js | 43 +++++++++++++++++++++ DataStructures/Queue/UseES6Queue.js | 26 +++++++++++++ DataStructures/Queue/UseQueue.js | 58 +++++++++++++++++++++++++++++ DataStructures/README.md | 6 ++- 4 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 DataStructures/Queue/CreateQueue.js create mode 100644 DataStructures/Queue/UseES6Queue.js create mode 100644 DataStructures/Queue/UseQueue.js diff --git a/DataStructures/Queue/CreateQueue.js b/DataStructures/Queue/CreateQueue.js new file mode 100644 index 0000000..aa8e0be --- /dev/null +++ b/DataStructures/Queue/CreateQueue.js @@ -0,0 +1,43 @@ +/** + * @author SkylineBin + * @time 2018-8-22 + * @function Create a Queue Structure + * + */ + + module.exports = class Queue { + constructor() { + // using a Array items to store Queue Datas + this.items = []; + } + // add element into this queue + enqueue(element) { + this.items.push(element); + } + + // remove element from this queue + dequeue() { + return this.items.shift(); + } + + // find the first element of this queue + front() { + return this.items[0]; + } + + // check this queue is empty + isEmpty() { + return this.items.length == 0; + } + + // get size of this queue + size() { + return this.items.length; + } + + // print this queue + print() { + console.log(this.items.toString()); + } + + } \ No newline at end of file diff --git a/DataStructures/Queue/UseES6Queue.js b/DataStructures/Queue/UseES6Queue.js new file mode 100644 index 0000000..3e97701 --- /dev/null +++ b/DataStructures/Queue/UseES6Queue.js @@ -0,0 +1,26 @@ +/** + * @author SkylineBin + * @time 2018-8-22 + * @function Using a Queue Structure Function + * + */ + +const Queue = require('./CreateQueue'); + +let queue = new Queue(); +console.log(queue.isEmpty()); + +queue.enqueue("Tom"); +queue.enqueue("Jerry"); + +queue.enqueue("Kerven"); + +queue.print(); +console.log(queue.size()); +console.log(queue.isEmpty()); +queue.dequeue(); + +console.log('front: ', queue.front()); + +queue.enqueue('Marry'); +queue.print(); \ No newline at end of file diff --git a/DataStructures/Queue/UseQueue.js b/DataStructures/Queue/UseQueue.js new file mode 100644 index 0000000..ccf4882 --- /dev/null +++ b/DataStructures/Queue/UseQueue.js @@ -0,0 +1,58 @@ +/** + * @author SkylineBin + * @time 2018-8-22 + * @function Using a Queue Structure Function + * + */ + +function Queue() { + let items = []; + + // add element into this queue + this.enqueue = function(element) { + items.push(element); + } + + // remove element from this queue + this.dequeue = function() { + return items.shift(); + } + + // find the first element of this queue + this.front = function() { + return items[0]; + } + + // check this queue is empty + this.isEmpty = function() { + return items.length == 0; + } + + // get size of this queue + this.size = function() { + return items.length; + } + + // print this queue + this.print = function() { + console.log(items.toString()); + } +} + +let queue = new Queue(); +console.log(queue.isEmpty()); + +queue.enqueue("Tom"); +queue.enqueue("Jerry"); + +queue.enqueue("Kerven"); + +queue.print(); +console.log(queue.size()); +console.log(queue.isEmpty()); +queue.dequeue(); + +console.log('front: ', queue.front()); + +queue.enqueue('Marry'); +queue.print(); \ No newline at end of file diff --git a/DataStructures/README.md b/DataStructures/README.md index d4d6469..f7af8b0 100644 --- a/DataStructures/README.md +++ b/DataStructures/README.md @@ -4,4 +4,8 @@ This contents includes Stack, Tickets.... ## Stack -Using JavaScript to create the Stack Structure \ No newline at end of file +Using JavaScript to create the Stack Structure + +## Queue + +Using JavaScript to create the Queue Structure \ No newline at end of file From 8becb96b31af179948bcffb6a09f798ef3af6b4d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 23 Aug 2018 10:59:32 +0800 Subject: [PATCH 021/274] add some introduction of this project. --- README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e34a437..d4d9fe6 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,17 @@ This project was originally set up to practice the algorithms on the OJ platform, and then summarized some understanding and connection about algorithms. +## Data Structures -# HuaWeiOJ Algorithms +Using JavaScript to create those data structures. + + +## Disk Scheduling Algorithm + +Carrying out disk scheduling algorithm by Java. + + +## HuaWeiOJ Algorithms Some algorithms solved by Python2.7 from HuaWeiOJ Projects From 9c14c951ec96ccbebe9d577f75795417a6dbc86f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 23 Aug 2018 11:05:28 +0800 Subject: [PATCH 022/274] add attributes change to javascript --- .gitattributes | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..abeb795 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +*.py linguist-language=JavaScript +*.txt linguist-language=JavaScript +*.java linguist-language=JavaScript \ No newline at end of file From 79257bdf287bf36e1194da5eb17b1df4d0c6aa81 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 23 Aug 2018 11:10:16 +0800 Subject: [PATCH 023/274] update url of old pics --- Disk Scheduling Algorithm/readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Disk Scheduling Algorithm/readme.md b/Disk Scheduling Algorithm/readme.md index b718dac..a3b76aa 100644 --- a/Disk Scheduling Algorithm/readme.md +++ b/Disk Scheduling Algorithm/readme.md @@ -6,8 +6,8 @@ The file named **SstfAlgo.java** is about SSTF(Shortest Seek Time First) Algorit The file named **ScanAlgo.java** is about SCAN Algorithm It can be discribed like this picture : -![SCAN Algorithm](http://osaussnqu.bkt.clouddn.com/image/system/scanAlgo.png) +![SCAN Algorithm](https://store.skylinebin.com/image/system/scanAlgo.png) The file named **CscanAlgo.java** is about CSCAN Algorithm It can be discribed like this picture : -![CSCAN Algorithm](http://osaussnqu.bkt.clouddn.com/image/system/cscanAlgo.png) +![CSCAN Algorithm](https://store.skylinebin.com/image/system/cscanAlgo.png) From 435fbbf6baf960e90044b3957c678e4e4a254f40 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 29 Aug 2018 20:27:54 +0800 Subject: [PATCH 024/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BC=98=E5=85=88?= =?UTF-8?q?=E9=98=9F=E5=88=97=E7=9A=84=E5=AE=9E=E7=8E=B0=E5=BD=A2=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Queue/PriorityQueue.js | 69 +++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 DataStructures/Queue/PriorityQueue.js diff --git a/DataStructures/Queue/PriorityQueue.js b/DataStructures/Queue/PriorityQueue.js new file mode 100644 index 0000000..32edfd8 --- /dev/null +++ b/DataStructures/Queue/PriorityQueue.js @@ -0,0 +1,69 @@ +/** + * @author SkylineBin + * @time 2018-8-29 + * @function add priority queue + * + */ + +function PriorityQueue() { + let items = []; + + function QueueElement (element, priority) { + this.element = element; + this.priority = priority; + } + + // add element into this queue + this.enqueue = function (element, priority) { + let queueElement = new QueueElement(element, priority); + + let added = false; + for (let i = 0; i < items.length; i++) { + if (queueElement.priority < items[i].priority) { + items.splice(i, 0, queueElement); + added = true; + break; + } + } + if (!added) { + items.push(queueElement); + } + } + + // remove element from this queue + this.dequeue = function () { + return items.shift(); + } + + // find the first element of this queue + this.front = function () { + return items[0]; + } + + // check this queue is empty + this.isEmpty = function () { + return items.length == 0; + } + + // get size of this queue + this.size = function () { + return items.length; + } + + // print this queue + this.print = function () { + for (let i = 0; i < items.length; i++) { + console.log(`${items[i].element} -- ${items[i].priority}`); + } + } +} + + +let priorityQueue = new PriorityQueue(); +priorityQueue.enqueue("John", 2); +priorityQueue.enqueue("Jack", 1); +priorityQueue.enqueue("Kervin", 1); +priorityQueue.enqueue("Skr", 5); +priorityQueue.enqueue("Sam", 3); +priorityQueue.enqueue("Bob", 6); +priorityQueue.print(); From 3c172603417eca23d0c21d22a77260e1c1105c0b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 13 Sep 2018 23:26:53 +0800 Subject: [PATCH 025/274] add leetcode from NowCoder --- NowCoder/Leetcode/checkDatainArray.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 NowCoder/Leetcode/checkDatainArray.js diff --git a/NowCoder/Leetcode/checkDatainArray.js b/NowCoder/Leetcode/checkDatainArray.js new file mode 100644 index 0000000..a537c33 --- /dev/null +++ b/NowCoder/Leetcode/checkDatainArray.js @@ -0,0 +1,19 @@ +/** + * 在一个二维数组中( 每个一维数组的长度相同), * 每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。 + * 请完成一个函数, 输入这样的一个二维数组和一个整数, 判断数组中是否含有该整数。 + * + */ + + // first version + + function Find(target, array) { + // write code here + for (var i = 0; i < array.length; i++) { + for (var j = 0; j < array[i].length; j++) { + if (target == array[i][j]) { + return true; + } + } + } + return false; + } \ No newline at end of file From 22af69e598af8462960eb286418a349da18f03ae Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 13 Sep 2018 23:40:18 +0800 Subject: [PATCH 026/274] add replace space file --- NowCoder/Leetcode/replaceSpaceinString.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 NowCoder/Leetcode/replaceSpaceinString.js diff --git a/NowCoder/Leetcode/replaceSpaceinString.js b/NowCoder/Leetcode/replaceSpaceinString.js new file mode 100644 index 0000000..137553b --- /dev/null +++ b/NowCoder/Leetcode/replaceSpaceinString.js @@ -0,0 +1,15 @@ +/**** + * + * 请实现一个函数, 将一个字符串中的每个空格替换成“ % 20”。 + * 例如, 当字符串为We Are Happy.则经过替换之后的字符串为We % 20 Are % 20 Happy。 + * + */ + + // first version + + function replaceSpace(str) { + // write code here + var regstr = new RegExp(' ', "g"); + var backstr = str.replace(regstr, '%20'); + return backstr; + } From 9e527805ad718c20db1ae2e101ede4a9a8840048 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 13 Sep 2018 23:57:51 +0800 Subject: [PATCH 027/274] add Fibonacci file --- NowCoder/Leetcode/outputFibonacci.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 NowCoder/Leetcode/outputFibonacci.js diff --git a/NowCoder/Leetcode/outputFibonacci.js b/NowCoder/Leetcode/outputFibonacci.js new file mode 100644 index 0000000..26eabe1 --- /dev/null +++ b/NowCoder/Leetcode/outputFibonacci.js @@ -0,0 +1,24 @@ +/**** + * + * 大家都知道斐波那契数列, 现在要求输入一个整数n, 请你输出斐波那契数列的第n项( 从0开始, 第0项为0)。n<=39 + * + */ + + // first version + function Fibonacci(n) { + // write code here + var beforelastnum = 0; + var lastnum = 1; + if (n <= 0) { + return 0; + } else if (n == 1) { + return 1; + } else { + for (var i = 2; i <= n; i++) { + result = beforelastnum + lastnum; + beforelastnum = lastnum; + lastnum = result; + } + return result; + } + } \ No newline at end of file From d8a38abb4a310f543efb4c76f10d7c57de344e0f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 14 Sep 2018 00:10:40 +0800 Subject: [PATCH 028/274] add two stack to create one Queue --- NowCoder/Leetcode/useTwoStackCreatQueue.js | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 NowCoder/Leetcode/useTwoStackCreatQueue.js diff --git a/NowCoder/Leetcode/useTwoStackCreatQueue.js b/NowCoder/Leetcode/useTwoStackCreatQueue.js new file mode 100644 index 0000000..cc92f7d --- /dev/null +++ b/NowCoder/Leetcode/useTwoStackCreatQueue.js @@ -0,0 +1,26 @@ +/**** + * + * 用两个栈来实现一个队列, 完成队列的Push和Pop操作。 队列中的元素为int类型。 + * + */ + + // first version + + var stack1 = [], + stack2 = []; + + function push(node) { + // write code here + stack1.push(node); + } + + function pop() { + if (stack2.length === 0) { + while (stack1.length !== 0) { + stack2.push(stack1.pop()); + } + return stack2.pop(); + } else { + return stack2.pop(); + } + } \ No newline at end of file From 6487ef02a831b4d91c96dea8691d37b5c397131f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 14 Sep 2018 00:47:53 +0800 Subject: [PATCH 029/274] add ListNode --- NowCoder/Leetcode/shiftListNode.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 NowCoder/Leetcode/shiftListNode.js diff --git a/NowCoder/Leetcode/shiftListNode.js b/NowCoder/Leetcode/shiftListNode.js new file mode 100644 index 0000000..257db23 --- /dev/null +++ b/NowCoder/Leetcode/shiftListNode.js @@ -0,0 +1,18 @@ +/**** + * + * 输入一个链表, 按链表值从尾到头的顺序返回一个ArrayList。 + * + * + */ + + // first version + + function printListFromTailToHead(head) { + // write code here + var alldata = []; + while (head != null) { + alldata.unshift(head.val); + head = head.next; + } + return alldata; + } From d724f18ab566bdb952294ace984fef0e9537ed6f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 14 Sep 2018 23:28:10 +0800 Subject: [PATCH 030/274] a failed doublePower algorithm --- NowCoder/Leetcode/doublePower.js | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 NowCoder/Leetcode/doublePower.js diff --git a/NowCoder/Leetcode/doublePower.js b/NowCoder/Leetcode/doublePower.js new file mode 100644 index 0000000..fffa8e4 --- /dev/null +++ b/NowCoder/Leetcode/doublePower.js @@ -0,0 +1,37 @@ +/**** + * + * 给定一个double类型的浮点数base和int类型的整数exponent。 求base的exponent次方。 + * + * + */ + + // first version + + +function Power(base, exponent) { + // write code here + var beforebase = 1; + if (base == 1.0) { + return 1.0; + } else if (base == 0) { + return 'error'; + } else { + + if (exponent == 0) { + return 1; + } else if (exponrnt > 0) { + for (var i = 0; i < exponent; i++) { + beforebase = beforebase * base; + } + return beforebase; + } else if (exponrnt < 0) { + for (var i = 0; i < -exponent; i++) { + beforebase = beforebase * base; + } + return 1 / beforebase; + } + } + +} + +// failed \ No newline at end of file From c3bd4e79d1b9d0696c6f4e264a963c3eac15e7a5 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 14 Sep 2018 23:57:24 +0800 Subject: [PATCH 031/274] =?UTF-8?q?=E7=94=A8=E4=BA=8E=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E6=AD=A3=E5=88=99=E8=A1=A8=E8=BE=BE=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TestProjects/RegText.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 TestProjects/RegText.md diff --git a/TestProjects/RegText.md b/TestProjects/RegText.md new file mode 100644 index 0000000..2d5d774 --- /dev/null +++ b/TestProjects/RegText.md @@ -0,0 +1,11 @@ +12345608587 +027-13245786 +0719-3465785 +0792-1324569 +0359-1340984 + + +```javascript + "0\d{2}-\d{8}|0\d{3}-\d{7}" +``` + From 29ed1e20ddb26dab9bbe4e5f96fd613684af5d7a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 17 Sep 2018 23:44:44 +0800 Subject: [PATCH 032/274] add loop left string --- NowCoder/Leetcode/loopStr.js | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 NowCoder/Leetcode/loopStr.js diff --git a/NowCoder/Leetcode/loopStr.js b/NowCoder/Leetcode/loopStr.js new file mode 100644 index 0000000..8fb521f --- /dev/null +++ b/NowCoder/Leetcode/loopStr.js @@ -0,0 +1,48 @@ +/** + * + * 汇编语言中有一种移位指令叫做循环左移( ROL), 现在有个简单的任务, 就是用字符串模拟这个指令的运算结果。 + * 对于一个给定的字符序列S, 请你把其循环左移K位后的序列输出。 + * 例如, 字符序列S = ”abcXYZdef”, 要求输出循环左移3位后的结果, 即“ XYZdefabc” + * + */ + + +function LeftRotateString(str, n) { + // write code here + n = parseInt(n); + if (str == null || str == '') { + return ""; + } + var thislength = String(str).length; + if (n == 0) { + return str; + } else if (n > 0) { + str = String(str); + var realrol = n % thislength; + var output = ""; + if (realrol == 0) { + return str; + } else { + // for (var i = realrol; i < thislength; i++) { + // output = output + str[i]; + // } + // for (var j = 0; j < realrol; j++) { + // output = output + str[j]; + // } + output = (str.substr(0, realrol).split('').reverse().join('') + str.substr(realrol, thislength - realrol).split('').reverse().join('')).split('').reverse().join(''); + return String(output); + } + + } +} + +var teststr = ""; +console.log('------------------------------------'); +console.log(LeftRotateString(teststr,6)); +console.log('------------------------------------'); + +console.log('------------------------------------'); +console.log(teststr.length); +console.log('------------------------------------'); + + From f7c651a6296612f42647fdda11c57d86b1158664 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 17 Sep 2018 23:57:08 +0800 Subject: [PATCH 033/274] add reverse words --- NowCoder/Leetcode/reverseWords.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 NowCoder/Leetcode/reverseWords.js diff --git a/NowCoder/Leetcode/reverseWords.js b/NowCoder/Leetcode/reverseWords.js new file mode 100644 index 0000000..312c559 --- /dev/null +++ b/NowCoder/Leetcode/reverseWords.js @@ -0,0 +1,18 @@ +/*** + * + * + * + */ + + function ReverseSentence(str) { + // write code here + if (str == null || str == '') { + return ""; + } else { + return str.split(" ").reverse().join(" ") + } + } + + console.log('------------------------------------'); + console.log(ReverseSentence("student a am I")); + console.log('------------------------------------'); \ No newline at end of file From c6f351f732b447aa6ba04d63ac155563c104b322 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 18 Sep 2018 00:06:17 +0800 Subject: [PATCH 034/274] add one semicolon --- EasyPractice/pic.jsp | 1291 +++++++++++++++++++++++++++++ NowCoder/Leetcode/reverseWords.js | 7 +- 2 files changed, 1296 insertions(+), 2 deletions(-) create mode 100644 EasyPractice/pic.jsp diff --git a/EasyPractice/pic.jsp b/EasyPractice/pic.jsp new file mode 100644 index 0000000..1a95b9c --- /dev/null +++ b/EasyPractice/pic.jsp @@ -0,0 +1,1291 @@ +<%@ page language="java" import="java.util.*,com.security.model.UserInfo,com.security.model.RoleInfo" pageEncoding="UTF-8"%> +<% +String path = request.getContextPath(); +String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; +UserInfo userinfo = (UserInfo)session.getAttribute("LOGINUSER"); +String thisusername =null; +String thisuserrole =null; +thisusername = userinfo.getUsername().toString(); +thisuserrole = userinfo.getRoleInfo().getRolename().toString(); +%> + + + + + + + + + + + + + + + + + + + + +<%-- + + --%> + + + + + + + + + + + + + +
+
+

正在加载数据......

+
+
+
+
+
+
+
+ + + +
+
+
+ + +
+ + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 共0 条记录 (0/0) + [首页] + + + [下页] + 跳转到第页(共0页) + +
+ + + + + + +
+ 关闭 +
+
+ +
+
+ 更改图片:   + + + +
+
+
+
+ + + + + +
+
+ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/NowCoder/Leetcode/reverseWords.js b/NowCoder/Leetcode/reverseWords.js index 312c559..81db9ae 100644 --- a/NowCoder/Leetcode/reverseWords.js +++ b/NowCoder/Leetcode/reverseWords.js @@ -1,5 +1,8 @@ /*** - * + * 牛客最近来了一个新员工Fish, 每天早晨总是会拿着一本英文杂志, 写些句子在本子上。 + * 同事Cat对Fish写的内容颇感兴趣, 有一天他向Fish借来翻看, 但却读不懂它的意思。 + * 例如,“ student.a am I”。 后来才意识到, 这家伙原来把句子单词的顺序翻转了, + * 正确的句子应该是“ I am a student.”。 * * */ @@ -9,7 +12,7 @@ if (str == null || str == '') { return ""; } else { - return str.split(" ").reverse().join(" ") + return str.split(" ").reverse().join(" "); } } From a4b659b8513ed0acf9006e9bb6bd92b00b3cd248 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 18 Sep 2018 00:07:07 +0800 Subject: [PATCH 035/274] delete pic.jsp --- EasyPractice/pic.jsp | 1291 ------------------------------------------ 1 file changed, 1291 deletions(-) delete mode 100644 EasyPractice/pic.jsp diff --git a/EasyPractice/pic.jsp b/EasyPractice/pic.jsp deleted file mode 100644 index 1a95b9c..0000000 --- a/EasyPractice/pic.jsp +++ /dev/null @@ -1,1291 +0,0 @@ -<%@ page language="java" import="java.util.*,com.security.model.UserInfo,com.security.model.RoleInfo" pageEncoding="UTF-8"%> -<% -String path = request.getContextPath(); -String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; -UserInfo userinfo = (UserInfo)session.getAttribute("LOGINUSER"); -String thisusername =null; -String thisuserrole =null; -thisusername = userinfo.getUsername().toString(); -thisuserrole = userinfo.getRoleInfo().getRolename().toString(); -%> - - - - - - - - - - - - - - - - - - - - -<%-- - - --%> - - - - - - - - - - - - - -
-
-

正在加载数据......

-
-
-
-
-
-
-
- - - -
-
-
- - -
- - -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- 共0 条记录 (0/0) - [首页] - - - [下页] - 跳转到第页(共0页) - -
- - - - - - -
- 关闭 -
-
- -
-
- 更改图片:   - - - -
-
-
-
- - - - - -
-
- - - - - - - - - - - - - - - - \ No newline at end of file From 7c3c5083229ee10c8917c9b9ecf8b4b2d2374b1a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 19 Sep 2018 18:45:59 +0800 Subject: [PATCH 036/274] add circulQueue --- DataStructures/Queue/CirculQueue.js | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 DataStructures/Queue/CirculQueue.js diff --git a/DataStructures/Queue/CirculQueue.js b/DataStructures/Queue/CirculQueue.js new file mode 100644 index 0000000..5456017 --- /dev/null +++ b/DataStructures/Queue/CirculQueue.js @@ -0,0 +1,33 @@ +/** + * @author SkylineBin + * @time 2018-9-19日 + * @function use Queue to loop flower + * + * + */ + +var Queue = require('./CreateQueue'); + +function hotPotato (nameList, num){ + let queue = new Queue(); + + // add all gamer into this queue + for (let index = 0; index < nameList.length; index++) { + queue.enqueue(nameList[index]); + } + let eliminated = ''; + while (queue.size() > 1) { + for (let second = 0; second < num; second++) { + // move the head data into the end data + queue.enqueue(queue.dequeue()); + } + eliminated = queue.dequeue(); + // remove chosed data + console.log(eliminated + ' is failed in this game~'); + } + return queue.dequeue(); +} + +let names = ['John', 'Rick', 'Tom', 'Carl', 'Iiva']; +let winner = hotPotato(names, 7); +console.log('The winner of this game is ' + winner); \ No newline at end of file From 0107b47c1be85a6c3dba476f1554e0302cce4eb9 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 19 Sep 2018 19:11:25 +0800 Subject: [PATCH 037/274] add the LinkedList Structure --- DataStructures/LinkedList/CreateLinkedList.js | 10 +++ DataStructures/LinkedList/UseLinkedList.js | 68 +++++++++++++++++++ DataStructures/README.md | 6 +- 3 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 DataStructures/LinkedList/CreateLinkedList.js create mode 100644 DataStructures/LinkedList/UseLinkedList.js diff --git a/DataStructures/LinkedList/CreateLinkedList.js b/DataStructures/LinkedList/CreateLinkedList.js new file mode 100644 index 0000000..73b8ea3 --- /dev/null +++ b/DataStructures/LinkedList/CreateLinkedList.js @@ -0,0 +1,10 @@ +/** + * @author SkylineBin + * @time 2018-9-19 + * @function Create a LinkedList structure + * + */ + +module.exports = class LinkedList { + +} \ No newline at end of file diff --git a/DataStructures/LinkedList/UseLinkedList.js b/DataStructures/LinkedList/UseLinkedList.js new file mode 100644 index 0000000..83d5411 --- /dev/null +++ b/DataStructures/LinkedList/UseLinkedList.js @@ -0,0 +1,68 @@ +/** + * @author SkylineBin + * @time 2018-9-19 + * @function Using a LinkedList Structure Function + * + */ + +function LinkedList() { + // we need a Node class to help us create one LinkedList + let Node = function (element) { + this.element = element; + this.next = null; + } + + let length = 0; + let head = null; + + // append another element after the end of this linkedlist + this.append = function(element) { + + } + + // insert an element into this position + this.insert = function(position, element) { + + } + + // remove this position + this.removeAt = function(position){ + + } + + // remove one element from this linkedlist + this.remove = function(element){ + + } + + // find the index of this linkedlist + this.indexOf = function(element) { + + } + + // check this linkedlist is empty + this.isEmpty = function(){ + + } + + // get the size of this linkedlist + this.size = function(){ + + } + + // get the head of this LinkedList + this.getHead = function(){ + + } + + // to String + this.toString = function() { + + } + + // print this LinkedList + this.print = function(){ + + } + +} \ No newline at end of file diff --git a/DataStructures/README.md b/DataStructures/README.md index f7af8b0..45c46eb 100644 --- a/DataStructures/README.md +++ b/DataStructures/README.md @@ -8,4 +8,8 @@ Using JavaScript to create the Stack Structure ## Queue -Using JavaScript to create the Queue Structure \ No newline at end of file +Using JavaScript to create the Queue Structure + +## LinkedList + +Using JavaScript to create the LinkedList Structure \ No newline at end of file From c3e9c5693cc90a379f531739297c3c86d2fb64a6 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 19 Sep 2018 20:00:51 +0800 Subject: [PATCH 038/274] add append function and remove function --- DataStructures/LinkedList/UseLinkedList.js | 45 +++++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/DataStructures/LinkedList/UseLinkedList.js b/DataStructures/LinkedList/UseLinkedList.js index 83d5411..b6a3134 100644 --- a/DataStructures/LinkedList/UseLinkedList.js +++ b/DataStructures/LinkedList/UseLinkedList.js @@ -16,8 +16,19 @@ function LinkedList() { let head = null; // append another element after the end of this linkedlist - this.append = function(element) { - + this.append = function(thiselement) { + let node = new Node(thiselement), + current; + if (head == null){ + head = node; + } else { + current = head; + while (current.next) { + current = current.next; + } + current.next = node; + } + length++; } // insert an element into this position @@ -25,9 +36,29 @@ function LinkedList() { } - // remove this position + // remove the element at this position this.removeAt = function(position){ - + if(position > -1 && position < length){ + let current = head, + previous, + index = 0; + + if(position === 0){ + head = current.next; + } else { + while(index++ < position){ + previous = current; + current = current.next; + } + + previous.next = current.next; + } + length--; + + return current.element; + }else { + return null; + } } // remove one element from this linkedlist @@ -65,4 +96,8 @@ function LinkedList() { } -} \ No newline at end of file +} + +let list = new LinkedList(); +list.append(10); +list.append(15); \ No newline at end of file From 5624aaf1dee7a483264f57ec8afdb9c15886d308 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 19 Sep 2018 20:00:51 +0800 Subject: [PATCH 039/274] add append function and remove function --- DataStructures/LinkedList/UseLinkedList.js | 45 +++++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/DataStructures/LinkedList/UseLinkedList.js b/DataStructures/LinkedList/UseLinkedList.js index 83d5411..b6a3134 100644 --- a/DataStructures/LinkedList/UseLinkedList.js +++ b/DataStructures/LinkedList/UseLinkedList.js @@ -16,8 +16,19 @@ function LinkedList() { let head = null; // append another element after the end of this linkedlist - this.append = function(element) { - + this.append = function(thiselement) { + let node = new Node(thiselement), + current; + if (head == null){ + head = node; + } else { + current = head; + while (current.next) { + current = current.next; + } + current.next = node; + } + length++; } // insert an element into this position @@ -25,9 +36,29 @@ function LinkedList() { } - // remove this position + // remove the element at this position this.removeAt = function(position){ - + if(position > -1 && position < length){ + let current = head, + previous, + index = 0; + + if(position === 0){ + head = current.next; + } else { + while(index++ < position){ + previous = current; + current = current.next; + } + + previous.next = current.next; + } + length--; + + return current.element; + }else { + return null; + } } // remove one element from this linkedlist @@ -65,4 +96,8 @@ function LinkedList() { } -} \ No newline at end of file +} + +let list = new LinkedList(); +list.append(10); +list.append(15); \ No newline at end of file From f1cc5d10dac7857e5b10919d55897552ea59965e Mon Sep 17 00:00:00 2001 From: skylinebin Date: Fri, 21 Sep 2018 23:18:08 +0800 Subject: [PATCH 040/274] add find two nums from array --- NowCoder/Leetcode/findSumfromArray.js | 49 +++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 NowCoder/Leetcode/findSumfromArray.js diff --git a/NowCoder/Leetcode/findSumfromArray.js b/NowCoder/Leetcode/findSumfromArray.js new file mode 100644 index 0000000..63554e7 --- /dev/null +++ b/NowCoder/Leetcode/findSumfromArray.js @@ -0,0 +1,49 @@ +/** +*输入一个递增排序的数组和一个数字S,在数组中查找两个数, +*使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。 +* +*/ + +// failed first + +function FindNumbersWithSum(array, sum) +{ + // write code here + var arrlength = array.length; + var numones =[]; + var numtwos=[]; + var nummulti=[]; + if(arrlength === 0 || array == null){ + return ''; + }else{ + for(var i=0;i< arrlength-1;i++){ + for(var j=i+1;jnummulti[k]){ + leastnum = nummulti[k]; + leastone = k; + } + } + return numones[leastone],numtwos[leastone]; + } + } + +} From 7696e4dd189ca268728d119f972d6aa93085c702 Mon Sep 17 00:00:00 2001 From: skylinebin Date: Sat, 22 Sep 2018 21:27:51 +0800 Subject: [PATCH 041/274] add the algorithms path to prepare for the future --- Algorithms/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Algorithms/README.md diff --git a/Algorithms/README.md b/Algorithms/README.md new file mode 100644 index 0000000..9499987 --- /dev/null +++ b/Algorithms/README.md @@ -0,0 +1,3 @@ +## Algorithms + +Some classic algorithms are always worth learning! From 9a79e118dce4e58cc969f2eef44cd030530d2eef Mon Sep 17 00:00:00 2001 From: skylinebin Date: Sat, 22 Sep 2018 21:31:03 +0800 Subject: [PATCH 042/274] move Disk Scheduling Algorithms to Algorithms path --- .../Disk Scheduling Algorithm}/CscanAlgo.java | 218 ++++++++--------- .../Disk Scheduling Algorithm}/FcfsAlgo.java | 108 ++++----- .../Disk Scheduling Algorithm}/ScanAlgo.java | 220 +++++++++--------- .../Disk Scheduling Algorithm}/SstfAlgo.java | 140 +++++------ .../Disk Scheduling Algorithm}/readme.md | 0 5 files changed, 343 insertions(+), 343 deletions(-) rename {Disk Scheduling Algorithm => Algorithms/Disk Scheduling Algorithm}/CscanAlgo.java (97%) rename {Disk Scheduling Algorithm => Algorithms/Disk Scheduling Algorithm}/FcfsAlgo.java (97%) rename {Disk Scheduling Algorithm => Algorithms/Disk Scheduling Algorithm}/ScanAlgo.java (97%) rename {Disk Scheduling Algorithm => Algorithms/Disk Scheduling Algorithm}/SstfAlgo.java (97%) rename {Disk Scheduling Algorithm => Algorithms/Disk Scheduling Algorithm}/readme.md (100%) diff --git a/Disk Scheduling Algorithm/CscanAlgo.java b/Algorithms/Disk Scheduling Algorithm/CscanAlgo.java similarity index 97% rename from Disk Scheduling Algorithm/CscanAlgo.java rename to Algorithms/Disk Scheduling Algorithm/CscanAlgo.java index c635659..caff64e 100644 --- a/Disk Scheduling Algorithm/CscanAlgo.java +++ b/Algorithms/Disk Scheduling Algorithm/CscanAlgo.java @@ -1,109 +1,109 @@ -package System; - -public class CscanAlgo { - public static void main(String[] args){ - - int[] fixedataA = {29,84,8,89,1,94}; - int fixedcurrent = 42; - System.out.println("当前磁道位置:"+fixedcurrent); - for(int i=0;idataA[tj]){ - tempd = dataA[ti]; - dataA[ti] = dataA[tj]; - dataA[tj] = tempd; - } - } - } - //判断当前磁头所在位置 - for(int ti=0;ticurrent){ - sortIndex = ti; - break; - }else if(ti == processlen-1){ - sortIndex = processlen; - } - //否则当前磁头位置最小 - } - int allcount=0; - int step=0; - int countnum=0; - //若磁道位置不在开头也不在结尾 - if(sortIndex!=0 && sortIndex!=processlen){ - if(direction == 0){ - //先小后大 从大到小 - for(int ts=sortIndex-1;ts>=0;ts--){ - step = Math.abs(dataA[ts] - current); - System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - for(int ts =processlen-1;ts>=sortIndex;ts--){ - step = Math.abs(dataA[ts] - current); - System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - }else{ - //先大后小 - for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - - for(int ts=0;ts"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - } - }else if(sortIndex==0 ||sortIndex==processlen){ - //若磁头在位置开头或者在位置结尾 - if(direction == 0){ - for(int ts=processlen-1;ts>=0;ts--){ - step = Math.abs(dataA[ts] - current); - System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - }else{ - for(int ts =0;ts"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - } - } - System.out.println(); - System.out.println("磁道磁头总移动:"+allcount+"次"); - System.out.println("-------------------------"); - } -} +package System; + +public class CscanAlgo { + public static void main(String[] args){ + + int[] fixedataA = {29,84,8,89,1,94}; + int fixedcurrent = 42; + System.out.println("当前磁道位置:"+fixedcurrent); + for(int i=0;idataA[tj]){ + tempd = dataA[ti]; + dataA[ti] = dataA[tj]; + dataA[tj] = tempd; + } + } + } + //判断当前磁头所在位置 + for(int ti=0;ticurrent){ + sortIndex = ti; + break; + }else if(ti == processlen-1){ + sortIndex = processlen; + } + //否则当前磁头位置最小 + } + int allcount=0; + int step=0; + int countnum=0; + //若磁道位置不在开头也不在结尾 + if(sortIndex!=0 && sortIndex!=processlen){ + if(direction == 0){ + //先小后大 从大到小 + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + for(int ts =processlen-1;ts>=sortIndex;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else{ + //先大后小 + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + + for(int ts=0;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + }else if(sortIndex==0 ||sortIndex==processlen){ + //若磁头在位置开头或者在位置结尾 + if(direction == 0){ + for(int ts=processlen-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else{ + for(int ts =0;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } +} diff --git a/Disk Scheduling Algorithm/FcfsAlgo.java b/Algorithms/Disk Scheduling Algorithm/FcfsAlgo.java similarity index 97% rename from Disk Scheduling Algorithm/FcfsAlgo.java rename to Algorithms/Disk Scheduling Algorithm/FcfsAlgo.java index e0e588b..f809039 100644 --- a/Disk Scheduling Algorithm/FcfsAlgo.java +++ b/Algorithms/Disk Scheduling Algorithm/FcfsAlgo.java @@ -1,54 +1,54 @@ -package System; - -import java.util.Random; - -public class FcfsAlgo { - public static void main(String[] args){ -// int maxran = 100; -// int minran =1; -// int totalnum = 6; -// int tempdata =0; -// int[] dataArray = new int[6]; -// Random trandom = new Random(); -// int currentdata = trandom.nextInt(maxran)%(maxran-minran+1) + minran; -//// 生成初始磁道位置 -// System.out.println("当前磁道位置:"+currentdata); -// for(int i=0;i"+dataA[0]+" 移动"+step+"次"); - allcount = allcount+step; - for(int i=0;i"+dataA[i+1]+" 移动"+step+"次"); - allcount+= step; - } - System.out.println(); - System.out.println("磁道磁头总移动:"+allcount+"次"); - System.out.println("-------------------------"); - } -} +package System; + +import java.util.Random; + +public class FcfsAlgo { + public static void main(String[] args){ +// int maxran = 100; +// int minran =1; +// int totalnum = 6; +// int tempdata =0; +// int[] dataArray = new int[6]; +// Random trandom = new Random(); +// int currentdata = trandom.nextInt(maxran)%(maxran-minran+1) + minran; +//// 生成初始磁道位置 +// System.out.println("当前磁道位置:"+currentdata); +// for(int i=0;i"+dataA[0]+" 移动"+step+"次"); + allcount = allcount+step; + for(int i=0;i"+dataA[i+1]+" 移动"+step+"次"); + allcount+= step; + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } +} diff --git a/Disk Scheduling Algorithm/ScanAlgo.java b/Algorithms/Disk Scheduling Algorithm/ScanAlgo.java similarity index 97% rename from Disk Scheduling Algorithm/ScanAlgo.java rename to Algorithms/Disk Scheduling Algorithm/ScanAlgo.java index e81826b..033e33b 100644 --- a/Disk Scheduling Algorithm/ScanAlgo.java +++ b/Algorithms/Disk Scheduling Algorithm/ScanAlgo.java @@ -1,110 +1,110 @@ -package System; - -public class ScanAlgo { - public static void main(String[] args){ - - int[] fixedataA = {29,84,8,89,1,94}; - int fixedcurrent = 42; -// int[] fixedataA = {65,68,49,28,100,170,160,48,194}; -// int fixedcurrent = 110; - System.out.println("当前磁道位置:"+fixedcurrent); - for(int i=0;idataA[tj]){ - tempd = dataA[ti]; - dataA[ti] = dataA[tj]; - dataA[tj] = tempd; - } - } - } - //判断当前磁头所在位置 - for(int ti=0;ticurrent){ - sortIndex = ti; - break; - }else if(ti == processlen-1){ - sortIndex = processlen; - } - //否则当前磁头位置最小 - } - int allcount=0; - int step=0; - int countnum=0; - //若磁道位置不在开头也不在结尾 - if(sortIndex!=0 && sortIndex!=processlen){ - if(direction == 0){ - //先小后大 - for(int ts=sortIndex-1;ts>=0;ts--){ - step = Math.abs(dataA[ts] - current); - System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - }else{ - //先大后小 - for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - - for(int ts=sortIndex-1;ts>=0;ts--){ - step = Math.abs(dataA[ts] - current); - System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - } - }else if(sortIndex==0){ - //若磁头在位置开头 - for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - }else if(sortIndex==processlen){ - //若磁道在位置结尾 - for(int ts=sortIndex-1;ts>=0;ts--){ - step = Math.abs(dataA[ts] - current); - System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); - allcount+= step; - current = dataA[ts]; - countnum++; - } - } - System.out.println(); - System.out.println("磁道磁头总移动:"+allcount+"次"); - System.out.println("-------------------------"); - } -} +package System; + +public class ScanAlgo { + public static void main(String[] args){ + + int[] fixedataA = {29,84,8,89,1,94}; + int fixedcurrent = 42; +// int[] fixedataA = {65,68,49,28,100,170,160,48,194}; +// int fixedcurrent = 110; + System.out.println("当前磁道位置:"+fixedcurrent); + for(int i=0;idataA[tj]){ + tempd = dataA[ti]; + dataA[ti] = dataA[tj]; + dataA[tj] = tempd; + } + } + } + //判断当前磁头所在位置 + for(int ti=0;ticurrent){ + sortIndex = ti; + break; + }else if(ti == processlen-1){ + sortIndex = processlen; + } + //否则当前磁头位置最小 + } + int allcount=0; + int step=0; + int countnum=0; + //若磁道位置不在开头也不在结尾 + if(sortIndex!=0 && sortIndex!=processlen){ + if(direction == 0){ + //先小后大 + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else{ + //先大后小 + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + }else if(sortIndex==0){ + //若磁头在位置开头 + for(int ts =sortIndex;ts"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + }else if(sortIndex==processlen){ + //若磁道在位置结尾 + for(int ts=sortIndex-1;ts>=0;ts--){ + step = Math.abs(dataA[ts] - current); + System.out.println(countnum+1+": "+ current+"---->"+dataA[ts]+" 移动"+step+"次"); + allcount+= step; + current = dataA[ts]; + countnum++; + } + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } +} diff --git a/Disk Scheduling Algorithm/SstfAlgo.java b/Algorithms/Disk Scheduling Algorithm/SstfAlgo.java similarity index 97% rename from Disk Scheduling Algorithm/SstfAlgo.java rename to Algorithms/Disk Scheduling Algorithm/SstfAlgo.java index a88afd8..d22a3a3 100644 --- a/Disk Scheduling Algorithm/SstfAlgo.java +++ b/Algorithms/Disk Scheduling Algorithm/SstfAlgo.java @@ -1,70 +1,70 @@ -package System; - -import java.util.Random; - -public class SstfAlgo { - public static void main(String[] args){ -// int maxran = 100; -// int minran =1; -// int totalnum = 6; -// int tempdata =0; -// int[] dataArray = new int[totalnum]; -// Random trandom = new Random(); -// int currentdata = trandom.nextInt(maxran)%(maxran-minran+1) + minran; -//// 生成初始磁道位置 -// System.out.println("当前磁道位置:"+currentdata); -// for(int i=0;i Math.abs(dataA[j]-current)){ - tempmove = dataA[j]; - ChosedIndex = j; - } - } - } - accessList[i] = tempmove; - step = Math.abs(tempmove - current); - System.out.println(i+1+": "+ current+"---->"+tempmove+" 移动"+step+"次"); - allcount+= step; - dataA[ChosedIndex] = -1; - current = tempmove; - tempmove = 1000; - } - System.out.println(); - System.out.println("磁道磁头总移动:"+allcount+"次"); - System.out.println("-------------------------"); - } - -} +package System; + +import java.util.Random; + +public class SstfAlgo { + public static void main(String[] args){ +// int maxran = 100; +// int minran =1; +// int totalnum = 6; +// int tempdata =0; +// int[] dataArray = new int[totalnum]; +// Random trandom = new Random(); +// int currentdata = trandom.nextInt(maxran)%(maxran-minran+1) + minran; +//// 生成初始磁道位置 +// System.out.println("当前磁道位置:"+currentdata); +// for(int i=0;i Math.abs(dataA[j]-current)){ + tempmove = dataA[j]; + ChosedIndex = j; + } + } + } + accessList[i] = tempmove; + step = Math.abs(tempmove - current); + System.out.println(i+1+": "+ current+"---->"+tempmove+" 移动"+step+"次"); + allcount+= step; + dataA[ChosedIndex] = -1; + current = tempmove; + tempmove = 1000; + } + System.out.println(); + System.out.println("磁道磁头总移动:"+allcount+"次"); + System.out.println("-------------------------"); + } + +} diff --git a/Disk Scheduling Algorithm/readme.md b/Algorithms/Disk Scheduling Algorithm/readme.md similarity index 100% rename from Disk Scheduling Algorithm/readme.md rename to Algorithms/Disk Scheduling Algorithm/readme.md From ed447f52e9db3f3f2d42c1bad0541befc5920041 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Oct 2018 13:03:15 +0800 Subject: [PATCH 043/274] add three basic sort algorithms --- Algorithms/basic_algorithm/BubbleSort.java | 29 +++++++++++++++++++ Algorithms/basic_algorithm/InsertionSort.java | 28 ++++++++++++++++++ Algorithms/basic_algorithm/SelectionSort.java | 26 +++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 Algorithms/basic_algorithm/BubbleSort.java create mode 100644 Algorithms/basic_algorithm/InsertionSort.java create mode 100644 Algorithms/basic_algorithm/SelectionSort.java diff --git a/Algorithms/basic_algorithm/BubbleSort.java b/Algorithms/basic_algorithm/BubbleSort.java new file mode 100644 index 0000000..5c63c6c --- /dev/null +++ b/Algorithms/basic_algorithm/BubbleSort.java @@ -0,0 +1,29 @@ +package basic_algorithm; + +import java.util.Arrays; + +public class BubbleSort { + +// ʵð + public static void bubbleSort(int[] arr) { + if(arr == null || arr.length < 2) { + return; + } + for (int end = arr.length - 1; end >0; end--) { +// ̶Χ ÿһηź + for (int i=0; i< end; i++) { + if (arr[i] > arr[i + 1]) { + swap(arr, i, i+1); + } + } + } + + } + + public static void swap(int[] arr, int i, int j) { + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } + +} diff --git a/Algorithms/basic_algorithm/InsertionSort.java b/Algorithms/basic_algorithm/InsertionSort.java new file mode 100644 index 0000000..cec01d4 --- /dev/null +++ b/Algorithms/basic_algorithm/InsertionSort.java @@ -0,0 +1,28 @@ +package basic_algorithm; + +public class InsertionSort { + public static void insertionSort(int[] arr) { + if (arr == null || arr.length < 2) { + return; + } + for (int i = 1; i < arr.length; i++) { +// ǰ i λõ + for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) { +// i-1 i λ򽻻j--ǰ +// j >= 0 Խ磬arr[j] > arr[j + 1] жǷС + swap(arr, j, j+1); + } + } + } + + public static void swap(int[] arr, int i, int j) { +// һֽķ +// arr[i] = arr[i] ^ arr[j]; +// arr[j] = arr[i] ^ arr[j]; +// arr[i] = arr[i] ^ arr[j]; + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } + +} diff --git a/Algorithms/basic_algorithm/SelectionSort.java b/Algorithms/basic_algorithm/SelectionSort.java new file mode 100644 index 0000000..e81ee16 --- /dev/null +++ b/Algorithms/basic_algorithm/SelectionSort.java @@ -0,0 +1,26 @@ +package basic_algorithm; + +public class SelectionSort { + +// ʵѡ + public static void selectionSort(int[] arr) { + if (arr == null || arr.length < 2) { + return; + } + for (int i = 0; i < arr.length - 1; i++) { +// 涨ʼλ + int minIndex =i; +// minIndex ¼С± + for (int j = i + 1; j < arr.length; j++) { + minIndex = arr[j] < arr[minIndex] ? j : minIndex; + } + swap(arr, i, minIndex); + } + } + + public static void swap(int[] arr, int i, int j) { + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } +} From 9a72026f0f92f0de36cf167222758e4ecf01f95e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Oct 2018 13:38:13 +0800 Subject: [PATCH 044/274] =?UTF-8?q?=E5=8A=A0=E5=85=A5=20=E5=AF=B9=E6=95=B0?= =?UTF-8?q?=E5=99=A8=E6=B5=8B=E8=AF=95=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/basic_algorithm/BubbleSort.java | 50 ++++++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/Algorithms/basic_algorithm/BubbleSort.java b/Algorithms/basic_algorithm/BubbleSort.java index 5c63c6c..05ab04d 100644 --- a/Algorithms/basic_algorithm/BubbleSort.java +++ b/Algorithms/basic_algorithm/BubbleSort.java @@ -4,13 +4,13 @@ public class BubbleSort { -// ʵð +// 使用 java 实现 冒泡排序 public static void bubbleSort(int[] arr) { if(arr == null || arr.length < 2) { return; - } + } for (int end = arr.length - 1; end >0; end--) { -// ̶Χ ÿһηź +// 每一轮排一个数 for (int i=0; i< end; i++) { if (arr[i] > arr[i + 1]) { swap(arr, i, i+1); @@ -25,5 +25,49 @@ public static void swap(int[] arr, int i, int j) { arr[i] = arr[j]; arr[j] = tmp; } + + + + +// for test (绝对正确的算法) +// 一般使用系统自带的排序算法,或者容易实现无错误的算法 + public static void rightMethod(int[] arr) { + Arrays.sort(arr); + } + + + + + +// for test +// 使用对数器进行测试 + public static int[] generateRandomArray(int size, int value) { +// 使用系统自带的随机数生成器生成备选数集合 +// Math.random() -> double [0,1) +// (int) ((size + 1) * Math.random()) -> [0,size] 整数集合 +// size =6, size + 1 =7; +// Math.random() -> [0,1) * 7 -> [0,7) double +// double -> int [0,6] -> int + + +// 生成长度随机的数组 + int[] arr = new int[(int) ((size + 1) * Math.random())]; +// 数组内的每个数也是随机的 + for (int i = 0; i < arr.length; i++) { + arr[i] = (int) ((value + 1) * Math.random()) - (int) (value * Math.random()); + } + return arr; + + } + + + + + + + + + + } From 38abcde034ef50ccd76b3da47ec7e8055d47499b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Oct 2018 14:00:48 +0800 Subject: [PATCH 045/274] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E5=A4=A7=E6=A0=B7?= =?UTF-8?q?=E6=9C=AC=E7=8E=AF=E5=A2=83=E6=B5=8B=E8=AF=95=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E5=AF=B9=E6=AF=94=E8=87=AA=E5=B7=B1=E4=BC=98=E5=8C=96=E7=9A=84?= =?UTF-8?q?=E7=AE=97=E6=B3=95=E4=B8=8E=E7=BB=9D=E5=AF=B9=E6=AD=A3=E7=A1=AE?= =?UTF-8?q?=E7=9A=84=E7=AE=97=E6=B3=95=E7=9A=84=E4=B8=8D=E5=90=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 以及一些辅助的函数 --- Algorithms/basic_algorithm/BubbleSort.java | 71 ++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/Algorithms/basic_algorithm/BubbleSort.java b/Algorithms/basic_algorithm/BubbleSort.java index 05ab04d..6864d88 100644 --- a/Algorithms/basic_algorithm/BubbleSort.java +++ b/Algorithms/basic_algorithm/BubbleSort.java @@ -60,7 +60,78 @@ public static int[] generateRandomArray(int size, int value) { } +// for test +// 生成拷贝数组的方法 + public static int[] copyArray(int[] arr) { + if (arr == null) { + return null; + } + int[] res = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + res[i] = arr[i]; + } + return res; + } + +// for test +// 判断两个数组是否相同 + public static boolean isEqual(int[] arrone, int[] arrtwo) { + if((arrone == null && arrtwo != null) || (arrone != null && arrtwo == null)) { + return false; + } + if(arrone == null && arrtwo == null) { + return true; + } + if(arrone.length != arrtwo.length) { + return false; + } + for (int i = 0; i < arrone.length; i++) { + if (arrone[i] != arrtwo[i]) { + return false; + } + } + return true; + } + +// for test +// 打印数组的方法 + public static void printArray(int[] arr) { + if(arr == null || arr.length ==0) { + System.out.println(""); + }else { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i]); + System.out.println(""); + } + } + } + +// 大样本测试 方法 + public static void main(String[] args) { + int testTime = 500000; + int size = 10; + int value = 100; + boolean succeed = true; + for (int i = 0; i < testTime; i++) { + int[] arrone = generateRandomArray(size, value); + int[] arrtwo = copyArray(arrone); + int[] arrthree = copyArray(arrone); + bubbleSort(arrone); + rightMethod(arrtwo); + if(!isEqual(arrone, arrtwo)) { + succeed = false; + printArray(arrthree); + break; + } + } + + System.out.println(succeed ? "well done!" : "wrong algorithms!"); + + int[] arr = generateRandomArray(size, value); + printArray(arr); + + } From c1974b44632af879ba61ef20db733f1f26f60a10 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Oct 2018 14:17:55 +0800 Subject: [PATCH 046/274] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E7=9A=84=E7=BC=96=E7=A0=81=EF=BC=8C=E4=BB=A5=E5=8F=8A=E6=9B=B4?= =?UTF-8?q?=E6=94=B9=E6=B3=A8=E9=87=8A=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/basic_algorithm/InsertionSort.java | 9 +++++---- Algorithms/basic_algorithm/SelectionSort.java | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Algorithms/basic_algorithm/InsertionSort.java b/Algorithms/basic_algorithm/InsertionSort.java index cec01d4..d12e555 100644 --- a/Algorithms/basic_algorithm/InsertionSort.java +++ b/Algorithms/basic_algorithm/InsertionSort.java @@ -1,22 +1,23 @@ package basic_algorithm; public class InsertionSort { +// 使用 java 实现的插入排序 public static void insertionSort(int[] arr) { if (arr == null || arr.length < 2) { return; } for (int i = 1; i < arr.length; i++) { -// ǰ i λõ +// 指定第 i 个数的初始值 for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) { -// i-1 i λ򽻻j--ǰ -// j >= 0 Խ磬arr[j] > arr[j + 1] жǷС +// 从 i 个数开始往前进行排序 +// j >= 0 防止越界 arr[j] > arr[j + 1] 保证左边的最小 swap(arr, j, j+1); } } } public static void swap(int[] arr, int i, int j) { -// һֽķ +// 交换两个数的另一种写法 // arr[i] = arr[i] ^ arr[j]; // arr[j] = arr[i] ^ arr[j]; // arr[i] = arr[i] ^ arr[j]; diff --git a/Algorithms/basic_algorithm/SelectionSort.java b/Algorithms/basic_algorithm/SelectionSort.java index e81ee16..ad5c57f 100644 --- a/Algorithms/basic_algorithm/SelectionSort.java +++ b/Algorithms/basic_algorithm/SelectionSort.java @@ -2,15 +2,15 @@ public class SelectionSort { -// ʵѡ +// 使用 java 实现的选择排序 public static void selectionSort(int[] arr) { if (arr == null || arr.length < 2) { return; } for (int i = 0; i < arr.length - 1; i++) { -// 涨ʼλ +// 给出初始值索引 int minIndex =i; -// minIndex ¼С± +// minIndex 保存从 i 往后的最小值索引 for (int j = i + 1; j < arr.length; j++) { minIndex = arr[j] < arr[minIndex] ? j : minIndex; } From f55d84a5ce710268cb916bf884b9c2ff7fdd40e9 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Oct 2018 14:21:11 +0800 Subject: [PATCH 047/274] =?UTF-8?q?=E5=8A=A0=E5=85=A5=20=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=20=E5=92=8C=20=E9=80=89=E6=8B=A9=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=E7=9A=84=20=E5=A4=A7=E6=A0=B7=E6=9C=AC=E6=B5=8B?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/basic_algorithm/InsertionSort.java | 108 +++++++++++++++++ Algorithms/basic_algorithm/SelectionSort.java | 110 ++++++++++++++++++ 2 files changed, 218 insertions(+) diff --git a/Algorithms/basic_algorithm/InsertionSort.java b/Algorithms/basic_algorithm/InsertionSort.java index d12e555..e699ac0 100644 --- a/Algorithms/basic_algorithm/InsertionSort.java +++ b/Algorithms/basic_algorithm/InsertionSort.java @@ -1,5 +1,7 @@ package basic_algorithm; +import java.util.Arrays; + public class InsertionSort { // 使用 java 实现的插入排序 public static void insertionSort(int[] arr) { @@ -25,5 +27,111 @@ public static void swap(int[] arr, int i, int j) { arr[i] = arr[j]; arr[j] = tmp; } + + + + +// for test (绝对正确的算法) +// 一般使用系统自带的排序算法,或者容易实现无错误的算法 + public static void rightMethod(int[] arr) { + Arrays.sort(arr); + } + + + + + +// for test +// 使用对数器进行测试 + public static int[] generateRandomArray(int size, int value) { +// 使用系统自带的随机数生成器生成备选数集合 +// Math.random() -> double [0,1) +// (int) ((size + 1) * Math.random()) -> [0,size] 整数集合 +// size =6, size + 1 =7; +// Math.random() -> [0,1) * 7 -> [0,7) double +// double -> int [0,6] -> int + + +// 生成长度随机的数组 + int[] arr = new int[(int) ((size + 1) * Math.random())]; +// 数组内的每个数也是随机的 + for (int i = 0; i < arr.length; i++) { + arr[i] = (int) ((value + 1) * Math.random()) - (int) (value * Math.random()); + } + return arr; + + } + +// for test +// 生成拷贝数组的方法 + public static int[] copyArray(int[] arr) { + if (arr == null) { + return null; + } + int[] res = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + res[i] = arr[i]; + } + return res; + } + +// for test +// 判断两个数组是否相同 + public static boolean isEqual(int[] arrone, int[] arrtwo) { + if((arrone == null && arrtwo != null) || (arrone != null && arrtwo == null)) { + return false; + } + if(arrone == null && arrtwo == null) { + return true; + } + if(arrone.length != arrtwo.length) { + return false; + } + for (int i = 0; i < arrone.length; i++) { + if (arrone[i] != arrtwo[i]) { + return false; + } + } + return true; + } + +// for test +// 打印数组的方法 + public static void printArray(int[] arr) { + if(arr == null || arr.length ==0) { + System.out.println(""); + }else { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + } + } + + +// 大样本测试 方法 + public static void main(String[] args) { + int testTime = 500000; + int size = 10; + int value = 100; + boolean succeed = true; + for (int i = 0; i < testTime; i++) { + int[] arrone = generateRandomArray(size, value); + int[] arrtwo = copyArray(arrone); + int[] arrthree = copyArray(arrone); + insertionSort(arrone); + rightMethod(arrtwo); + if(!isEqual(arrone, arrtwo)) { + succeed = false; + printArray(arrthree); + break; + } + } + + System.out.println(succeed ? "well done!" : "wrong algorithms!"); + + int[] arr = generateRandomArray(size, value); + printArray(arr); + + } } diff --git a/Algorithms/basic_algorithm/SelectionSort.java b/Algorithms/basic_algorithm/SelectionSort.java index ad5c57f..a673bbe 100644 --- a/Algorithms/basic_algorithm/SelectionSort.java +++ b/Algorithms/basic_algorithm/SelectionSort.java @@ -1,5 +1,7 @@ package basic_algorithm; +import java.util.Arrays; + public class SelectionSort { // 使用 java 实现的选择排序 @@ -23,4 +25,112 @@ public static void swap(int[] arr, int i, int j) { arr[i] = arr[j]; arr[j] = tmp; } + + + +// for test (绝对正确的算法) +// 一般使用系统自带的排序算法,或者容易实现无错误的算法 + public static void rightMethod(int[] arr) { + Arrays.sort(arr); + } + + + + + +// for test +// 使用对数器进行测试 + public static int[] generateRandomArray(int size, int value) { +// 使用系统自带的随机数生成器生成备选数集合 +// Math.random() -> double [0,1) +// (int) ((size + 1) * Math.random()) -> [0,size] 整数集合 +// size =6, size + 1 =7; +// Math.random() -> [0,1) * 7 -> [0,7) double +// double -> int [0,6] -> int + + +// 生成长度随机的数组 + int[] arr = new int[(int) ((size + 1) * Math.random())]; +// 数组内的每个数也是随机的 + for (int i = 0; i < arr.length; i++) { + arr[i] = (int) ((value + 1) * Math.random()) - (int) (value * Math.random()); + } + return arr; + + } + +// for test +// 生成拷贝数组的方法 + public static int[] copyArray(int[] arr) { + if (arr == null) { + return null; + } + int[] res = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + res[i] = arr[i]; + } + return res; + } + +// for test +// 判断两个数组是否相同 + public static boolean isEqual(int[] arrone, int[] arrtwo) { + if((arrone == null && arrtwo != null) || (arrone != null && arrtwo == null)) { + return false; + } + if(arrone == null && arrtwo == null) { + return true; + } + if(arrone.length != arrtwo.length) { + return false; + } + for (int i = 0; i < arrone.length; i++) { + if (arrone[i] != arrtwo[i]) { + return false; + } + } + return true; + } + +// for test +// 打印数组的方法 + public static void printArray(int[] arr) { + if(arr == null || arr.length ==0) { + System.out.println(""); + }else { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + } + } + + +// 大样本测试 方法 + public static void main(String[] args) { + int testTime = 500000; + int size = 10; + int value = 100; + boolean succeed = true; + for (int i = 0; i < testTime; i++) { + int[] arrone = generateRandomArray(size, value); + int[] arrtwo = copyArray(arrone); + int[] arrthree = copyArray(arrone); + selectionSort(arrone); + rightMethod(arrtwo); + if(!isEqual(arrone, arrtwo)) { + succeed = false; + printArray(arrthree); + break; + } + } + + System.out.println(succeed ? "well done!" : "wrong algorithms!"); + + int[] arr = generateRandomArray(size, value); + printArray(arr); + + } + + + } From 7f3dc0030542db624b5ad2e60ccefb3906d906f0 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 4 Oct 2018 21:49:31 +0800 Subject: [PATCH 048/274] add maxvalue file in basic algorithms --- Algorithms/basic_algorithm/FindMaxValue.java | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Algorithms/basic_algorithm/FindMaxValue.java diff --git a/Algorithms/basic_algorithm/FindMaxValue.java b/Algorithms/basic_algorithm/FindMaxValue.java new file mode 100644 index 0000000..f8a845d --- /dev/null +++ b/Algorithms/basic_algorithm/FindMaxValue.java @@ -0,0 +1,23 @@ +package basic_algorithm; + +public class FindMaxValue { + +// 使用递归求数组最大值 + public static int getMaxValue(int[] arr, int Ln, int Rn) { + if (Ln == Rn) { + return arr[Ln]; + } + int midn= (Ln + Rn)/2; + int maxLeft = getMaxValue(arr, Ln, midn); + int maxRight = getMaxValue(arr, midn+1, Rn); + return Math.max(maxLeft, maxRight); + + } + + public static void main(String[] args) { + int[] arr = {4, 3, 2, 1}; +// 调用递归实现找最大值 + System.out.println(getMaxValue(arr, 0, arr.length - 1)); + } + +} From e2e829593bbecad00e63cf715c1f2dcf02a4f7a6 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 5 Oct 2018 15:34:24 +0800 Subject: [PATCH 049/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0java=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=20=E5=BD=92=E5=B9=B6=E6=8E=92=E5=BA=8F=20=E7=9A=84?= =?UTF-8?q?=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/basic_algorithm/MergeSort.java | 70 +++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Algorithms/basic_algorithm/MergeSort.java diff --git a/Algorithms/basic_algorithm/MergeSort.java b/Algorithms/basic_algorithm/MergeSort.java new file mode 100644 index 0000000..837da54 --- /dev/null +++ b/Algorithms/basic_algorithm/MergeSort.java @@ -0,0 +1,70 @@ +package basic_algorithm; + +public class MergeSort { + +// 使用 java 实现归并排序 + public static void mergeSort(int[] arr) { + if (arr == null || arr.length < 2) { + return; + } +// 递归过程,是排序的实质 + sortProgress(arr, 0, arr.length - 1); + + } + + public static void sortProgress(int[] arr, int Ln, int Rn) { +// 实现 在 Ln 和 Rn 之间排好序 (0, N-1) + +// 若范围上只有一个数,已经排好了 + if (Ln == Rn) { + return; + } + int midn = Ln + ((Rn - Ln) >> 1); // Ln 和 Rn 中点的位置 +// same as (Ln + Rn) / 2 +// 在 Ln 和 middle 中间排好序 + sortProgress(arr, Ln, midn); // T(N/2) +// 在 middle + 1 和 Rn 间排好序 + sortProgress(arr, midn + 1, Rn); // T(N/2) +// 进行 merge 操作 + merge(arr, Ln, midn, Rn); // O(N) +// T(N) = 2*T(N/2) + O(N) + + } + +// 实现 已排好序的Ln ~ midn 与 已排好序的 midn+1 ~ Rn 整体的排序 + public static void merge(int[] arr, int Ln, int midn, int Rn) { +// 辅助数组,有多少就生成多大的 + int[] help = new int[Rn - Ln +1]; + int i = 0; + + int pone = Ln; + int ptwo = midn +1; +// 保证两侧都没有 比完 + while (pone <= midn && ptwo <= Rn) { +// 实现 谁小填谁 的功能 + help[i++] = arr[pone] < arr[ptwo] ? arr[pone++] : arr[ptwo++]; + } + +// 两个必定 有一个会越界,两个只会执行一个 +// copy 那些没有越界 对应的 值,放在后面 + while (pone <= midn) { +// 若 pone 没有越界,潜台词是 ptwo 必定越界了 + help[i++] = arr[pone++]; + } + + while (ptwo <= Rn) { + help[i++] = arr[ptwo++]; + } + +// 将 help数组里的 copy 回 arr + for (int j = 0; j < help.length; j++) { + arr[Ln +j] = help[j]; + } + + } + + public static void comparator(int[] arr) { + + + } +} From 7857fe731343422a7b715d2c9176e2e1b10c5f49 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 5 Oct 2018 15:40:42 +0800 Subject: [PATCH 050/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=B9=E6=95=B0?= =?UTF-8?q?=E5=99=A8=20=E6=B5=8B=E8=AF=95=E6=96=B9=E6=B3=95=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E6=B5=8B=E8=AF=95=E5=BD=92=E5=B9=B6=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/basic_algorithm/MergeSort.java | 107 ++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/Algorithms/basic_algorithm/MergeSort.java b/Algorithms/basic_algorithm/MergeSort.java index 837da54..7e2b7e7 100644 --- a/Algorithms/basic_algorithm/MergeSort.java +++ b/Algorithms/basic_algorithm/MergeSort.java @@ -1,5 +1,7 @@ package basic_algorithm; +import java.util.Arrays; + public class MergeSort { // 使用 java 实现归并排序 @@ -64,7 +66,112 @@ public static void merge(int[] arr, int Ln, int midn, int Rn) { } public static void comparator(int[] arr) { + System.out.println("this is comparator"); + } + + +// for test (绝对正确的算法) +// 一般使用系统自带的排序算法,或者容易实现无错误的算法 + public static void rightMethod(int[] arr) { + Arrays.sort(arr); + } + + + + + +// for test +// 使用对数器进行测试 + public static int[] generateRandomArray(int size, int value) { +// 使用系统自带的随机数生成器生成备选数集合 +// Math.random() -> double [0,1) +// (int) ((size + 1) * Math.random()) -> [0,size] 整数集合 +// size =6, size + 1 =7; +// Math.random() -> [0,1) * 7 -> [0,7) double +// double -> int [0,6] -> int + + +// 生成长度随机的数组 + int[] arr = new int[(int) ((size + 1) * Math.random())]; +// 数组内的每个数也是随机的 + for (int i = 0; i < arr.length; i++) { + arr[i] = (int) ((value + 1) * Math.random()) - (int) (value * Math.random()); + } + return arr; } + +// for test +// 生成拷贝数组的方法 + public static int[] copyArray(int[] arr) { + if (arr == null) { + return null; + } + int[] res = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + res[i] = arr[i]; + } + return res; + } + +// for test +// 判断两个数组是否相同 + public static boolean isEqual(int[] arrone, int[] arrtwo) { + if((arrone == null && arrtwo != null) || (arrone != null && arrtwo == null)) { + return false; + } + if(arrone == null && arrtwo == null) { + return true; + } + if(arrone.length != arrtwo.length) { + return false; + } + for (int i = 0; i < arrone.length; i++) { + if (arrone[i] != arrtwo[i]) { + return false; + } + } + return true; + } + +// for test +// 打印数组的方法 + public static void printArray(int[] arr) { + if(arr == null || arr.length ==0) { + System.out.println(""); + }else { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + } + } + + +// 大样本测试 方法 + public static void main(String[] args) { + int testTime = 500000; + int size = 10; + int value = 100; + boolean succeed = true; + for (int i = 0; i < testTime; i++) { + int[] arrone = generateRandomArray(size, value); + int[] arrtwo = copyArray(arrone); + int[] arrthree = copyArray(arrone); + mergeSort(arrone); + rightMethod(arrtwo); + if(!isEqual(arrone, arrtwo)) { + succeed = false; + printArray(arrthree); + break; + } + } + + System.out.println(succeed ? "well done!" : "wrong algorithms!"); + + int[] arr = generateRandomArray(size, value); + printArray(arr); + + } + } From 8481a59d32448040e361937830aab5baff4c5679 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 5 Oct 2018 16:26:42 +0800 Subject: [PATCH 051/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=B0=8F=E5=92=8C?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E7=9A=84=20=E5=BD=92=E5=B9=B6=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=E6=80=9D=E8=B7=AF=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/basic_algorithm/SmallSum.java | 53 ++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Algorithms/basic_algorithm/SmallSum.java diff --git a/Algorithms/basic_algorithm/SmallSum.java b/Algorithms/basic_algorithm/SmallSum.java new file mode 100644 index 0000000..fd037a3 --- /dev/null +++ b/Algorithms/basic_algorithm/SmallSum.java @@ -0,0 +1,53 @@ +package basic_algorithm; + +public class SmallSum { + +// 使用 java 实现 小和问题 + public static int smallSum(int[] arr) { + if (arr == null || arr.length < 2) { + return 0; + } + return mergeSort(arr, 0, arr.length - 1); + } + +// 返回的 ln 到 rn 之间的所有小和 + public static int mergeSort(int[] arr, int ln, int rn) { + if (ln == rn) { + return 0; + } + int midn = ln + ((rn - ln) >> 1); +// 整体的小和 = 左侧部分产生的小和 + 右侧部分产生的小和 + merge过程中产生的小和 + return mergeSort(arr, ln, midn) + + mergeSort(arr, midn + 1, rn) + + merge(arr, ln, midn, rn); + } + + public static int merge(int[] arr, int ln, int mn, int rn) { + int[] help = new int[rn - ln +1]; + int i =0; + int pone =ln; + int ptwo = mn +1; + int res = 0; + while (pone <= mn && ptwo <= rn) { + res += arr[pone] < arr[ptwo] ? (rn - ptwo +1) * arr[pone] : 0; + help[i++] = arr[pone] < arr[ptwo] ? arr[pone++] : arr[ptwo++]; + } + + while (pone <= mn) { +// 若 pone 没有越界,潜台词是 ptwo 必定越界了 + help[i++] = arr[pone++]; + } + + while (ptwo <= rn) { + help[i++] = arr[ptwo++]; + } + +// 将 help数组里的 copy 回 arr + for (int j = 0; j < help.length; j++) { + arr[ln +j] = help[j]; + } + + return res; + + } +} From 2b1ba23471fde1e915bdbbad31d4521dd63e3cd6 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Oct 2018 10:34:30 +0800 Subject: [PATCH 052/274] repart basic_algorithms src --- .vscode/launch.json | 14 ++++++++++++++ .../{ => SortAlgorithmsbyJava}/BubbleSort.java | 0 .../{ => SortAlgorithmsbyJava}/InsertionSort.java | 0 .../{ => SortAlgorithmsbyJava}/MergeSort.java | 0 .../{ => SortAlgorithmsbyJava}/SelectionSort.java | 0 5 files changed, 14 insertions(+) create mode 100644 .vscode/launch.json rename Algorithms/basic_algorithm/{ => SortAlgorithmsbyJava}/BubbleSort.java (100%) rename Algorithms/basic_algorithm/{ => SortAlgorithmsbyJava}/InsertionSort.java (100%) rename Algorithms/basic_algorithm/{ => SortAlgorithmsbyJava}/MergeSort.java (100%) rename Algorithms/basic_algorithm/{ => SortAlgorithmsbyJava}/SelectionSort.java (100%) diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..2448d07 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,14 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - BubbleSort", + "request": "launch", + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "stopOnEntry": false, + "mainClass": "basic_algorithm.BubbleSort", + "args": "" + } + ] +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/BubbleSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/BubbleSort.java similarity index 100% rename from Algorithms/basic_algorithm/BubbleSort.java rename to Algorithms/basic_algorithm/SortAlgorithmsbyJava/BubbleSort.java diff --git a/Algorithms/basic_algorithm/InsertionSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/InsertionSort.java similarity index 100% rename from Algorithms/basic_algorithm/InsertionSort.java rename to Algorithms/basic_algorithm/SortAlgorithmsbyJava/InsertionSort.java diff --git a/Algorithms/basic_algorithm/MergeSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/MergeSort.java similarity index 100% rename from Algorithms/basic_algorithm/MergeSort.java rename to Algorithms/basic_algorithm/SortAlgorithmsbyJava/MergeSort.java diff --git a/Algorithms/basic_algorithm/SelectionSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/SelectionSort.java similarity index 100% rename from Algorithms/basic_algorithm/SelectionSort.java rename to Algorithms/basic_algorithm/SortAlgorithmsbyJava/SelectionSort.java From ca1c9b06c2e7cdd52d5c5b47ad58706c8da5685d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Oct 2018 10:56:02 +0800 Subject: [PATCH 053/274] use JavaScript to create BubbleSort --- .../SortAlgorithmsbyJavaScript/BubbleSort.js | 28 +++++++++++++++++++ .../SortAlgorithmsbyJavaScript/mainSort.js | 20 +++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js new file mode 100644 index 0000000..a12a622 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js @@ -0,0 +1,28 @@ +/** + * @author SkylineBin + * @time 2018-10-6 + * @function use javascript to bubble sort arrays + * + * + */ + + module.exports = function BubbleSort(arrays){ + if(arrays == null || arrays.length < 2){ + return; + } + for (let index = arrays.length - 1; index > 0; index--) { + for (let i = 0; i < index; i++) { + if (arrays[i] > arrays[i+1]) { + swap(arrays, i, i+1); + console.log(arrays); + } + } + + } + } + + function swap(arrays, si, sj){ + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; + } \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js new file mode 100644 index 0000000..d688045 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -0,0 +1,20 @@ +/** + * @author SkylineBin + * @time 2018-10-6 + * @function test BubbleSort + * + * + */ + + const BubbleSort = require('./BubbleSort'); + + let arrone = [3,6,2,4,0,5,9]; + + console.log(arrone); + + console.log('--------start BubbleSort-----------'); + + BubbleSort(arrone); + + console.log('--------end BubbleSort-----------'); + console.log(arrone); \ No newline at end of file From c7339e7297278829fabdf643786cc87dc30ce6be Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Oct 2018 11:05:18 +0800 Subject: [PATCH 054/274] add SelectionSort by JavaScript --- .../SelectionSort.js | 26 +++++++++++++++++++ .../SortAlgorithmsbyJavaScript/mainSort.js | 16 +++++++++--- 2 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js new file mode 100644 index 0000000..7059d65 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js @@ -0,0 +1,26 @@ +/** + * @author SkylineBin + * @time 2018-10-6 + * @function use javascript to create SelectionSort + * + */ + +module.exports = function SelectionSort(arrays){ + if (arrays == null || arrays.length < 2) { + return; + } + for (let index = 0; index < arrays.length - 1; index++) { + let minIndex = index; + for (let j = index + 1; j < arrays.length; j++) { + minIndex = arrays[j] < arrays[minIndex] ? j : minIndex; + } + swap(arrays, index, minIndex); + console.log(arrays); + } +} + + function swap(arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; + } \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js index d688045..9b15e07 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -7,14 +7,24 @@ */ const BubbleSort = require('./BubbleSort'); + const SelectionSort = require('./SelectionSort'); let arrone = [3,6,2,4,0,5,9]; console.log(arrone); - console.log('--------start BubbleSort-----------'); +// console.log('--------start BubbleSort-----------'); + +// BubbleSort(arrone); + +// console.log('--------end BubbleSort-----------'); + + + console.log('--------start SelectionSort-----------'); + + SelectionSort(arrone); + + console.log('--------end SelectionSort-----------'); - BubbleSort(arrone); - console.log('--------end BubbleSort-----------'); console.log(arrone); \ No newline at end of file From 9a03c59b1e50c8baa591836b0682a33e8f264ff7 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Oct 2018 11:08:23 +0800 Subject: [PATCH 055/274] add Comment in this two sort algorithms --- .../basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js | 2 ++ .../SortAlgorithmsbyJavaScript/SelectionSort.js | 3 +++ 2 files changed, 5 insertions(+) diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js index a12a622..4d8d150 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js @@ -3,6 +3,8 @@ * @time 2018-10-6 * @function use javascript to bubble sort arrays * + * @Algorithm_bigO O(N^2) + * N is the length of arrays * */ diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js index 7059d65..b9407ce 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js @@ -2,6 +2,9 @@ * @author SkylineBin * @time 2018-10-6 * @function use javascript to create SelectionSort + * + * @Algorithm_bigO O(N ^ 2) + * N is the length of arrays * */ From afcf697940dfa0f0f02f960e1e8f47bc64ca8c13 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Oct 2018 11:21:16 +0800 Subject: [PATCH 056/274] add InsertionSort by JavaScript --- .../InsertionSort.js | 29 +++++++++++++++++++ .../SortAlgorithmsbyJavaScript/mainSort.js | 13 +++++++-- 2 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js new file mode 100644 index 0000000..7c832e9 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js @@ -0,0 +1,29 @@ +/** + * @author SkylineBin + * @time 2018-10-6 + * @function create InsertionSort by JavaScript + * + * @Algorithm_bigO + * best_bigO = O(N) + * worst_bigO = O(N^2) + * + */ + +module.exports = function InsertionSort(arrays) { + if (arrays == null || arrays.length < 2) { + return; + } + for (let i = 1; i < arrays.length; i++) { + for (let j = i - 1; j >= 0 && arrays[j] > arrays[j + 1]; j--) { + swap(arrays, j, j+1); + console.log(arrays); + } + + } +} + +function swap(arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js index 9b15e07..9bd5e1b 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -8,6 +8,7 @@ const BubbleSort = require('./BubbleSort'); const SelectionSort = require('./SelectionSort'); + const InsertionSort = require('./InsertionSort'); let arrone = [3,6,2,4,0,5,9]; @@ -20,11 +21,17 @@ // console.log('--------end BubbleSort-----------'); - console.log('--------start SelectionSort-----------'); +// console.log('--------start SelectionSort-----------'); - SelectionSort(arrone); +// SelectionSort(arrone); - console.log('--------end SelectionSort-----------'); +// console.log('--------end SelectionSort-----------'); + + console.log('--------start InsertionSort-----------'); + + InsertionSort(arrone); + + console.log('--------end InsertionSort-----------'); console.log(arrone); \ No newline at end of file From 975f989b52df6081402042fcf642837be7dbec44 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Oct 2018 17:24:16 +0800 Subject: [PATCH 057/274] create MergeSort by JavaScript --- .../SortAlgorithmsbyJavaScript/MergeSort.js | 51 +++++++++++++++++++ .../SortAlgorithmsbyJavaScript/mainSort.js | 12 +++-- 2 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js new file mode 100644 index 0000000..9aa7280 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js @@ -0,0 +1,51 @@ +/** + * @author SkylineBin + * @time 2018-10-6 + * @function create MergeSort by JavaScript + * + * @Algorithm_bigO + * O(N * log(N)) + * + */ + + module.exports = function MergeSort(arrays) { + if (arrays == null || arrays.length < 2) { + return; + } + // Recursive process + sortProgress(arrays, 0, arrays.length - 1); + } + + function sortProgress(arrays, Ln, Rn) { + if (Ln == Rn){ + return; + } + let midn = Ln + ((Rn - Ln) >> 1); + sortProgress(arrays, Ln, midn); + sortProgress(arrays, midn + 1, Rn); + merge(arrays, Ln, midn, Rn); + console.log(arrays); + } + + function merge(arrays, Ln, midn, Rn) { + let temparrays = new Array(); + let ti = 0; + let pone = Ln; + let ptwo = midn + 1; + while (pone <= midn && ptwo <= Rn) { + // outside sort, insert it which is small than another + temparrays[ti++] = arrays[pone] < arrays[ptwo] ? arrays[pone++] : arrays[ptwo++]; + } + + while (pone <= midn) { + temparrays[ti++] = arrays[pone++]; + } + + while (ptwo <= Rn) { + temparrays[ti++] = arrays[ptwo++]; + } + + for (let index = 0; index < temparrays.length; index++) { + arrays[Ln + index] = temparrays[index]; + } + } \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js index 9bd5e1b..0aa04f1 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -9,6 +9,7 @@ const BubbleSort = require('./BubbleSort'); const SelectionSort = require('./SelectionSort'); const InsertionSort = require('./InsertionSort'); + const MergeSort = require('./MergeSort'); let arrone = [3,6,2,4,0,5,9]; @@ -27,11 +28,16 @@ // console.log('--------end SelectionSort-----------'); - console.log('--------start InsertionSort-----------'); +// console.log('--------start InsertionSort-----------'); - InsertionSort(arrone); +// InsertionSort(arrone); - console.log('--------end InsertionSort-----------'); +// console.log('--------end InsertionSort-----------'); + console.log('--------start MergeSort-----------'); + + MergeSort(arrone); + + console.log('--------end MergeSort-----------'); console.log(arrone); \ No newline at end of file From ea8d2366df3d96ce03c91fe4a7f85279d9d1c29d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Oct 2018 19:36:15 +0800 Subject: [PATCH 058/274] add SmallSum by JavaScript --- Algorithms/README.md | 9 +++- .../basic_algorithm/SmallSumbyJavaScript.js | 54 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 Algorithms/basic_algorithm/SmallSumbyJavaScript.js diff --git a/Algorithms/README.md b/Algorithms/README.md index 9499987..17e3c16 100644 --- a/Algorithms/README.md +++ b/Algorithms/README.md @@ -1,3 +1,10 @@ ## Algorithms -Some classic algorithms are always worth learning! +Some classic algorithms are always worth learning! + + +### basic_algorithm +we practice some basic algorithms by Java or JavaScript! + +### Disk Scheduling Algorithm +some disk Scheduling algorithms by Java! diff --git a/Algorithms/basic_algorithm/SmallSumbyJavaScript.js b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js new file mode 100644 index 0000000..03ef4e3 --- /dev/null +++ b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js @@ -0,0 +1,54 @@ +/***** + * + * @author SkylineBin + * @time 2018-10-6 + * @function use mergesort to caculate small sum of one array + * + */ + + + function smallSum(arrays) { + if (arrays == null || arrays.length < 2) { + return 0; + } + return camergeSort(arrays, 0, arrays.length -1); + } + + function camergeSort(arrays, ln, rn) { + if (ln == rn) { + return 0; + } + let midn = ln + ((rn - ln) >> 1); + return camergeSort(arrays, ln, midn) + camergeSort(arrays, midn + 1, rn) + caMerge(arrays, ln, midn, rn); + } + + function caMerge(arrays, ln, midn, rn){ + let temparrays = new Array(); + let ti = 0; + let pone = ln; + let ptwo = midn + 1; + let resultsum = 0; + while (pone <= midn && ptwo <= rn) { + // outside sort, insert it which is small than another + resultsum += arrays[pone] < arrays[ptwo] ? (rn - ptwo + 1) * arrays[pone] : 0; + temparrays[ti++] = arrays[pone] < arrays[ptwo] ? arrays[pone++] : arrays[ptwo++]; + } + + while (pone <= midn) { + temparrays[ti++] = arrays[pone++]; + } + + while (ptwo <= rn) { + temparrays[ti++] = arrays[ptwo++]; + } + + for (let index = 0; index < temparrays.length; index++) { + arrays[ln + index] = temparrays[index]; + } + return resultsum; + } + + + let testArrays = [1, 3, 4, 2, 5]; + console.log('this array is: '+ testArrays); + console.log('the small sum of this array is: ' + smallSum(testArrays)); \ No newline at end of file From 3065313e16850066af0397a4bb8a70a872ca16d8 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 7 Oct 2018 19:04:01 +0800 Subject: [PATCH 059/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=80=86=E5=BA=8F?= =?UTF-8?q?=E5=AF=B9=E9=97=AE=E9=A2=98=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../basic_algorithm/InversionbyJavaScript.js | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Algorithms/basic_algorithm/InversionbyJavaScript.js diff --git a/Algorithms/basic_algorithm/InversionbyJavaScript.js b/Algorithms/basic_algorithm/InversionbyJavaScript.js new file mode 100644 index 0000000..d47f37d --- /dev/null +++ b/Algorithms/basic_algorithm/InversionbyJavaScript.js @@ -0,0 +1,56 @@ +/**** + * + * @author SkylineBin + * @time 2018-10-7 + * @function print all inversions of one array by JavaScript + * + */ + +function printInversion(arrays) { + if (arrays == null || arrays.length <2){ + return ''; + } + return processInversion(arrays, 0, arrays.length - 1); +} + +function processInversion(arrays, ln, rn) { + if (ln == rn) { + return ''; + } + let midn = ln + ((rn - ln) >> 1); + return String(processInversion(arrays, ln, midn)) + String(processInversion(arrays, midn + 1, rn)) + String(outallInversion(arrays, ln, midn, rn)); +} + +function outallInversion(arrays, ln, midn, rn) { + let temparrays = new Array(); + let ti = 0; + let pone = ln; + let ptwo = midn + 1; + let resultsum = ''; + while (pone <= midn && ptwo <= rn) { + // outside sort, insert it which is small than another + resultsum += arrays[pone] > arrays[ptwo] ? String(String(arrays[pone])+'_'+String(arrays[ptwo])+"#") : ''; + // temparrays[ti++] = arrays[pone] > arrays[ptwo] ? arrays[ptwo++] : arrays[pone++]; + temparrays[ti++] = arrays[pone] > arrays[ptwo] ? arrays[pone++] : arrays[ptwo++]; + } + + while (pone <= midn) { + temparrays[ti++] = arrays[pone++]; + } + + while (ptwo <= rn) { + temparrays[ti++] = arrays[ptwo++]; + } + + for (let index = 0; index < temparrays.length; index++) { + arrays[ln + index] = temparrays[index]; + } + return resultsum; + +} + + +// let testArrays = [1, 3, 4, 2, 5]; + let testArrays = [3, 1, 2, 4, 0, 7, 5]; + console.log('this array is: ' + testArrays); + console.log('the small sum of this array is: ' + printInversion(testArrays)); \ No newline at end of file From 64ceaa4e5de00f2581b0d5e4952a471b073d7a40 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 7 Oct 2018 19:20:18 +0800 Subject: [PATCH 060/274] =?UTF-8?q?=E5=AE=9E=E7=8E=B0Java=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E7=9A=84=20=E9=80=86=E5=BA=8F=E5=AF=B9=E8=A7=A3?= =?UTF-8?q?=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/basic_algorithm/Inversion.java | 98 +++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Algorithms/basic_algorithm/Inversion.java diff --git a/Algorithms/basic_algorithm/Inversion.java b/Algorithms/basic_algorithm/Inversion.java new file mode 100644 index 0000000..738df0a --- /dev/null +++ b/Algorithms/basic_algorithm/Inversion.java @@ -0,0 +1,98 @@ +package basic_algorithm; + +public class Inversion { + +// 使用Java 解决逆序对问题 + public static String printInversion(int[] arr) { + if (arr == null || arr.length < 2) { + return ""; + } + return mergeSort(arr, 0, arr.length - 1); + } + +// 返回的 ln 到 rn 之间的所有逆序对 + public static String mergeSort(int[] arr, int ln, int rn) { + if (ln == rn) { + return ""; + } + int midn = ln + ((rn - ln) >> 1); +// 整体的小和 = 左侧部分产生的小和 + 右侧部分产生的小和 + merge过程中产生的小和 + return mergeSort(arr, ln, midn) + + mergeSort(arr, midn + 1, rn) + + mergeInversion(arr, ln, midn, rn); + } + + public static String mergeInversion(int[] arr, int ln, int midn, int rn) { + int[] help = new int[rn - ln +1]; + int i =0; + int pone =ln; + int ptwo = midn +1; + String res = ""; + while (pone <= midn && ptwo <= rn) { + res += arr[pone] > arr[ptwo] ? Integer.toString(arr[pone]) + "_" + Integer.toString(arr[ptwo])+"#" : ""; + help[i++] = arr[pone] > arr[ptwo] ? arr[pone++] : arr[ptwo++]; + } + + while (pone <= midn) { +// 若 pone 没有越界,潜台词是 ptwo 必定越界了 + help[i++] = arr[pone++]; + } + + while (ptwo <= rn) { + help[i++] = arr[ptwo++]; + } + +// 将 help数组里的 copy 回 arr + for (int j = 0; j < help.length; j++) { + arr[ln +j] = help[j]; + } + + return res; + } + +// for test +// 使用对数器进行测试 + public static int[] generateRandomArray(int size, int value) { +// 使用系统自带的随机数生成器生成备选数集合 +// Math.random() -> double [0,1) +// (int) ((size + 1) * Math.random()) -> [0,size] 整数集合 +// size =6, size + 1 =7; +// Math.random() -> [0,1) * 7 -> [0,7) double +// double -> int [0,6] -> int + + +// 生成长度随机的数组 + int[] arr = new int[(int) ((size + 1) * Math.random())]; +// 数组内的每个数也是随机的 + for (int i = 0; i < arr.length; i++) { + arr[i] = (int) ((value + 1) * Math.random()) - (int) (value * Math.random()); + } + return arr; + + } + +// for test +// 打印数组的方法 + public static void printArray(int[] arr) { + if(arr == null || arr.length ==0) { + System.out.println(""); + }else { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + System.out.println(); + } + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + int size = 10; + int value = 100; + int[] arrone = generateRandomArray(size, value); + printArray(arrone); + System.out.println(printInversion(arrone)); + + } + +} From 090afd4d87fdb1fd22ed8cfdc5b7b1d4593eb87d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 8 Oct 2018 12:37:00 +0800 Subject: [PATCH 061/274] add insert and toString function of LinkedList --- DataStructures/LinkedList/UseLinkedList.js | 39 ++++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/DataStructures/LinkedList/UseLinkedList.js b/DataStructures/LinkedList/UseLinkedList.js index b6a3134..c64ac6e 100644 --- a/DataStructures/LinkedList/UseLinkedList.js +++ b/DataStructures/LinkedList/UseLinkedList.js @@ -33,11 +33,36 @@ function LinkedList() { // insert an element into this position this.insert = function(position, element) { + if (position > -1 && position < length) { + let node = new Node(element), + current = head, + previous, + index = 0; - } + if (position === 0) { + // insert element at the head of this LinkedList + node.next = current; + head = node; + } else { + while (index++ < position) { + previous = current; + current = current.next; + } + + // insert elemrnt in this position + node.next = current; + previous.next = node; + } + length++; + return true; + } else { + return false; + } + }; // remove the element at this position this.removeAt = function(position){ + // check Cross-border if(position > -1 && position < length){ let current = head, previous, @@ -50,7 +75,7 @@ function LinkedList() { previous = current; current = current.next; } - + // current element will be recyclied by JavaScript GC previous.next = current.next; } length--; @@ -59,7 +84,7 @@ function LinkedList() { }else { return null; } - } + }; // remove one element from this linkedlist this.remove = function(element){ @@ -88,6 +113,14 @@ function LinkedList() { // to String this.toString = function() { + let current = head; + string = ''; + while (current) { + string += current.element + (current.next ? '_': ''); + current = current.next; + } + return string; + } From fb04a78fbe8525af983e76697864c2ab01e22806 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 8 Oct 2018 12:45:16 +0800 Subject: [PATCH 062/274] add other fundamental functions --- DataStructures/LinkedList/UseLinkedList.js | 28 +++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/DataStructures/LinkedList/UseLinkedList.js b/DataStructures/LinkedList/UseLinkedList.js index c64ac6e..58d19c8 100644 --- a/DataStructures/LinkedList/UseLinkedList.js +++ b/DataStructures/LinkedList/UseLinkedList.js @@ -88,27 +88,39 @@ function LinkedList() { // remove one element from this linkedlist this.remove = function(element){ - - } + // find the position + // remove this element at the position + let index = this.indexOf(element); + return this.removeAt(index); + }; // find the index of this linkedlist this.indexOf = function(element) { - - } + let current = head; + index = -1; + while (current) { + if (element === current.element) { + return index; + } + index++; + current = current.next; + } + return -1; + }; // check this linkedlist is empty this.isEmpty = function(){ - - } + return length === 0; + }; // get the size of this linkedlist this.size = function(){ - + return length; } // get the head of this LinkedList this.getHead = function(){ - + return head; } // to String From 271ac9a13f21f1c6781287faba48ca682fb7fe49 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 10 Oct 2018 12:22:17 +0800 Subject: [PATCH 063/274] =?UTF-8?q?=E6=89=93=E5=8D=B0=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E6=89=80=E6=9C=89=E5=85=83=E7=B4=A0=E7=9A=84?= =?UTF-8?q?=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/LinkedList/UseLinkedList.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/DataStructures/LinkedList/UseLinkedList.js b/DataStructures/LinkedList/UseLinkedList.js index 58d19c8..2cd01c9 100644 --- a/DataStructures/LinkedList/UseLinkedList.js +++ b/DataStructures/LinkedList/UseLinkedList.js @@ -138,11 +138,25 @@ function LinkedList() { // print this LinkedList this.print = function(){ - + let current = head; + let outstr = ''; + while (current) { + // console.log(current.element); + outstr += String(current.element) + (current.next ? ' ':''); + current = current.next; + } + console.log('------------------------------------'); + console.log(outstr); + console.log('------------------------------------'); } } let list = new LinkedList(); list.append(10); -list.append(15); \ No newline at end of file +list.append(15); +list.append(4); +list.append(16); +list.append(13); + +list.print(); \ No newline at end of file From 69a040212bb10f717d3e63b62d979f4f2e5e8fab Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 10 Oct 2018 12:44:40 +0800 Subject: [PATCH 064/274] add DoublyLinkedList Structure --- .../LinkedList/UseDoublyLinkedList.js | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 DataStructures/LinkedList/UseDoublyLinkedList.js diff --git a/DataStructures/LinkedList/UseDoublyLinkedList.js b/DataStructures/LinkedList/UseDoublyLinkedList.js new file mode 100644 index 0000000..1eb9148 --- /dev/null +++ b/DataStructures/LinkedList/UseDoublyLinkedList.js @@ -0,0 +1,30 @@ +/**** + * + * @author SkylineBin + * @time 2018-10-10 + * @function create doublyLinkedList by JavaScript + * + */ + + function DoublyLinkedList( ) { + let Node = function(element) { + this.element = element; + this.next = null; + this.prev = null; + } + + let length = 0; + let head = null; + let tail = null; + + // insert a element at this position + this.insert = function(position,element) { + + }; + + // remove element at this position + this.removeAt = function(position) { + + }; + + } \ No newline at end of file From 0f18793d68c98665dbf561cdceddcd95cd0ee64f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 10 Oct 2018 23:48:40 +0800 Subject: [PATCH 065/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=8C=E5=90=91?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9A=84=20=E6=8F=92=E5=85=A5=20=E5=92=8C=20?= =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=85=83=E7=B4=A0=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 都是有三种位置情况 --- .../LinkedList/UseDoublyLinkedList.js | 74 ++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/DataStructures/LinkedList/UseDoublyLinkedList.js b/DataStructures/LinkedList/UseDoublyLinkedList.js index 1eb9148..6dba6e8 100644 --- a/DataStructures/LinkedList/UseDoublyLinkedList.js +++ b/DataStructures/LinkedList/UseDoublyLinkedList.js @@ -19,12 +19,82 @@ // insert a element at this position this.insert = function(position,element) { - + if (position >= 0 && position <= length) { + let node = new Node(element), + current = head, + previous, + index = 0; + + if (position === 0) { + // 在双向链表的头部插入一个元素 + if (!head) { + head = node; + tail = node; + } else { + node.next = current; + current.prev = node; + head = node; + } + } else if (position === length) { + // 在链表的尾部插入一个元素 + current = tail; + current.next = node; + node.prev = current; + tail = node; + } else { + // 在链表中间插入该元素 + while (index++ < position) { + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + current.prev = node; + node.prev = previous; + } + + length++; + return true; + } else { + return false; + } }; // remove element at this position this.removeAt = function(position) { - + if (position > -1 && position < length) { + let current = head, + previous, + index = 0; + + if (position === 0) { + head = current.next; + + if (length === 1) { + tail = null; + } else { + head.prev = null; + } + } else if (position === length - 1){ + current = tail; + tail = current.prev; + tail.next = null; + } else { + while (index++ < position) { + previous = current; + current = current.next; + } + + // 直接连接 前一项 和 后一项 + previous.next = current.next; + current.next.prev = previous; + } + + length--; + return current.element; + } else { + return null; + } }; } \ No newline at end of file From 829e5b6f42a36435dd9946b03a14b4d21e22ddff Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 11 Oct 2018 12:34:48 +0800 Subject: [PATCH 066/274] add Set Data Structure --- DataStructures/Set/UseSetbySelf.js | 102 +++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 DataStructures/Set/UseSetbySelf.js diff --git a/DataStructures/Set/UseSetbySelf.js b/DataStructures/Set/UseSetbySelf.js new file mode 100644 index 0000000..8e7e7cf --- /dev/null +++ b/DataStructures/Set/UseSetbySelf.js @@ -0,0 +1,102 @@ +/**** + * + * @author SkylineBin + * @time 2018-10-11 + * @function create a set structure by JavaScript + * + */ + + function SetS() { + let items = {}; + + // check if value in this set + this.has = function (value) { + // return value in items; // old function + return items.hasOwnProperty(value); + } + + // add this value + this.add = function (value) { + if (!this.has(value)) { + items[value] = value; + return true; + } + return false; + }; + + // remove this value from this Set + this.remove = function(value) { + if (this.has(value)) { + delete items[value]; + return true; + } + return false; + }; + + // clear this set + this.clear = function () { + items = {}; + } + + // get the size of this Set + this.size = function () { + return Object.keys(items).length; + } + + // another function of getting the size of this Set + this.sizeLegacy = function (){ + let count = 0; + for (let key in items) { + if (items.hasOwnProperty(key)) { + // avoid count the repeated key + ++count; + } + } + return count; + }; + + // get all values of this Set + this.values = function() { + let values = []; + for (let index = 0, keys=Object.keys(items); index < keys.length; index++) { + values.push(items[keys[index]]); + } + return values; + } + + this.valuesLegacy = function (){ + let values = []; + for (let key in items) { + if (items.hasOwnProperty(key)) { + values.push(items[key]); + } + } + return values; + }; + + + + } + + + let set = new SetS(); + set.add(1); + set.add(2); + set.add(6); + set.add(7); + console.log('------------------------------------'); + console.log(set.values()); + console.log('------------------------------------'); + console.log(set.has(1)); + console.log('------------------------------------'); +console.log(set.size()); +console.log('------------------------------------'); +set.add(4); +set.add(7); +console.log('------------------------------------'); +console.log(set.values()); +console.log('------------------------------------'); +set.remove(2); +console.log('------------------------------------'); +console.log(set.values()); +console.log('------------------------------------'); From 9a727c5c345e5797e37b6dccb3e2a0533e8a7b23 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 11 Oct 2018 12:46:06 +0800 Subject: [PATCH 067/274] update some markdown texts --- DataStructures/README.md | 6 +++++- HuaWeiOJ Algorithms/OtherOJ.md | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 HuaWeiOJ Algorithms/OtherOJ.md diff --git a/DataStructures/README.md b/DataStructures/README.md index 45c46eb..dd77983 100644 --- a/DataStructures/README.md +++ b/DataStructures/README.md @@ -12,4 +12,8 @@ Using JavaScript to create the Queue Structure ## LinkedList -Using JavaScript to create the LinkedList Structure \ No newline at end of file +Using JavaScript to create the LinkedList Structure + +## Set + +Using JavaScript to create the Set Structure \ No newline at end of file diff --git a/HuaWeiOJ Algorithms/OtherOJ.md b/HuaWeiOJ Algorithms/OtherOJ.md new file mode 100644 index 0000000..aaae241 --- /dev/null +++ b/HuaWeiOJ Algorithms/OtherOJ.md @@ -0,0 +1,8 @@ +## Other Algorithms Website +- [UVa Online Judge](http://uva.onlinejudge.org) +- [Sphere Online Judge](http://www.spoj.com) +- [Coder Byte](http://coderbyte.com) +- [Project Euler](https://projecteuler.net) +- [Hacker Rank](https://hackerrank.com) +- [Code Chef](http://www.codechef.com) +- [Top Coder](http://www.topcoder.com) \ No newline at end of file From 116cf1e5ff5a70c30964121787dc3125ea52ba26 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 12 Oct 2018 12:39:52 +0800 Subject: [PATCH 068/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=9B=86=E5=90=88?= =?UTF-8?q?=E7=9A=84=20=E5=B9=B6=E9=9B=86=EF=BC=8C=E4=BA=A4=E9=9B=86?= =?UTF-8?q?=EF=BC=8C=E5=B7=AE=E9=9B=86=EF=BC=8C=E5=AD=90=E9=9B=86=E7=9A=84?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E7=A8=8B=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Set/UseSetbySelf.js | 81 +++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) diff --git a/DataStructures/Set/UseSetbySelf.js b/DataStructures/Set/UseSetbySelf.js index 8e7e7cf..b656f03 100644 --- a/DataStructures/Set/UseSetbySelf.js +++ b/DataStructures/Set/UseSetbySelf.js @@ -74,7 +74,62 @@ return values; }; + // union this set and otherSet + this.union = function (otherSet) { + let unionSet = new SetS(); + let values = this.values(); + for (let index = 0; index < values.length; index++) { + unionSet.add(values[index]); + } + + values = otherSet.values(); + for (let j = 0; j < values.length; j++) { + unionSet.add(values[j]); + } + return unionSet; + }; + + // intersection two sets + this.intersection = function (otherSet) { + let intersectionSet = new SetS(); + + let values = this.values(); + for (let index = 0; index < values.length; index++) { + if (otherSet.has(values[index])) { + intersectionSet.add(values[index]); + } + } + return intersectionSet; + } + + // difference of set and setone + this.difference =function (otherSet) { + let differenceSet = new SetS(); + + let values = this.values(); + for (let index = 0; index < values.length; index++) { + if (!otherSet.has(values[index])) { + differenceSet.add(values[index]); + } + } + return differenceSet; + }; + + // judge if set if a subset if otherSet + this.subset = function (otherSet) { + if (this.size() > otherSet.size()) { + return false; + } else { + let values = this.values(); + for (let index = 0; index < values.length; index++) { + if (!otherSet.has(values[index])) { + return false; + } + } + return true; + } + } } @@ -82,6 +137,7 @@ let set = new SetS(); set.add(1); set.add(2); + set.add(3); set.add(6); set.add(7); console.log('------------------------------------'); @@ -97,6 +153,29 @@ console.log('------------------------------------'); console.log(set.values()); console.log('------------------------------------'); set.remove(2); -console.log('------------------------------------'); +console.log('-------------set valuse-----------------------'); console.log(set.values()); console.log('------------------------------------'); + + + +let settwo = new SetS(); +settwo.add(79); +settwo.add(5); +settwo.add(3); +settwo.add(16); +settwo.add(49); + +console.log('-------------settwo valuse-----------------------'); +console.log(settwo.values()); +console.log('------------------------------------'); + +let unionOneTwo = set.union(settwo); +console.log('--------------set union setone--------------------'); +console.log(unionOneTwo.values()); +console.log('------------------------------------'); + +let intersectionSetone = set.intersection(settwo); +console.log('---------------set intersectate settwo---------------------'); +console.log(intersectionSetone.values()); +console.log('------------------------------------'); From a318d429ee8b2859c07db7e9d8304b88d9019a71 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 14 Oct 2018 15:05:41 +0800 Subject: [PATCH 069/274] add ES6 Set functions --- DataStructures/Set/UseES6Set.js | 59 +++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 DataStructures/Set/UseES6Set.js diff --git a/DataStructures/Set/UseES6Set.js b/DataStructures/Set/UseES6Set.js new file mode 100644 index 0000000..f08be7b --- /dev/null +++ b/DataStructures/Set/UseES6Set.js @@ -0,0 +1,59 @@ +/**** + * + * @author SkylineBin + * @time 2018-10-14 + * + * @function Use ES6 Set to modify some function + * + * + */ + + let setA = new Set(); + setA.add(1); + setA.add(2); + setA.add(3); + + let setB = new Set(); + setB.add(2); + setB.add(3); + setB.add(4); + +// union two sets +let unionAb = new Set(); +for (let x of setA) { + unionAb.add(x); +} +for (let y of setB) { + unionAb.add(y); +} + + +// intersection of two sets +let intersection = function(seta,setb) { + let intersectionSet = new Set(); + for(let x of seta){ + if (setb.has(x)) { + intersectionSet.add(x); + } + } + return intersectionSet; +} + +let intersectionAB = intersection(setA, setB); + +// let intersectionAb = new Set([x for (x of setA) if (setB.has(x))]); + + +let difference = function (seta, setb) { + let differenceSet = new Set(); + for (let x of seta) { + if (!setb.has(x)) { + differenceSet.add(x); + } + } + return differenceSet; +} + +let differenceAB = difference(setA, setB); + +// let differenceAb = new Set([x for (x of setA) if (!setB.has(x))]); \ No newline at end of file From d2f650be06106826a9868829fe26e345efc10811 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 15 Oct 2018 12:26:09 +0800 Subject: [PATCH 070/274] add easy jum steps --- NowCoder/Leetcode/jumpStep.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 NowCoder/Leetcode/jumpStep.js diff --git a/NowCoder/Leetcode/jumpStep.js b/NowCoder/Leetcode/jumpStep.js new file mode 100644 index 0000000..061187c --- /dev/null +++ b/NowCoder/Leetcode/jumpStep.js @@ -0,0 +1,24 @@ +/**** + * + * @author SkylineBin + * @time 2018-10-15 + * @function 跳台阶问题 + */ + +// 一只青蛙一次可以跳上1级台阶,也可以跳上2级。 +// 求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 + +function jumpFloor(number) { + // write code here + // let number = parseInt(number); + if (number <= 0) { + return 0; + } else if (number == 1) { + return 1; + } else if (number == 2) { + return 2; + } else { + return jumpFloor(number - 1) + jumpFloor(number - 2); + } + +} \ No newline at end of file From 2f10906103658dfeb675e457a75c4260c295b462 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 15 Oct 2018 12:32:29 +0800 Subject: [PATCH 071/274] add another jumpStep problem --- NowCoder/Leetcode/jumpStepII.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 NowCoder/Leetcode/jumpStepII.js diff --git a/NowCoder/Leetcode/jumpStepII.js b/NowCoder/Leetcode/jumpStepII.js new file mode 100644 index 0000000..774dd35 --- /dev/null +++ b/NowCoder/Leetcode/jumpStepII.js @@ -0,0 +1,22 @@ +/**** + * + * @author SkylineBin + * @time 2018-10-15 + * @function 升级跳台阶问题 + */ + +// 一只青蛙一次可以跳上1级台阶,也可以跳上2级,……它也可以跳上n级。 +// 求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 + +function jumpFloorII(number) { + // write code here + // let number = parseInt(number); + if (number <= 0) { + return 0; + } else if (number == 1) { + return 1; + } else { + return jumpFloorII(number - 1); + } + +} \ No newline at end of file From e4e9da9c3b26db1f6d0a4fdccef66af4d36ebbd3 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 16 Oct 2018 12:29:47 +0800 Subject: [PATCH 072/274] create dictionary datastructure by JavaScript --- DataStructures/Dictionary/UseDictionary.js | 88 ++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 DataStructures/Dictionary/UseDictionary.js diff --git a/DataStructures/Dictionary/UseDictionary.js b/DataStructures/Dictionary/UseDictionary.js new file mode 100644 index 0000000..0bc1120 --- /dev/null +++ b/DataStructures/Dictionary/UseDictionary.js @@ -0,0 +1,88 @@ +/***** + * + * @author SkylineBin + * @time 2018-10-16 + * @function Create Dictionary Structure by JavaScript + * + * + */ + +function Dictionary() { + var items = {}; + + // check if has item + this.has = function (key) { + return key in items; + }; + + // set this value with this key + this.set = function (key, value){ + items[key] = value; + }; + + // delete this item + this.delete = function (key) { + if (this.has(key)) { + delete items[key]; + return true; + } + return false; + } + + // get this item by key + this.get = function (key) { + return this.has(key) ? items[key] : undefined; + } + + // get all values + this.values = function () { + var values = []; + for (let k in items) { + if (this.has(k)) { + values.push(items[k]); + } + } + return values; + }; + + // clear this dictionary + this.clear = function () { + items = {}; + } + + // get the size of this Set + this.size = function () { + return Object.keys(items).length; + } + + // get all keys + this.keys = function () { + return Object.keys(items); + } + + // get this item + this.getItems = function () { + return items; + } +} + + +let dictionary = new Dictionary(); +dictionary.set('John','jogn@gmail.com'); +dictionary.set('Tyrion', 'tyrion@gmail.com'); +dictionary.set('Shanny', 'shanny@gmail.com'); +dictionary.set('Mike', 'mike@gmail.com'); + +console.log('------------------------------------'); +console.log(dictionary.size()); +console.log('------------------------------------'); +console.log(dictionary.keys()); +console.log(dictionary.values()); +console.log('------------------------------------'); +console.log('------------------------------------'); +console.log(dictionary.delete('Shanny')); +console.log(dictionary.keys()); +console.log(dictionary.values()); +console.log(dictionary.getItems()); +console.log('------------------------------------'); +console.log('------------------------------------'); \ No newline at end of file From 696ad3daa200aa6fb1f3b11a1bbba8d1a8d2d3ad Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 16 Oct 2018 12:45:27 +0800 Subject: [PATCH 073/274] Create HashTable DataStructure by JavaScript --- DataStructures/Dictionary/UseHashTable.js | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 DataStructures/Dictionary/UseHashTable.js diff --git a/DataStructures/Dictionary/UseHashTable.js b/DataStructures/Dictionary/UseHashTable.js new file mode 100644 index 0000000..c112647 --- /dev/null +++ b/DataStructures/Dictionary/UseHashTable.js @@ -0,0 +1,49 @@ +/***** + * + * @author SkylineBin + * @time 2018-10-16 + * @function Create HashTable Structure by JavaScript + * + * + */ + + function HashTable() { + var table = []; + + // lose lose hash code + var loseloseHashCode = function (key) { + var hash = 0; + for (let index = 0; index < key.length; index++) { + hash += key.charCodeAt(index); + } + return hash % 37; + }; + + // put this value at the position computed by this key + this.put = function (key, value) { + var position = loseloseHashCode(key); + console.log(position + '-' + key); + table[position] = value; + } + + // get this value by key + this.get = function (key) { + return table[loseloseHashCode(key)]; + } + + // remove this value by key + this.remove = function (key) { + table[loseloseHashCode(key)] = undefined; + } + } + + let hash = new HashTable(); +hash.put('John', 'jogn@gmail.com'); +hash.put('Tyrion', 'tyrion@gmail.com'); +hash.put('Shanny', 'shanny@gmail.com'); +hash.put('Mike', 'mike@gmail.com'); + +console.log('------------------------------------'); +console.log(hash.get('Mike')); +console.log(hash.get('Rick')); +console.log('------------------------------------'); \ No newline at end of file From ca63f5523d98df14900870533c70ba9630bdc3e3 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 17 Oct 2018 00:12:11 +0800 Subject: [PATCH 074/274] =?UTF-8?q?=E4=B8=BA=20HashTable=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=20=E5=88=86=E7=A6=BB=E9=93=BE=E6=8E=A5=E7=9A=84?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E5=86=B2=E7=AA=81=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Dictionary/UseHashTable.js | 18 ++- .../Dictionary/UseHashTableApart.js | 116 ++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 DataStructures/Dictionary/UseHashTableApart.js diff --git a/DataStructures/Dictionary/UseHashTable.js b/DataStructures/Dictionary/UseHashTable.js index c112647..a34884c 100644 --- a/DataStructures/Dictionary/UseHashTable.js +++ b/DataStructures/Dictionary/UseHashTable.js @@ -35,6 +35,16 @@ this.remove = function (key) { table[loseloseHashCode(key)] = undefined; } + + // print values of this HashTable + this.print = function () { + for (let index = 0; index < table.length; index++) { + if (table[index] !== undefined) { + console.log(index + " : "+table[index]); + } + + } + } } let hash = new HashTable(); @@ -46,4 +56,10 @@ hash.put('Mike', 'mike@gmail.com'); console.log('------------------------------------'); console.log(hash.get('Mike')); console.log(hash.get('Rick')); -console.log('------------------------------------'); \ No newline at end of file +console.log('------------------------------------'); + +hash.put('Jonathan', 'jonathan@gmail.com'); +hash.put('Jamie', 'jamie@gmail.com'); +hash.put('Sue', 'sue@gmail.com'); + +hash.print(); \ No newline at end of file diff --git a/DataStructures/Dictionary/UseHashTableApart.js b/DataStructures/Dictionary/UseHashTableApart.js new file mode 100644 index 0000000..4c9acb7 --- /dev/null +++ b/DataStructures/Dictionary/UseHashTableApart.js @@ -0,0 +1,116 @@ +/***** + * + * @author SkylineBin + * @time 2018-10-16 + * @function Create HashTable Structure (Apart Link) by JavaScript + * + * + */ + +function HashTable() { + var table = []; + + // lose lose hash code + var loseloseHashCode = function (key) { + var hash = 0; + for (let index = 0; index < key.length; index++) { + hash += key.charCodeAt(index); + } + return hash % 37; + }; + + var ValuePair = function (key, value) { + this.key = key; + this.value = value; + + this.toString = function () { + return '[' + this.key + ' - ' + this.value + ']'; + } + }; + + // put this value at the position computed by this key + this.put = function (key, value) { + var position = loseloseHashCode(key); + if (table[position] == undefined) { + table[position] = new LinkedList(); + } + table[position].append(new ValuePair(key, value)); + } + + // get this value by key + this.get = function (key) { + var position = loseloseHashCode(key); + + if (table[position] !== undefined) { + var current = table[position].getHead(); + + while (current.next) { + if (current.element.key === key) { + return current.element.value; + } + current = current.next; + } + + if (current.element.key === key) { + return current.element.value; + } + } + return undefined; + }; + + // remove this value by key + this.remove = function (key) { + var position = loseloseHashCode(key); + + if (table[position] !== undefined) { + var current = table[position].getHead(); + + while (current.next) { + if (current.element.key === key) { + table[position].remove(current.element); + if (table[position].isEmpty()) { + table[position] = undefined; + } + return true; + } + current = current.next; + } + + if (current.element.key === key) { + table[position].remove(current.element); + if (table[position].isEmpty()) { + table[position] = undefined; + } + return true; + } + } + return false; + } + + // print values of this HashTable + this.print = function () { + for (let index = 0; index < table.length; index++) { + if (table[index] !== undefined) { + console.log(index + " : " + table[index]); + } + + } + } +} + +let hash = new HashTable(); +hash.put('John', 'jogn@gmail.com'); +hash.put('Tyrion', 'tyrion@gmail.com'); +hash.put('Shanny', 'shanny@gmail.com'); +hash.put('Mike', 'mike@gmail.com'); + +console.log('------------------------------------'); +console.log(hash.get('Mike')); +console.log(hash.get('Rick')); +console.log('------------------------------------'); + +hash.put('Jonathan', 'jonathan@gmail.com'); +hash.put('Jamie', 'jamie@gmail.com'); +hash.put('Sue', 'sue@gmail.com'); + +hash.print(); \ No newline at end of file From 677ac8a4e59f796e1b583e69be3984dc2de83b7e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 17 Oct 2018 23:42:35 +0800 Subject: [PATCH 075/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=BA=BF=E6=80=A7?= =?UTF-8?q?=E6=8E=A2=E6=9F=A5=E5=A4=84=E7=90=86=E7=9A=84=E6=95=A3=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E4=B8=AD=E7=9A=84=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Dictionary/UseHashTableLinerCheck.js | 114 ++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 DataStructures/Dictionary/UseHashTableLinerCheck.js diff --git a/DataStructures/Dictionary/UseHashTableLinerCheck.js b/DataStructures/Dictionary/UseHashTableLinerCheck.js new file mode 100644 index 0000000..72bf1f7 --- /dev/null +++ b/DataStructures/Dictionary/UseHashTableLinerCheck.js @@ -0,0 +1,114 @@ +/***** + * + * @author SkylineBin + * @time 2018-10-17 + * @function Create HashTable Structure (Liner Check) by JavaScript + * + * + */ + +function HashTable() { + var table = []; + + // lose lose hash code + var loseloseHashCode = function (key) { + var hash = 0; + for (let index = 0; index < key.length; index++) { + hash += key.charCodeAt(index); + } + return hash % 37; + }; + + var ValuePair = function (key, value) { + this.key = key; + this.value = value; + + this.toString = function () { + return '[' + this.key + ' - ' + this.value + ']'; + } + }; + + // put this value at the position computed by this key + this.put = function (key, value) { + var position = loseloseHashCode(key); + if (table[position] == undefined) { + table[position] = new ValuePair(key, value); + } else { + var index = ++position; + while (table[index] != undefined) { + index++; + } + table[index] =new ValuePair(key, value); + } + }; + + // get this value by key + this.get = function (key) { + var position = loseloseHashCode(key); + + if (table[position] !== undefined) { + if (table[position].key === key) { + return table[position].value; + } else { + var index = ++position; + while (table[index] === undefined || + table[index].key !== key) { + index++; + } + if (table[index].key === key) { + return table[index].value; + } + } + } + return undefined; + + }; + + // remove this value by key + this.remove = function (key) { + var position = loseloseHashCode(key); + + if (table[position] !== undefined) { + if (table[position].key === key) { + table[index] = undefined; + } else { + var index = ++position; + while (table[index] === undefined || + table[index].key !== key) { + index++; + } + if (table[index].key === key) { + table[index] = undefined; + } + } + } + return undefined; + } + + // print values of this HashTable + this.print = function () { + for (let index = 0; index < table.length; index++) { + if (table[index] !== undefined) { + console.log(index + " : " + table[index]); + } + + } + } +} + +let hash = new HashTable(); +hash.put('John', 'jogn@gmail.com'); +hash.put('Tyrion', 'tyrion@gmail.com'); +hash.put('Shanny', 'shanny@gmail.com'); +hash.put('Mike', 'mike@gmail.com'); + +console.log('------------------------------------'); +console.log(hash.get('Mike')); +console.log(hash.get('Rick')); +console.log('------------------------------------'); + +hash.put('Jonathan', 'jonathan@gmail.com'); +hash.put('Jamie', 'jamie@gmail.com'); +hash.put('Sue', 'sue@gmail.com'); + +hash.print(); \ No newline at end of file From 74d4712aaffdb257cdea48a9f1bfc420d8392c5b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 23 Oct 2018 23:21:05 +0800 Subject: [PATCH 076/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=80=A7=E8=B4=A8=E7=9A=84=E6=8F=8F=E8=BF=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/OptimizationAlgorithm/README.md | 3 +++ Algorithms/README.md | 2 +- DataStructures/README.md | 6 +++++- 3 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 Algorithms/OptimizationAlgorithm/README.md diff --git a/Algorithms/OptimizationAlgorithm/README.md b/Algorithms/OptimizationAlgorithm/README.md new file mode 100644 index 0000000..8beed86 --- /dev/null +++ b/Algorithms/OptimizationAlgorithm/README.md @@ -0,0 +1,3 @@ +## Optimization Algorithms + +Some heuristic algorithms and commonly used optimization algorithms diff --git a/Algorithms/README.md b/Algorithms/README.md index 17e3c16..350b90a 100644 --- a/Algorithms/README.md +++ b/Algorithms/README.md @@ -4,7 +4,7 @@ Some classic algorithms are always worth learning! ### basic_algorithm -we practice some basic algorithms by Java or JavaScript! +we practice some basic algorithms by Java or JavaScript! Time Complexity(O(n*logn)) ### Disk Scheduling Algorithm some disk Scheduling algorithms by Java! diff --git a/DataStructures/README.md b/DataStructures/README.md index dd77983..c1fd73d 100644 --- a/DataStructures/README.md +++ b/DataStructures/README.md @@ -16,4 +16,8 @@ Using JavaScript to create the LinkedList Structure ## Set -Using JavaScript to create the Set Structure \ No newline at end of file +Using JavaScript to create the Set Structure + +## Dictionary + +Using JavaScript to create the Dictionary Structure and HashTable Structure \ No newline at end of file From 89a1bef1c16302c05409970fde7d837a8eea0dd8 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 25 Oct 2018 23:27:02 +0800 Subject: [PATCH 077/274] add ReverseLinkList by JavaScript --- NowCoder/Leetcode/ReverseList.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 NowCoder/Leetcode/ReverseList.js diff --git a/NowCoder/Leetcode/ReverseList.js b/NowCoder/Leetcode/ReverseList.js new file mode 100644 index 0000000..0fce156 --- /dev/null +++ b/NowCoder/Leetcode/ReverseList.js @@ -0,0 +1,28 @@ +/*** + * + * @author SkylineBin\ + * @time 2018-10-25 + * @function reverse LinkList by JavaScript + * + * + * 输入一个链表, 反转链表后, 输出新链表的表头。 + * + */ + +/*function ListNode(x){ + this.val = x; + this.next = null; +}*/ +function ReverseList(pHead) { + // write code here + var preList; + var nextList; + while (pHead != null) { + nextList = pHead.next; + pHead.next = preList; + preList = pHead; + pHead = nextList; + } + return preList; + +} \ No newline at end of file From a8b9bc692066651f3c33fa62163e3b023b2727b9 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 16 Dec 2018 17:20:35 +0800 Subject: [PATCH 078/274] =?UTF-8?q?=E7=89=9B=E5=AE=A2=E7=BD=91=20=E5=89=91?= =?UTF-8?q?=E6=8C=87offer=E7=AE=97=E6=B3=95=E5=BD=92=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/ReverseList.js | 12 +++++- NowCoder/Leetcode/checkDatainArray.js | 32 ++++++++++------ NowCoder/Leetcode/doublePower.js | 12 +++++- NowCoder/Leetcode/findSumfromArray.js | 29 ++++++++------ NowCoder/Leetcode/jumpStep.js | 11 +++++- NowCoder/Leetcode/jumpStepII.js | 10 ++++- NowCoder/Leetcode/loopStr.js | 8 +++- NowCoder/Leetcode/outputFibonacci.js | 44 +++++++++++++--------- NowCoder/Leetcode/replaceSpaceinString.js | 22 +++++++---- NowCoder/Leetcode/reverseWords.js | 30 +++++++++------ NowCoder/Leetcode/shiftListNode.js | 28 +++++++++----- NowCoder/Leetcode/useTwoStackCreatQueue.js | 42 ++++++++++++--------- 12 files changed, 187 insertions(+), 93 deletions(-) diff --git a/NowCoder/Leetcode/ReverseList.js b/NowCoder/Leetcode/ReverseList.js index 0fce156..5ce0e55 100644 --- a/NowCoder/Leetcode/ReverseList.js +++ b/NowCoder/Leetcode/ReverseList.js @@ -1,6 +1,6 @@ /*** * - * @author SkylineBin\ + * @author SkylineBin * @time 2018-10-25 * @function reverse LinkList by JavaScript * @@ -25,4 +25,12 @@ function ReverseList(pHead) { } return preList; -} \ No newline at end of file +} + +/* + * 涉及理论: 链表、循环 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/checkDatainArray.js b/NowCoder/Leetcode/checkDatainArray.js index a537c33..de104ac 100644 --- a/NowCoder/Leetcode/checkDatainArray.js +++ b/NowCoder/Leetcode/checkDatainArray.js @@ -4,16 +4,24 @@ * */ - // first version +// first version - function Find(target, array) { - // write code here - for (var i = 0; i < array.length; i++) { - for (var j = 0; j < array[i].length; j++) { - if (target == array[i][j]) { - return true; - } - } - } - return false; - } \ No newline at end of file +function Find(target, array) { + // write code here + for (var i = 0; i < array.length; i++) { + for (var j = 0; j < array[i].length; j++) { + if (target == array[i][j]) { + return true; + } + } + } + return false; +} + + /* + * 涉及理论: 搜索及排序 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/doublePower.js b/NowCoder/Leetcode/doublePower.js index fffa8e4..3c73d66 100644 --- a/NowCoder/Leetcode/doublePower.js +++ b/NowCoder/Leetcode/doublePower.js @@ -5,7 +5,7 @@ * */ - // first version +// first version function Power(base, exponent) { @@ -34,4 +34,12 @@ function Power(base, exponent) { } -// failed \ No newline at end of file +// failed + + /* + * 涉及理论: 递归、边界 + * 普通解法: 判断+遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/findSumfromArray.js b/NowCoder/Leetcode/findSumfromArray.js index 63554e7..85b109e 100644 --- a/NowCoder/Leetcode/findSumfromArray.js +++ b/NowCoder/Leetcode/findSumfromArray.js @@ -15,7 +15,7 @@ function FindNumbersWithSum(array, sum) var nummulti=[]; if(arrlength === 0 || array == null){ return ''; - }else{ + } else { for(var i=0;i< arrlength-1;i++){ for(var j=i+1;jnummulti[k]){ - leastnum = nummulti[k]; - leastone = k; + var leastone =0; + var leastnum = nummulti[0]; + for(var k=0;knummulti[k]){ + leastnum = nummulti[k]; + leastone = k; + } } + return numones[leastone],numtwos[leastone]; } - return numones[leastone],numtwos[leastone]; - } } - } + + + /* + * 涉及理论: 搜索及排序 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/jumpStep.js b/NowCoder/Leetcode/jumpStep.js index 061187c..b1b9753 100644 --- a/NowCoder/Leetcode/jumpStep.js +++ b/NowCoder/Leetcode/jumpStep.js @@ -21,4 +21,13 @@ function jumpFloor(number) { return jumpFloor(number - 1) + jumpFloor(number - 2); } -} \ No newline at end of file +} + + +/* + * 涉及理论: 递归 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/jumpStepII.js b/NowCoder/Leetcode/jumpStepII.js index 774dd35..bed1e2d 100644 --- a/NowCoder/Leetcode/jumpStepII.js +++ b/NowCoder/Leetcode/jumpStepII.js @@ -18,5 +18,13 @@ function jumpFloorII(number) { } else { return jumpFloorII(number - 1); } +} -} \ No newline at end of file + +/* + * 涉及理论: 递归 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/loopStr.js b/NowCoder/Leetcode/loopStr.js index 8fb521f..6bd7447 100644 --- a/NowCoder/Leetcode/loopStr.js +++ b/NowCoder/Leetcode/loopStr.js @@ -45,4 +45,10 @@ console.log('------------------------------------'); console.log(teststr.length); console.log('------------------------------------'); - +/* + * 涉及理论: 字符串处理 + * 普通解法: 拼接 + * 改进方向: + * + * + */ diff --git a/NowCoder/Leetcode/outputFibonacci.js b/NowCoder/Leetcode/outputFibonacci.js index 26eabe1..d0fc8aa 100644 --- a/NowCoder/Leetcode/outputFibonacci.js +++ b/NowCoder/Leetcode/outputFibonacci.js @@ -4,21 +4,29 @@ * */ - // first version - function Fibonacci(n) { - // write code here - var beforelastnum = 0; - var lastnum = 1; - if (n <= 0) { - return 0; - } else if (n == 1) { - return 1; - } else { - for (var i = 2; i <= n; i++) { - result = beforelastnum + lastnum; - beforelastnum = lastnum; - lastnum = result; - } - return result; - } - } \ No newline at end of file +// first version +function Fibonacci(n) { + // write code here + var beforelastnum = 0; + var lastnum = 1; + if (n <= 0) { + return 0; + } else if (n == 1) { + return 1; + } else { + for (var i = 2; i <= n; i++) { + result = beforelastnum + lastnum; + beforelastnum = lastnum; + lastnum = result; + } + return result; + } +} + +/* + * 涉及理论: 循环 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/replaceSpaceinString.js b/NowCoder/Leetcode/replaceSpaceinString.js index 137553b..bae9a10 100644 --- a/NowCoder/Leetcode/replaceSpaceinString.js +++ b/NowCoder/Leetcode/replaceSpaceinString.js @@ -5,11 +5,19 @@ * */ - // first version +// first version - function replaceSpace(str) { - // write code here - var regstr = new RegExp(' ', "g"); - var backstr = str.replace(regstr, '%20'); - return backstr; - } +function replaceSpace(str) { + // write code here + var regstr = new RegExp(' ', "g"); + var backstr = str.replace(regstr, '%20'); + return backstr; +} + +/* + * 涉及理论: 字符串处理 + * 普通解法: 替换 + * 改进方向: + * + * + */ diff --git a/NowCoder/Leetcode/reverseWords.js b/NowCoder/Leetcode/reverseWords.js index 81db9ae..0d3fc54 100644 --- a/NowCoder/Leetcode/reverseWords.js +++ b/NowCoder/Leetcode/reverseWords.js @@ -7,15 +7,23 @@ * */ - function ReverseSentence(str) { - // write code here - if (str == null || str == '') { - return ""; - } else { - return str.split(" ").reverse().join(" "); - } - } +function ReverseSentence(str) { + // write code here + if (str == null || str == '') { + return ""; + } else { + return str.split(" ").reverse().join(" "); + } +} - console.log('------------------------------------'); - console.log(ReverseSentence("student a am I")); - console.log('------------------------------------'); \ No newline at end of file +console.log('------------------------------------'); +console.log(ReverseSentence("student a am I")); +console.log('------------------------------------'); + +/* + * 涉及理论: 字符串处理 + * 普通解法: 使用 reverse 函数 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/shiftListNode.js b/NowCoder/Leetcode/shiftListNode.js index 257db23..1b63a20 100644 --- a/NowCoder/Leetcode/shiftListNode.js +++ b/NowCoder/Leetcode/shiftListNode.js @@ -5,14 +5,22 @@ * */ - // first version +// first version - function printListFromTailToHead(head) { - // write code here - var alldata = []; - while (head != null) { - alldata.unshift(head.val); - head = head.next; - } - return alldata; - } +function printListFromTailToHead(head) { + // write code here + var alldata = []; + while (head != null) { + alldata.unshift(head.val); + head = head.next; + } + return alldata; +} + +/* + * 涉及理论: 数组处理 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/Leetcode/useTwoStackCreatQueue.js b/NowCoder/Leetcode/useTwoStackCreatQueue.js index cc92f7d..20b130c 100644 --- a/NowCoder/Leetcode/useTwoStackCreatQueue.js +++ b/NowCoder/Leetcode/useTwoStackCreatQueue.js @@ -4,23 +4,31 @@ * */ - // first version +// first version - var stack1 = [], - stack2 = []; +var stack1 = [], + stack2 = []; - function push(node) { - // write code here - stack1.push(node); - } +function push(node) { + // write code here + stack1.push(node); +} - function pop() { - if (stack2.length === 0) { - while (stack1.length !== 0) { - stack2.push(stack1.pop()); - } - return stack2.pop(); - } else { - return stack2.pop(); - } - } \ No newline at end of file +function pop() { + if (stack2.length === 0) { + while (stack1.length !== 0) { + stack2.push(stack1.pop()); + } + return stack2.pop(); + } else { + return stack2.pop(); + } +} + +/* + * 涉及理论: 队列 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file From bdc35245fd47e498294c0c3f9c830b61d9bfbfbf Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 24 Feb 2019 22:01:47 +0800 Subject: [PATCH 079/274] add minNumberInRotateArray function find the min number in rotate array --- NowCoder/Leetcode/minNumberInRotateArray.js | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 NowCoder/Leetcode/minNumberInRotateArray.js diff --git a/NowCoder/Leetcode/minNumberInRotateArray.js b/NowCoder/Leetcode/minNumberInRotateArray.js new file mode 100644 index 0000000..d9aa320 --- /dev/null +++ b/NowCoder/Leetcode/minNumberInRotateArray.js @@ -0,0 +1,38 @@ +/**** + * + * 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 + * 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 + * 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 + * NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 + * + */ + +function minNumberInRotateArray(rotateArray) +{ + // write code here + var len = rotateArray.length; + var minNum = 0; + if (len <= 0) { + return 0; + } else { + if (rotateArray[0] < rotateArray[len-1]) { + minNum = rotateArray[0]; + for (var index = 0; index < len; index++) { + if (rotateArray[index] <= minNum) { + minNum = rotateArray[index]; + } + } + } else { + minNum = rotateArray[len-1]; + for (var index = len -1; index >= 0; index--) { + if (rotateArray[index] <= minNum) { + minNum = rotateArray[index]; + } + } + } + return minNum; + } +} + +var rotateArray = [4,5,6,2,3]; +console.log(minNumberInRotateArray(rotateArray)); \ No newline at end of file From dcb0b47b8c34b794fd0918a6b8c57feb64922aa6 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 24 Feb 2019 22:25:33 +0800 Subject: [PATCH 080/274] Create twoSum.js --- Leetcode/twoSum.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Leetcode/twoSum.js diff --git a/Leetcode/twoSum.js b/Leetcode/twoSum.js new file mode 100644 index 0000000..b260620 --- /dev/null +++ b/Leetcode/twoSum.js @@ -0,0 +1,28 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + var numArray = new Array(); + if (nums.length <= 0) { + return numArray; + } else { + for (var index = 0; index < nums.length; index++) { + if (index < nums.length -1) { + for (var indexj = index+1; indexj < nums.length; indexj++) { + if (nums[index] + nums[indexj] == target) { + numArray.push(index); + numArray.push(indexj); + return numArray; + } + } + } + } + } +}; + +var testArray = [-1, -2, -3, -4, -5]; +var testTarget = -8; +console.log(twoSum(testArray,testTarget)); +console.log(twoSum(testArray,testTarget).length); \ No newline at end of file From ee79b09653a5ab2aba4adfccca0e921020ca28b4 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 14 Mar 2019 21:22:59 +0800 Subject: [PATCH 081/274] =?UTF-8?q?=E7=89=9B=E5=AE=A2=E7=BD=91=E4=B8=A4?= =?UTF-8?q?=E9=81=93=E7=AE=97=E6=B3=95=E9=A2=98=EF=BC=8C=E6=96=90=E6=B3=A2?= =?UTF-8?q?=E6=8B=89=E5=A5=91=E6=95=B0=E5=88=97=E5=92=8C=E6=B1=82=E4=BA=8C?= =?UTF-8?q?=E8=BF=9B=E5=88=B6=E4=B8=AD=201=20=E7=9A=84=E4=B8=AA=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/doublePower.js | 9 +++++- NowCoder/Leetcode/numberOf1.js | 47 ++++++++++++++++++++++++++++++++ NowCoder/Leetcode/recCover.js | 23 ++++++++++++++++ TestProjects/testRegister.md | 2 ++ 4 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 NowCoder/Leetcode/numberOf1.js create mode 100644 NowCoder/Leetcode/recCover.js create mode 100644 TestProjects/testRegister.md diff --git a/NowCoder/Leetcode/doublePower.js b/NowCoder/Leetcode/doublePower.js index 3c73d66..37fedaf 100644 --- a/NowCoder/Leetcode/doublePower.js +++ b/NowCoder/Leetcode/doublePower.js @@ -42,4 +42,11 @@ function Power(base, exponent) { * 改进方向: * * - */ \ No newline at end of file + */ + +// second Practice +function Power2(base, exponent) { + // write code here + + +} \ No newline at end of file diff --git a/NowCoder/Leetcode/numberOf1.js b/NowCoder/Leetcode/numberOf1.js new file mode 100644 index 0000000..112a20c --- /dev/null +++ b/NowCoder/Leetcode/numberOf1.js @@ -0,0 +1,47 @@ +/*** +* +* 输入一个整数, 输出该数二进制表示中1的个数。 其中负数用补码表示。 +* +* +***/ +// ! 本质涉及: 位运算、二进制转换、补码 +function NumberOf1(n) { + // 左移 1 与每个位相与 + let count = 0; + let flag = 1; + while (flag !== 0) { + if ((n & flag) !== 0) { + count++; + } + flag = flag << 1; + } + return count; +} + +// 可能的最优解 +function NumberOf1best(n) { + // 每算一次和 n-1 相与 + let count = 0; + while (n !== 0) { + ++count; + n = n & (n-1); + } + return count; +} + + +// javascript 特性的解法 +function NumberOf1two(n) { + // javascript 中的负数直接以补码的形式存储 + if (n < 0) { + n = n >>> 0; + } + var numArr = n.toString(2).split('1'); + return numArr.length - 1; +} + +// Test Algorithm +var testNum = 3; +console.log(NumberOf1(testNum)); +console.log(NumberOf1two(testNum)); +console.log(NumberOf1best(testNum)); \ No newline at end of file diff --git a/NowCoder/Leetcode/recCover.js b/NowCoder/Leetcode/recCover.js new file mode 100644 index 0000000..28dba2c --- /dev/null +++ b/NowCoder/Leetcode/recCover.js @@ -0,0 +1,23 @@ +/*** + * + * 我们可以用2 * 1 的小矩形横着或者竖着去覆盖更大的矩形。 + * 请问用 n个2 * 1 的小矩形无重叠地覆盖一个2 * n的大矩形, + * 总共有多少种方法? + * + * +*/ + +// ! 本质:斐波拉契数列 + +function rectCover(number) { + if (number <= 0) { + return 0; + } else if(number === 1 || number === 2) { + return number; + } else { + return rectCover(number - 1) + rectCover(number - 2); + } +} + +// Test demo +console.log(rectCover(0)); // 0 \ No newline at end of file diff --git a/TestProjects/testRegister.md b/TestProjects/testRegister.md new file mode 100644 index 0000000..7315ebe --- /dev/null +++ b/TestProjects/testRegister.md @@ -0,0 +1,2 @@ +## 对数器基本案例 +**对数器** 是用来加快测试算法的小例程 \ No newline at end of file From 23aefcd515fad5fedd2146fff9ea6ef4f29fc237 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 14 Mar 2019 22:18:15 +0800 Subject: [PATCH 082/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=B8=A4?= =?UTF-8?q?=E7=A7=8D=E5=A4=8D=E6=9D=82=E5=BA=A6=E8=BE=83=E4=BD=8E=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/recCover.js | 71 ++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/NowCoder/Leetcode/recCover.js b/NowCoder/Leetcode/recCover.js index 28dba2c..167c1c7 100644 --- a/NowCoder/Leetcode/recCover.js +++ b/NowCoder/Leetcode/recCover.js @@ -9,6 +9,7 @@ // ! 本质:斐波拉契数列 +// 最简单版本 暴力递归 算法复杂度 O(2^n) function rectCover(number) { if (number <= 0) { return 0; @@ -19,5 +20,73 @@ function rectCover(number) { } } +// 中级版本 算法复杂度 O(N) +function rectCover2(number) { + if (number <= 0) { + return 0; + } + if (number === 1 || number === 2) { + return number; + } + let res = 2; // 当前数值 + let pre = 1; + let temp = 0; + for (let i = 3; i <= number; i++) { + temp = res; + res = res + pre; + pre = temp; + } + return res; +} + +// 变态版本 算法复杂度 O(logN) +// 本质是将 求 斐波拉契数列第 N 项 的问题转换成 求矩阵的 N 次方问题 + +// 先创建矩阵求幂的函数 +function matrixPower(m, p){ + let res = [[0],[0]]; + for (let i = 0; i < m.length; i++) { + res[i][i] = 1; + } + let temp = m; + for (; p !== 1; p >>= 1) { + if ((p & 1) !== 0) { + res = muliMatrix(res, temp); + } + temp = muliMatrix(temp, temp); + } + return res; +} + +// 矩阵相乘的方法 +function muliMatrix(m1, m2) { + let res2 = []; + for (let i = 0; i < m1.length; i++) { + for (let j = 0; j < m2[0].length; j++) { + for (let k = 0; k < m2.length; k++) { + res2[i][j] += m1[i][k] * m2[k][j]; + } + } + } + return res2; +} + +function rectCover3(number) { + if (number <= 0) { + return 0; + } + if (number === 1 || number === 2) { + return number; + } + let base = [[1,1],[1,0]]; // 当前数值 + let result = matrixPower(base, number-2); + return result[0][0] + result[1][0]; + +} + + // Test demo -console.log(rectCover(0)); // 0 \ No newline at end of file +var testNum = 3; +console.log(rectCover(testNum)); // 0 +console.log(rectCover2(testNum)); // 0 +console.log(rectCover3(testNum)); // 0 \ No newline at end of file From 34a3ba7781e746e54d216f0c3ff2f8ecc838079a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 15 Mar 2019 20:56:27 +0800 Subject: [PATCH 083/274] =?UTF-8?q?=E8=B0=83=E6=95=B4=E4=B9=8B=E5=89=8D?= =?UTF-8?q?=E7=AE=97=E6=B3=95=E7=9A=84=E9=83=A8=E5=88=86=E6=A0=B7=E5=BC=8F?= =?UTF-8?q?=E5=92=8C=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 12 ++++++++ .../basic_algorithm/InversionbyJavaScript.js | 6 ++-- .../SortAlgorithmsbyJavaScript/BubbleSort.js | 8 +++--- .../SortAlgorithmsbyJavaScript/MergeSort.js | 28 +++++++++---------- .../SelectionSort.js | 10 +++---- NowCoder/Leetcode/doublePower.js | 5 ++-- NowCoder/Leetcode/linkTest.js | 12 ++++++++ 7 files changed, 53 insertions(+), 28 deletions(-) create mode 100644 NowCoder/Leetcode/linkTest.js diff --git a/.vscode/launch.json b/.vscode/launch.json index 2448d07..151977b 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,5 +1,17 @@ { "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - Inversion", + "request": "launch", + "mainClass": "basic_algorithm.Inversion" + }, + { + "type": "java", + "name": "CodeLens (Launch) - FindMaxValue", + "request": "launch", + "mainClass": "basic_algorithm.FindMaxValue" + }, { "type": "java", "name": "CodeLens (Launch) - BubbleSort", diff --git a/Algorithms/basic_algorithm/InversionbyJavaScript.js b/Algorithms/basic_algorithm/InversionbyJavaScript.js index d47f37d..407ee3d 100644 --- a/Algorithms/basic_algorithm/InversionbyJavaScript.js +++ b/Algorithms/basic_algorithm/InversionbyJavaScript.js @@ -51,6 +51,6 @@ function outallInversion(arrays, ln, midn, rn) { // let testArrays = [1, 3, 4, 2, 5]; - let testArrays = [3, 1, 2, 4, 0, 7, 5]; - console.log('this array is: ' + testArrays); - console.log('the small sum of this array is: ' + printInversion(testArrays)); \ No newline at end of file +let testArrays = [3, 1, 2, 4, 0, 7, 5]; +console.log('this array is: ' + testArrays); +console.log('the small sum of this array is: ' + printInversion(testArrays)); \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js index 4d8d150..37718e7 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js @@ -8,7 +8,7 @@ * */ - module.exports = function BubbleSort(arrays){ +module.exports = function BubbleSort(arrays){ if(arrays == null || arrays.length < 2){ return; } @@ -21,10 +21,10 @@ } } - } +} - function swap(arrays, si, sj){ +function swap(arrays, si, sj){ let tempdata = arrays[si]; arrays[si] = arrays[sj]; arrays[sj] = tempdata; - } \ No newline at end of file +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js index 9aa7280..6d58beb 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js @@ -8,26 +8,26 @@ * */ - module.exports = function MergeSort(arrays) { +module.exports = function MergeSort(arrays) { if (arrays == null || arrays.length < 2) { return; } // Recursive process sortProgress(arrays, 0, arrays.length - 1); - } +} - function sortProgress(arrays, Ln, Rn) { - if (Ln == Rn){ - return; - } - let midn = Ln + ((Rn - Ln) >> 1); - sortProgress(arrays, Ln, midn); - sortProgress(arrays, midn + 1, Rn); - merge(arrays, Ln, midn, Rn); - console.log(arrays); - } +function sortProgress(arrays, Ln, Rn) { + if (Ln == Rn){ + return; + } + let midn = Ln + ((Rn - Ln) >> 1); + sortProgress(arrays, Ln, midn); + sortProgress(arrays, midn + 1, Rn); + merge(arrays, Ln, midn, Rn); + console.log(arrays); +} - function merge(arrays, Ln, midn, Rn) { +function merge(arrays, Ln, midn, Rn) { let temparrays = new Array(); let ti = 0; let pone = Ln; @@ -48,4 +48,4 @@ for (let index = 0; index < temparrays.length; index++) { arrays[Ln + index] = temparrays[index]; } - } \ No newline at end of file +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js index b9407ce..52a7cc7 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js @@ -22,8 +22,8 @@ module.exports = function SelectionSort(arrays){ } } - function swap(arrays, si, sj) { - let tempdata = arrays[si]; - arrays[si] = arrays[sj]; - arrays[sj] = tempdata; - } \ No newline at end of file +function swap(arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; +} \ No newline at end of file diff --git a/NowCoder/Leetcode/doublePower.js b/NowCoder/Leetcode/doublePower.js index 37fedaf..7168de6 100644 --- a/NowCoder/Leetcode/doublePower.js +++ b/NowCoder/Leetcode/doublePower.js @@ -47,6 +47,7 @@ function Power(base, exponent) { // second Practice function Power2(base, exponent) { // write code here - -} \ No newline at end of file + +} + diff --git a/NowCoder/Leetcode/linkTest.js b/NowCoder/Leetcode/linkTest.js new file mode 100644 index 0000000..b4f05b1 --- /dev/null +++ b/NowCoder/Leetcode/linkTest.js @@ -0,0 +1,12 @@ +/*** +* +* +* +* +***/ +// ! 本质涉及: + + +// Test Algorithm +// var testNum = 5; +console.log(); \ No newline at end of file From 0d102a0b2f292afe86129562b5f3c4d04afb9c2c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 18 Mar 2019 14:33:01 +0800 Subject: [PATCH 084/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=B0=8F=E6=95=B0?= =?UTF-8?q?=E6=B1=82=E5=B9=82=20=E5=92=8C=20=E6=95=B0=E7=BB=84=E9=87=8D?= =?UTF-8?q?=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/doublePower.js | 28 ++++++++++++++++++++++++++-- NowCoder/Leetcode/reOrderArray.js | 25 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 NowCoder/Leetcode/reOrderArray.js diff --git a/NowCoder/Leetcode/doublePower.js b/NowCoder/Leetcode/doublePower.js index 7168de6..99930b2 100644 --- a/NowCoder/Leetcode/doublePower.js +++ b/NowCoder/Leetcode/doublePower.js @@ -47,7 +47,31 @@ function Power(base, exponent) { // second Practice function Power2(base, exponent) { // write code here - - + if (exponent === 0 && base !== 0) { + return 1; + } + if (exponent === 1) { + return base; + } + if (base === 0 && exponent <= 0) { + throw new ErrorEvent(); + } + if (base === 0 && exponent > 0) { + return 0; + } + let index = exponent >= 0 ? exponent : - exponent; + let result = Power2(base, index >> 1); + result*= result; + if ((index&1) === 1) { + result*=base; + } + if (exponent < 0) { + result = 1/result; + } + return result; } +let baseNum = 1.5; +let exponentNum = 2; +console.log(Power2(baseNum, exponentNum)); + diff --git a/NowCoder/Leetcode/reOrderArray.js b/NowCoder/Leetcode/reOrderArray.js new file mode 100644 index 0000000..9309cc6 --- /dev/null +++ b/NowCoder/Leetcode/reOrderArray.js @@ -0,0 +1,25 @@ +/*** +* +* +* 输入一个整数数组, 实现一个函数来调整该数组中数字的顺序, +* 使得所有的奇数位于数组的前半部分, 所有的偶数位于数组的后半部分, +* 并保证奇数和奇数, 偶数和偶数之间的相对位置不变。 +* +***/ +// ! 本质涉及: 数组操作,排序,数组拼接 +function reOrderArray(array) { + let oddArr = []; + let evenArr = []; + for (let index = 0; index < array.length; index++) { + if (array[index]%2 !== 0) { + oddArr.push(array[index]); + }else { + evenArr.push(array[index]); + } + } + return oddArr.concat(evenArr); +} + +// Test Algorithm +var testNum = [2,3,4,5,6,7,0,9]; +console.log(reOrderArray(testNum)); \ No newline at end of file From 9dc5ba3d93c9b9517fb16b9ad7ddfc0a5d4c1763 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 18 Mar 2019 20:44:35 +0800 Subject: [PATCH 085/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E8=8D=B7=E5=85=B0?= =?UTF-8?q?=E5=9B=BD=E6=97=97=E9=97=AE=E9=A2=98=E7=9A=84=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJava/DutchFlagArray.java | 126 ++++++++++++++++++ .../DultFlagArray.js | 34 +++++ .../SortAlgorithmsbyJavaScript/mainSort.js | 27 ++-- 3 files changed, 177 insertions(+), 10 deletions(-) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java new file mode 100644 index 0000000..1d2131f --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java @@ -0,0 +1,126 @@ +package basic_algorithm; + +public class DutchFlagArray { + // 使用java 实现 荷兰国旗的数组分类问题(升级版,可选从L到R) + public static int[] partition(int[] arr, int L, int R, int num) { + int less = L - 1; + int more = R + 1; + int index = L; + while (index < more) { + if (arr[index] < num) { + swap(arr, ++less, index++); + } else if (arr[index] > num){ + swap(arr, --more, index); + } else { + index++; + } + } + return new int[] {less + 1, more - 1}; + } + + public static void swap(int[] arr, int i, int j) { + // 交换两个数 + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } + + +// for test +// 使用对数器进行测试 + public static int[] generateRandomArray(int size, int value) { +// 使用系统自带的随机数生成器生成备选数集合 +// Math.random() -> double [0,1) +// (int) ((size + 1) * Math.random()) -> [0,size] 整数集合 +// size =6, size + 1 =7; +// Math.random() -> [0,1) * 7 -> [0,7) double +// double -> int [0,6] -> int + + +// 生成长度随机的数组 + int[] arr = new int[(int) ((size + 1) * Math.random())]; +// 数组内的每个数也是随机的 + for (int i = 0; i < arr.length; i++) { + arr[i] = (int) ((value + 1) * Math.random()) - (int) (value * Math.random()); + } + return arr; + + } + +// for test +// 生成拷贝数组的方法 + public static int[] copyArray(int[] arr) { + if (arr == null) { + return null; + } + int[] res = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + res[i] = arr[i]; + } + return res; + } + +// for test +// 判断两个数组是否相同 + public static boolean isEqual(int[] arrone, int[] arrtwo) { + if((arrone == null && arrtwo != null) || (arrone != null && arrtwo == null)) { + return false; + } + if(arrone == null && arrtwo == null) { + return true; + } + if(arrone.length != arrtwo.length) { + return false; + } + for (int i = 0; i < arrone.length; i++) { + if (arrone[i] != arrtwo[i]) { + return false; + } + } + return true; + } + +// for test +// 打印数组的方法 + public static void printArray(int[] arr) { + if(arr == null || arr.length ==0) { + System.out.println(""); + }else { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + System.out.println(""); + } + } + + +// 大样本测试 方法 + public static void main(String[] args) { + int testTime = 500000; + int size = 10; + int value = 100; + boolean succeed = true; + for (int i = 0; i < testTime; i++) { + int[] arrone = generateRandomArray(size, value); + int[] arrtwo = copyArray(arrone); + int[] arrthree = copyArray(arrone); + partition(arrtwo, 0, arrtwo.length-1, 0); + partition(arrthree, 0, arrthree.length-1, 0); +// mergeSort(arrone); +// rightMethod(arrtwo); + if(!isEqual(arrtwo, arrthree)) { + succeed = false; + printArray(arrone); + printArray(arrtwo); + printArray(arrthree); + break; + } + } + + System.out.println(succeed ? "well done!" : "wrong algorithms!"); + + int[] arr = generateRandomArray(size, value); + printArray(arr); + + } +} diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js new file mode 100644 index 0000000..454b5d5 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js @@ -0,0 +1,34 @@ +/** + * @author SkylineBin + * @time 2019-03-18 + * @function 使用 javascript 进行模拟 荷兰国旗分类(将数组分为小于等于大于num 的三类) + * 是划分 从 L 到 R 区域内 如果整个数组, L = 0; R = arrays.length - 1; + * + * @Algorithm_bigO O(N) + * N is the length of arrays + * + */ + +module.exports = function DutchFlagArray(arrays, L, R, num) { + if (arrays == null || arrays.length < 2) { + return; + } + let less = L - 1; + let more = R + 1; + while (L < more) { + if (arrays[L] < num) { + swap(arrays, ++less, L++); + } else if (arrays[L] > num) { + swap(arrays, --more, L); + } else { + L++; + } + } + return arrays; +} + +function swap(arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js index 0aa04f1..4066cb9 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -6,14 +6,15 @@ * */ - const BubbleSort = require('./BubbleSort'); - const SelectionSort = require('./SelectionSort'); - const InsertionSort = require('./InsertionSort'); - const MergeSort = require('./MergeSort'); +const BubbleSort = require('./BubbleSort'); +const SelectionSort = require('./SelectionSort'); +const InsertionSort = require('./InsertionSort'); +const MergeSort = require('./MergeSort'); +const DutchFlagArray = require('./DultFlagArray'); - let arrone = [3,6,2,4,0,5,9]; +let arrone = [3,6,2,4,0,5,9]; - console.log(arrone); +console.log(arrone); // console.log('--------start BubbleSort-----------'); @@ -34,10 +35,16 @@ // console.log('--------end InsertionSort-----------'); - console.log('--------start MergeSort-----------'); + // console.log('--------start MergeSort-----------'); - MergeSort(arrone); + // MergeSort(arrone); - console.log('--------end MergeSort-----------'); + // console.log('--------end MergeSort-----------'); - console.log(arrone); \ No newline at end of file + console.log('--------start DutchFlagArray-----------'); + + DutchFlagArray(arrone, 0, 6 , 4); + + console.log('--------end DutchFlagArray-----------'); + +console.log(arrone); \ No newline at end of file From 7e92be50ab0c1e48babe0c8d342305fb02a02d6a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 18 Mar 2019 20:52:35 +0800 Subject: [PATCH 086/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=B9=E6=95=B0?= =?UTF-8?q?=E5=99=A8=E5=AF=B9=E6=8E=92=E5=BA=8F=E7=AE=97=E6=B3=95=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Algorithms/README.md | 11 +++ .../SortAlgorithmsbyJavaScript/BubbleSort.js | 1 + .../SortAlgorithmsbyJavaScript/bigdataTest.js | 88 +++++++++++++++++++ 3 files changed, 100 insertions(+) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js diff --git a/Algorithms/README.md b/Algorithms/README.md index 350b90a..3f8f6e1 100644 --- a/Algorithms/README.md +++ b/Algorithms/README.md @@ -6,5 +6,16 @@ Some classic algorithms are always worth learning! ### basic_algorithm we practice some basic algorithms by Java or JavaScript! Time Complexity(O(n*logn)) +各种基础的排序算法实现,包括 Java 版本 和 JavaScript 版本 + +#### 交换性质的排序算法 +- 冒泡排序 +- 插入排序 +- 选择排序 +- 归并排序 + + + + ### Disk Scheduling Algorithm some disk Scheduling algorithms by Java! diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js index 37718e7..c74c1ea 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js @@ -2,6 +2,7 @@ * @author SkylineBin * @time 2018-10-6 * @function use javascript to bubble sort arrays + * 对 数组 arrays 进行冒泡排序 * * @Algorithm_bigO O(N^2) * N is the length of arrays diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js new file mode 100644 index 0000000..d3862c7 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js @@ -0,0 +1,88 @@ +/** + * @author SkylineBin + * @time 2019-03-18 + * @function 使用大样本对常用的算法进行测试 + * 基于 对数器的思想 + * + * + */ + +const BubbleSort = require('./BubbleSort'); +const SelectionSort = require('./SelectionSort'); +const InsertionSort = require('./InsertionSort'); +const MergeSort = require('./MergeSort'); +const DutchFlagArray = require('./DultFlagArray'); + + +// 生成指定长度和取值范围的数组 +function generateRandomArray(size, value) { + let randomArrays = []; + // 生成长度随机的数组 + let arrayLength = parseInt((size + 1) * Math.random()); + for (let index = 0; index < arrayLength; index++) { + randomArrays[index] = parseInt((value + 1) * Math.random()) - parseInt(value * Math.random()); + } + + if (randomArrays.length === 0) { + arrayLength = generateRandomArray(size, value); + } + + return randomArrays; +} + +// 复制两个一样的数组 +function copyArray(array){ + if (array === null) { + return null; + } + let resultArray = []; + for (let index = 0; index < array.length; index++) { + resultArray[index] = array[index]; + } + return resultArray; +} + +// 判断两个数组是否相同 +function isEqual(arrone, arrtwo) { + if ((arrone === null && arrtwo !== null) || (arrone !== null && arrtwo === null)) { + return false; + } + if (arrone === null && arrtwo === null) { + return true; + } + if (arrone.length !== arrtwo.length) { + return false; + } + for (let index = 0; index < arrone.length; index++) { + if (arrone[index] != arrtwo[index]) { + return false; + } + } + return true; +} + + + +let size = 10; +let value = 100; +let randomArrays = generateRandomArray(size, value); +let copyarray = copyArray(randomArrays); +console.log(randomArrays); + +console.log("--------start Sort-----------"); + +// BubbleSort(randomArrays); +// SelectionSort(randomArrays); +// MergeSort(randomArrays); +InsertionSort(randomArrays); +console.log("--------after Sort-----------"); +console.log(randomArrays); + +console.log("--------system Sort-----------"); +copyarray.sort(function (a, b) { + return a - b; +}); +console.log(copyarray); + +console.log(isEqual(randomArrays, copyarray)); + From b12a7cdb2e361257cb3016b7712eff1a396464ef Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 18 Mar 2019 21:19:49 +0800 Subject: [PATCH 087/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=AE=80=E5=8C=96?= =?UTF-8?q?=E7=89=88=E4=BB=A3=E7=A0=81=E4=BB=A5=E5=8F=8A=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJava/DutchFlagArray.java | 1 + .../DultFlagArray.js | 35 +++++- DataStructures/LinkedList/CreateLinkedList.js | 5 +- .../LinkedList/UseDoublyLinkedList.js | 100 +++++++++--------- 4 files changed, 89 insertions(+), 52 deletions(-) diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java index 1d2131f..ccbcfae 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java @@ -16,6 +16,7 @@ public static int[] partition(int[] arr, int L, int R, int num) { } } return new int[] {less + 1, more - 1}; + // 返回的是 等于区域的 左右边界下标 数组 } public static void swap(int[] arr, int i, int j) { diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js index 454b5d5..0dd5804 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js @@ -27,8 +27,41 @@ module.exports = function DutchFlagArray(arrays, L, R, num) { return arrays; } + +/** + * @function 用于交互数组中的指定位置的两个数 + * @param {*} arrays + * @param {*} si + * @param {*} sj + */ function swap(arrays, si, sj) { let tempdata = arrays[si]; arrays[si] = arrays[sj]; arrays[sj] = tempdata; -} \ No newline at end of file +} + +/** + * @function 简化版 分两类问题, 左边是小于等于 num 的 + * @param {arrays} arrays + * @param {midnum} num + */ +function singleArray(arrays, num) { + if (arrays == null || arrays.length < 2) { + return; + } + let left = -1; + let current = 0; + let arrLength = arrays.length; + while (current < arrLength) { + if (arrays[current] < num) { + swap(arrays, ++left, current++); + } else { + current++; + } + } + return arrays; +} + +// let testArray = [-51, 50, -66, -22, 13, -16, 27, 74, -16, 38]; +// console.log(testArray); +// console.log(singleArray(testArray,0)); \ No newline at end of file diff --git a/DataStructures/LinkedList/CreateLinkedList.js b/DataStructures/LinkedList/CreateLinkedList.js index 73b8ea3..dd80716 100644 --- a/DataStructures/LinkedList/CreateLinkedList.js +++ b/DataStructures/LinkedList/CreateLinkedList.js @@ -6,5 +6,8 @@ */ module.exports = class LinkedList { - + constructor() { + // using a Array items to store Queue Datas + this.items = []; + } } \ No newline at end of file diff --git a/DataStructures/LinkedList/UseDoublyLinkedList.js b/DataStructures/LinkedList/UseDoublyLinkedList.js index 6dba6e8..c5b0d97 100644 --- a/DataStructures/LinkedList/UseDoublyLinkedList.js +++ b/DataStructures/LinkedList/UseDoublyLinkedList.js @@ -6,59 +6,59 @@ * */ - function DoublyLinkedList( ) { - let Node = function(element) { - this.element = element; - this.next = null; - this.prev = null; - } +function DoublyLinkedList( ) { + let Node = function(element) { + this.element = element; + this.next = null; + this.prev = null; + } - let length = 0; - let head = null; - let tail = null; + let length = 0; + let head = null; + let tail = null; - // insert a element at this position - this.insert = function(position,element) { - if (position >= 0 && position <= length) { - let node = new Node(element), - current = head, - previous, - index = 0; +// insert a element at this position + this.insert = function(position,element) { + if (position >= 0 && position <= length) { + let node = new Node(element), + current = head, + previous, + index = 0; - if (position === 0) { - // 在双向链表的头部插入一个元素 - if (!head) { - head = node; - tail = node; - } else { - node.next = current; - current.prev = node; - head = node; - } - } else if (position === length) { - // 在链表的尾部插入一个元素 - current = tail; - current.next = node; - node.prev = current; - tail = node; - } else { - // 在链表中间插入该元素 - while (index++ < position) { - previous = current; - current = current.next; - } - node.next = current; - previous.next = node; - current.prev = node; - node.prev = previous; - } + if (position === 0) { + // 在双向链表的头部插入一个元素 + if (!head) { + head = node; + tail = node; + } else { + node.next = current; + current.prev = node; + head = node; + } + } else if (position === length) { + // 在链表的尾部插入一个元素 + current = tail; + current.next = node; + node.prev = current; + tail = node; + } else { + // 在链表中间插入该元素 + while (index++ < position) { + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + current.prev = node; + node.prev = previous; + } - length++; - return true; - } else { - return false; - } - }; + length++; + return true; + } else { + return false; + } + }; // remove element at this position this.removeAt = function(position) { @@ -97,4 +97,4 @@ } }; - } \ No newline at end of file +} \ No newline at end of file From 1d055c063bce5fb34307d9caa15dcf7185c11f2e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 18 Mar 2019 22:10:28 +0800 Subject: [PATCH 088/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=BF=AB=E9=80=9F?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E7=9A=84=20Java=20=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=92=8C=20JavaScript=20=E7=89=88=E6=9C=AC=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJava/QuickSort.java | 154 ++++++++++++++++++ .../DultFlagArray.js | 3 +- .../SortAlgorithmsbyJavaScript/QuickSort.js | 65 ++++++++ .../SortAlgorithmsbyJavaScript/mainSort.js | 13 +- 4 files changed, 231 insertions(+), 4 deletions(-) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java new file mode 100644 index 0000000..c1824d1 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java @@ -0,0 +1,154 @@ +package basic_algorithm; + +import java.util.Arrays; + +public class QuickSort { + + // 使用 java 进行 快速排序 + public static void quickSort(int[] arr) { + if (arr == null || arr.length < 2) { + return; + } + quickSortProcess(arr, 0, arr.length - 1); + } + + public static void quickSortProcess(int[] arr, int L, int R) { + if (L < R) { + int[] p = partition(arr, L, R); + quickSortProcess(arr, L, p[0] - 1); + quickSortProcess(arr, p[1]+1, R); + } + } + + public static int[] partition(int[] arr, int L, int R) { + int less = L - 1; + int more = R; + int index = L; + while (index < more) { + if (arr[index] < arr[R]) { + swap(arr, ++less, index++); + } else if (arr[index] > arr[R]){ + swap(arr, --more, index); + } else { + index++; + } + } + // 因为是分类过程中是和传过来的 arrays[R] 进行比较 + // 所以第一个 大于 arrays[R] 的数arrays[more] 要和 arrays[R] 交换 + swap(arr, more, R); + return new int[] {less + 1, more }; + // 返回的是 等于区域 的范围 (左右边界下标) + } + + public static void swap(int[] arr, int i, int j) { + // 交换两个数 + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } + + + +// for test (绝对正确的算法) +// 一般使用系统自带的排序算法,或者容易实现无错误的算法 + public static void rightMethod(int[] arr) { + Arrays.sort(arr); + } + + + + + +// for test +// 使用对数器进行测试 + public static int[] generateRandomArray(int size, int value) { +// 使用系统自带的随机数生成器生成备选数集合 +// Math.random() -> double [0,1) +// (int) ((size + 1) * Math.random()) -> [0,size] 整数集合 +// size =6, size + 1 =7; +// Math.random() -> [0,1) * 7 -> [0,7) double +// double -> int [0,6] -> int + + +// 生成长度随机的数组 + int[] arr = new int[(int) ((size + 1) * Math.random())]; +// 数组内的每个数也是随机的 + for (int i = 0; i < arr.length; i++) { + arr[i] = (int) ((value + 1) * Math.random()) - (int) (value * Math.random()); + } + return arr; + + } + +// for test +// 生成拷贝数组的方法 + public static int[] copyArray(int[] arr) { + if (arr == null) { + return null; + } + int[] res = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + res[i] = arr[i]; + } + return res; + } + +// for test +// 判断两个数组是否相同 + public static boolean isEqual(int[] arrone, int[] arrtwo) { + if((arrone == null && arrtwo != null) || (arrone != null && arrtwo == null)) { + return false; + } + if(arrone == null && arrtwo == null) { + return true; + } + if(arrone.length != arrtwo.length) { + return false; + } + for (int i = 0; i < arrone.length; i++) { + if (arrone[i] != arrtwo[i]) { + return false; + } + } + return true; + } + +// for test +// 打印数组的方法 + public static void printArray(int[] arr) { + if(arr == null || arr.length ==0) { + System.out.println(""); + }else { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + } + } + + +// 大样本测试 方法 + public static void main(String[] args) { + int testTime = 500000; + int size = 10; + int value = 100; + boolean succeed = true; + for (int i = 0; i < testTime; i++) { + int[] arrone = generateRandomArray(size, value); + int[] arrtwo = copyArray(arrone); + int[] arrthree = copyArray(arrone); + quickSort(arrone); + rightMethod(arrtwo); + if(!isEqual(arrone, arrtwo)) { + succeed = false; + printArray(arrthree); + break; + } + } + + System.out.println(succeed ? "well done!" : "wrong algorithms!"); + + int[] arr = generateRandomArray(size, value); + printArray(arr); + + } +} diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js index 0dd5804..c13f401 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js @@ -24,7 +24,8 @@ module.exports = function DutchFlagArray(arrays, L, R, num) { L++; } } - return arrays; + // return arrays; + return [less+1, more-1]; } diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js new file mode 100644 index 0000000..77d6902 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js @@ -0,0 +1,65 @@ +/** + * @author SkylineBin + * @time 2019-03-18 + * @function create QuickSort by JavaScript + * 实现改进形式的快速排序 + * @Algorithm_bigO + * O(N * log(N)) + * + */ + +module.exports = function QuickSort(arrays) { + if (arrays == null || arrays.length < 2) { + return; + } + // 处理 快排 的 过程 + quickSortProgress(arrays, 0, arrays.length - 1); +} + +/** + * @function 快速排序的实际执行过程,整个递归的执行条件是 Ln < Rn + * @param {*} arrays + * @param {*} Ln + * @param {*} Rn + */ +function quickSortProgress(arrays, Ln, Rn) { + if (Ln < Rn) { + let p = partition(arrays, Ln, Rn); + quickSortProgress(arrays, Ln, p[0]-1); + quickSortProgress(arrays, p[1]+1, Rn); + } +} + +/** + * @function 对数组分三类的方法 + * @param {*} arrays + * @param {*} L + * @param {*} R + */ +function partition(arrays, L, R) { + let less = L - 1; + let more = R; + while (L < more) { + if (arrays[L] < arrays[R]) { + swap(arrays, ++less, L++); + } else if (arrays[L] > arrays[R]) { + swap(arrays, --more, L); + } else { + L++; + } + } + swap(arrays, more, R); // 因为是和传过来的 arrays[R] 进行比较所以第一个 大于 arrays[R] 的数arrays[more] 要和 arrays[R] 交换 + return [less + 1, more]; +} + +/** + * @function 用于交互数组中的指定位置的两个数 + * @param {*} arrays + * @param {*} si + * @param {*} sj + */ +function swap(arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js index 4066cb9..9f530a1 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -11,6 +11,7 @@ const SelectionSort = require('./SelectionSort'); const InsertionSort = require('./InsertionSort'); const MergeSort = require('./MergeSort'); const DutchFlagArray = require('./DultFlagArray'); +const QuickSort = require('./QuickSort'); let arrone = [3,6,2,4,0,5,9]; @@ -41,10 +42,16 @@ console.log(arrone); // console.log('--------end MergeSort-----------'); - console.log('--------start DutchFlagArray-----------'); + // console.log('--------start DutchFlagArray-----------'); - DutchFlagArray(arrone, 0, 6 , 4); + // DutchFlagArray(arrone, 0, 6 , 4); - console.log('--------end DutchFlagArray-----------'); + // console.log('--------end DutchFlagArray-----------'); + + console.log('--------start QuickSort-----------'); + + QuickSort(arrone); + + console.log('--------end QuickSort-----------'); console.log(arrone); \ No newline at end of file From a3ece185fffe752e5024a479f5478299e181825a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 18 Mar 2019 22:36:03 +0800 Subject: [PATCH 089/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A4=A7=E6=A0=B7?= =?UTF-8?q?=E6=9C=AC=E6=B5=8B=E8=AF=95=E5=87=BD=E6=95=B0=EF=BC=8C=E9=92=88?= =?UTF-8?q?=E5=AF=B9=E5=BF=AB=E9=80=9F=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJavaScript/QuickSort.js | 2 +- .../SortAlgorithmsbyJavaScript/bigdataTest.js | 36 ++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js index 77d6902..2eac66c 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js @@ -2,7 +2,7 @@ * @author SkylineBin * @time 2019-03-18 * @function create QuickSort by JavaScript - * 实现改进形式的快速排序 + * 实现改进形式的快速排序 (三类快排) * @Algorithm_bigO * O(N * log(N)) * diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js index d3862c7..81ee237 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js @@ -12,6 +12,7 @@ const SelectionSort = require('./SelectionSort'); const InsertionSort = require('./InsertionSort'); const MergeSort = require('./MergeSort'); const DutchFlagArray = require('./DultFlagArray'); +const QuickSort = require('./QuickSort'); // 生成指定长度和取值范围的数组 @@ -61,6 +62,33 @@ function isEqual(arrone, arrtwo) { return true; } +// 大样本测试 +function moreDataTest(){ + let size = 10; + let value = 100; + let testTime = 500000; + let succeed = true; + for (let index = 0; index < testTime; index++) { + let arrOne = generateRandomArray(size, value); + let arrTwo = copyArray(arrOne); + let arrThree = copyArray(arrOne); + // BubbleSort(arrOne); + // MergeSort(arrOne); + // InsertionSort(arrOne); + QuickSort(arrOne); + arrTwo.sort(function (a, b) { + return a - b; + }); + if (!isEqual(arrOne, arrTwo)) { + succeed = false; + console.log(arrThree); + break; + } + } + console.log(succeed ? 'well done! all right' : 'something is wrong!'); +} + + let size = 10; @@ -74,7 +102,9 @@ console.log("--------start Sort-----------"); // BubbleSort(randomArrays); // SelectionSort(randomArrays); // MergeSort(randomArrays); -InsertionSort(randomArrays); +// InsertionSort(randomArrays); +QuickSort(randomArrays); + console.log("--------after Sort-----------"); console.log(randomArrays); @@ -86,3 +116,7 @@ console.log(copyarray); console.log(isEqual(randomArrays, copyarray)); +moreDataTest(); + + + From 371116b5cf9b2d3b9c1aecd8a19c9dea7733ffcb Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 19 Mar 2019 20:27:55 +0800 Subject: [PATCH 090/274] =?UTF-8?q?=E6=89=BE=E9=93=BE=E8=A1=A8=E7=9A=84?= =?UTF-8?q?=E7=AC=AC=20k=20=E4=B8=AA=E7=BB=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/findKthToTail.js | 60 +++++++++++++++++++++++++ NowCoder/Leetcode/findNumbersWithSum.js | 17 +++++++ 2 files changed, 77 insertions(+) create mode 100644 NowCoder/Leetcode/findKthToTail.js create mode 100644 NowCoder/Leetcode/findNumbersWithSum.js diff --git a/NowCoder/Leetcode/findKthToTail.js b/NowCoder/Leetcode/findKthToTail.js new file mode 100644 index 0000000..7a48d3d --- /dev/null +++ b/NowCoder/Leetcode/findKthToTail.js @@ -0,0 +1,60 @@ +/*** +* +* 输入一个链表, +* 输出该链表中倒数第k个结点。 +* +* +***/ +// ! 本质涉及: 链表的查操作,快慢指针的解析 +// 慢指针 比快指针迟 k 个,先找到第 k 个 数据给快指针,慢指针从头开始 +// 向后移动 k 个 快指针达到末尾,慢指针到达倒数 第 k个 结点 + +function ListNode(x){ + this.val = x; + this.next = null; +} +// 1,{1,2,3,4,5} + +function FindKthToTail(head, k) { + // write code here + if (head == null || k <= 0) { + return null; + } + let slowTail = head; + let fastTail = head; + for (let index = 0; index < k - 1; index++) { + if (fastTail.next != null) { // 排除数组越界,不能使用 fastTail != null + fastTail = fastTail.next; + }else { + return null; + } + } + while(fastTail.next != null) { + fastTail = fastTail.next; + slowTail = slowTail.next; + } + return slowTail; +} + + + + + + +let list1 = new ListNode(1); +let list2 = new ListNode(2); +list1.next = list2; +let list3 = new ListNode(3); +list2.next = list3; +let list4 = new ListNode(4); +list3.next = list4; +let list5 = new ListNode(5); +list4.next = list5; +// list.append(10); +// list.append(15); +// list.append(4); +// list.append(16); +// list.append(13); + +// Test Algorithm +console.log(FindKthToTail(list1, 3)); diff --git a/NowCoder/Leetcode/findNumbersWithSum.js b/NowCoder/Leetcode/findNumbersWithSum.js new file mode 100644 index 0000000..9f3438a --- /dev/null +++ b/NowCoder/Leetcode/findNumbersWithSum.js @@ -0,0 +1,17 @@ +/*** +* +* 输入一个递增排序的数组和一个数字S, 在数组中查找两个数, +* 使得他们的和正好是S, 如果有多对数字的和等于S, +* 输出两个数的乘积最小的。 +* +* +***/ +// ! 本质涉及: 排序算法 + +function FindNumbersWithSum(array, sum) { + // write code here +} + +// Test Algorithm +var testNum = [1,2,3,4,5,6,7,8,9,10]; +console.log(FindNumbersWithSum(testNum, 9)); \ No newline at end of file From 24a82cf7bc507eedb811866ca4c9311d8a197a2c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 19 Mar 2019 21:49:23 +0800 Subject: [PATCH 091/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=9A=8F=E6=9C=BA?= =?UTF-8?q?=E5=BF=AB=E6=8E=92=E7=9A=84=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 6 ++++++ .../basic_algorithm/SortAlgorithmsbyJava/QuickSort.java | 1 + .../basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js | 4 ++++ .../basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js | 2 +- 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 151977b..7c202e3 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,5 +1,11 @@ { "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - QuickSort", + "request": "launch", + "mainClass": "basic_algorithm.QuickSort" + }, { "type": "java", "name": "CodeLens (Launch) - Inversion", diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java index c1824d1..4d4b729 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java @@ -14,6 +14,7 @@ public static void quickSort(int[] arr) { public static void quickSortProcess(int[] arr, int L, int R) { if (L < R) { + swap(arr, L + (int)(Math.random() * (R - L + 1)), R); // 加入随机快排的调整 int[] p = partition(arr, L, R); quickSortProcess(arr, L, p[0] - 1); quickSortProcess(arr, p[1]+1, R); diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js index 2eac66c..653bca1 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js @@ -24,7 +24,10 @@ module.exports = function QuickSort(arrays) { */ function quickSortProgress(arrays, Ln, Rn) { if (Ln < Rn) { + // 添加随机快排的代码 + swap(arrays, Ln + parseInt(Math.random() * (Rn-Ln+1)), Rn); let p = partition(arrays, Ln, Rn); + // console.log(p); quickSortProgress(arrays, Ln, p[0]-1); quickSortProgress(arrays, p[1]+1, Rn); } @@ -49,6 +52,7 @@ function partition(arrays, L, R) { } } swap(arrays, more, R); // 因为是和传过来的 arrays[R] 进行比较所以第一个 大于 arrays[R] 的数arrays[more] 要和 arrays[R] 交换 + // console.log(arrays); return [less + 1, more]; } diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js index 9f530a1..693d558 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -13,7 +13,7 @@ const MergeSort = require('./MergeSort'); const DutchFlagArray = require('./DultFlagArray'); const QuickSort = require('./QuickSort'); -let arrone = [3,6,2,4,0,5,9]; +let arrone = [3,6,5,2,4,0,5,3,9]; console.log(arrone); From 6168f22dee0f3ddacccf54d4439e3e1515997876 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 20 Mar 2019 22:20:22 +0800 Subject: [PATCH 092/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A0=86=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=E7=9A=84=20Java=20=E5=86=99=E6=B3=95=20=E5=92=8C=20Ja?= =?UTF-8?q?vaScript=20=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJava/HeapSort.java | 54 ++++++++++++++ .../SortAlgorithmsbyJavaScript/HeapSort.js | 71 +++++++++++++++++++ .../SortAlgorithmsbyJavaScript/mainSort.js | 13 +++- 3 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJava/HeapSort.java create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/HeapSort.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/HeapSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/HeapSort.java new file mode 100644 index 0000000..b3add25 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/HeapSort.java @@ -0,0 +1,54 @@ +package basic_algorithm; + +public class HeapSort { + + // 用 Java 实现堆排序 + public static void heapSort(int[] arr) { + if (arr == null || arr.length < 2) { + return; + } + for (int i = 0; i < arr.length; i++) { + heapInsert(arr, i); // 在 0~i 直接形成大根堆 + } + // for循环 后整个数组形成大根堆结构 + int heapSize = arr.length; + swap(arr, 0, --heapSize); + while (heapSize > 0) { + heapify(arr, 0, heapSize); + swap(arr, 0, --heapSize); + } + + } + + // 实现大根堆的结构,与父节点进行对比和交换 + public static void heapInsert(int[] arr, int index) { + while (arr[index] > arr[(index - 1)/2]) { + swap(arr, index, (index - 1) / 2); + index = (index - 1) / 2; + } + } + + // index 位置被更换后如何重新变成大根堆 + public static void heapify(int[] arr, int index, int heapSize) { + int left = index * 2 + 1; + while (left < heapSize) { + // 取到左右孩子中的最大的那一个 + int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left+1 : left; // 右孩子不越界,并且右孩子比左孩子大才能取到左孩子 + largest = arr[largest] > arr[index] ? largest : index; + if (largest == index) { + break; + } + swap(arr, index, largest); + index = largest; + left = index * 2 + 1; + } + + } + + public static void swap(int[] arr, int i, int j) { + // 交换两个数 + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } +} diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/HeapSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/HeapSort.js new file mode 100644 index 0000000..73947fd --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/HeapSort.js @@ -0,0 +1,71 @@ +/** + * @author SkylineBin + * @time 2019-03-20 + * @function create HeapSort by JavaScript + * 实现堆排序 + * @Algorithm_bigO + * O(N * log(N)) + * + */ + +module.exports = function HeapSort(arrays) { + if (arrays == null || arrays.length < 2) { + return; + } + // 处理 快排 的 过程 + for (let index = 0; index < arrays.length; index++) { + heapInsert(arrays, index); + } + let heapSize = arrays.length; + swap(arrays, 0, --heapSize); + while (heapSize > 0) { + heapify(arrays, 0, heapSize); + swap(arrays, 0, --heapSize); + } + +} + +/** + * @function 将一个数组调整成大根堆结构 + * @param {*} arrays + * @param {*} index + */ +function heapInsert(arrays, index) { + // 要使用 parseInt,要不然会出错 + while (arrays[index] > arrays[parseInt((index-1)/2)]) { + swap(arrays, index, parseInt((index - 1) / 2)); + index = parseInt((index - 1) / 2); + } +} + +/** + * @function index位置的数变小后进行往下沉处理,直到形成新的大根堆 + * @param {*} arrays + * @param {*} index + * @param {*} heapSize + */ +function heapify(arrays, index, heapSize){ + let left = index * 2 + 1; + while (left < heapSize) { + let largest = ((left + 1) < heapSize) && arrays[left+1] > arrays[left] ? left + 1 : left; + largest = arrays[largest] > arrays[index] ? largest : index; + if (largest === index) { + break; + } + swap(arrays, index, largest); + index = largest; + left = index * 2 + 1; + } +} + +/** + * @function 用于交互数组中的指定位置的两个数 + * @param {*} arrays + * @param {*} si + * @param {*} sj + */ +function swap(arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js index 693d558..bb8be16 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -12,6 +12,7 @@ const InsertionSort = require('./InsertionSort'); const MergeSort = require('./MergeSort'); const DutchFlagArray = require('./DultFlagArray'); const QuickSort = require('./QuickSort'); +const HeapSort = require('./HeapSort'); let arrone = [3,6,5,2,4,0,5,3,9]; @@ -48,10 +49,16 @@ console.log(arrone); // console.log('--------end DutchFlagArray-----------'); - console.log('--------start QuickSort-----------'); + // console.log('--------start QuickSort-----------'); - QuickSort(arrone); + // QuickSort(arrone); - console.log('--------end QuickSort-----------'); + // console.log('--------end QuickSort-----------'); + + console.log('--------start HeapSort-----------'); + + HeapSort(arrone); + + console.log('--------end HeapSort-----------'); console.log(arrone); \ No newline at end of file From a17163c62852bcba0491d4910ec83dd4ff74d978 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 21 Mar 2019 21:16:20 +0800 Subject: [PATCH 093/274] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E9=87=8D=E5=BB=BA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E7=AE=97=E6=B3=95=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 需要理解二叉树的前序遍历,中序遍历,后序遍历的特点,以及之间的联系 --- .../SortAlgorithmsbyJavaScript/bigdataTest.js | 5 ++- NowCoder/Leetcode/reConstructBinaryTree.js | 41 +++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 NowCoder/Leetcode/reConstructBinaryTree.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js index 81ee237..fee69ae 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js @@ -13,7 +13,7 @@ const InsertionSort = require('./InsertionSort'); const MergeSort = require('./MergeSort'); const DutchFlagArray = require('./DultFlagArray'); const QuickSort = require('./QuickSort'); - +const HeapSort = require('./HeapSort'); // 生成指定长度和取值范围的数组 function generateRandomArray(size, value) { @@ -75,7 +75,8 @@ function moreDataTest(){ // BubbleSort(arrOne); // MergeSort(arrOne); // InsertionSort(arrOne); - QuickSort(arrOne); + // QuickSort(arrOne); + HeapSort(arrOne); arrTwo.sort(function (a, b) { return a - b; }); diff --git a/NowCoder/Leetcode/reConstructBinaryTree.js b/NowCoder/Leetcode/reConstructBinaryTree.js new file mode 100644 index 0000000..01be862 --- /dev/null +++ b/NowCoder/Leetcode/reConstructBinaryTree.js @@ -0,0 +1,41 @@ +/*** +* +* 输入某二叉树的前序遍历和中序遍历的结果, 请重建出该二叉树。 +* 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 例如输入前序遍历序列 +* {1,2,4,7,3,5,6,8} +* 和中序遍历序列 +* {4,7,2,1,5,3,8,6}, +* 则重建二叉树并返回。 +* +* +***/ +// ! 本质涉及: 二叉树的前序,中序,后序遍历的规则 +// ! 主要还是使用前序遍历找到中间(根)节点的形式,根据中序遍历确认左右两侧的长度,进行递归 + +/* function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} */ +function reConstructBinaryTree(pre, vin) { + // write code here + if (pre.length === 0 || vin.length === 0 || pre.length !== vin.length) { + return null; + } + // 获取中间节点(根节点) + let index = vin.indexOf(pre[0]); + let left = vin.slice(0, index); + let right = vin.slice(index+1); + return { + val: pre[0], + left: reConstructBinaryTree(pre.slice(1, index+1), left), + right: reConstructBinaryTree(pre.slice(index+1), right) + }; +} + +// Test Algorithm +// var testNum = 5; +let pre = [1, 2, 4, 7, 3, 5, 6, 8]; +let vin = [4,7,2,1,5,3,8,6]; +console.log(reConstructBinaryTree(pre, vin)); +console.log(reConstructBinaryTree(pre, vin).left.left.right); \ No newline at end of file From 27219e3815ffcc6d267326109b0b395e392ed23e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 22 Mar 2019 15:42:42 +0800 Subject: [PATCH 094/274] =?UTF-8?q?=E4=B8=BB=E8=A6=81=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E5=88=86=E7=A6=BB=E9=93=BE=E6=8E=A5=E6=96=B9=E6=B3=95=E4=BB=A5?= =?UTF-8?q?=E5=8F=8A=E8=B0=83=E6=95=B4=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Dictionary/UseDictionary.js | 2 +- DataStructures/Dictionary/UseHashTable.js | 41 ++--- .../Dictionary/UseHashTableApart.js | 5 + DataStructures/LinkedList/CreateLinkedList.js | 148 +++++++++++++++++- DataStructures/LinkedList/mainLinkedList.js | 9 ++ DataStructures/Queue/CreateQueue.js | 4 +- DataStructures/Set/UseES6Set.js | 18 +-- DataStructures/Set/UseSetbySelf.js | 38 ++--- .../Stack/SolveProblem/SymbolsBalance.js | 2 +- README.md | 5 +- 10 files changed, 219 insertions(+), 53 deletions(-) create mode 100644 DataStructures/LinkedList/mainLinkedList.js diff --git a/DataStructures/Dictionary/UseDictionary.js b/DataStructures/Dictionary/UseDictionary.js index 0bc1120..026858d 100644 --- a/DataStructures/Dictionary/UseDictionary.js +++ b/DataStructures/Dictionary/UseDictionary.js @@ -57,7 +57,7 @@ function Dictionary() { // get all keys this.keys = function () { - return Object.keys(items); + return Object.keys(items); // 可直接使用对象的原型方法 } // get this item diff --git a/DataStructures/Dictionary/UseHashTable.js b/DataStructures/Dictionary/UseHashTable.js index a34884c..ff39683 100644 --- a/DataStructures/Dictionary/UseHashTable.js +++ b/DataStructures/Dictionary/UseHashTable.js @@ -3,28 +3,30 @@ * @author SkylineBin * @time 2018-10-16 * @function Create HashTable Structure by JavaScript - * + * 散列算法的作用是尽可能快地在数据结构中找到一个值 + * 散列函数的作用是给定一个键值,然后返回值在表中的地址 * */ - function HashTable() { - var table = []; +function HashTable() { + var table = []; - // lose lose hash code - var loseloseHashCode = function (key) { - var hash = 0; - for (let index = 0; index < key.length; index++) { - hash += key.charCodeAt(index); - } - return hash % 37; - }; + // lose lose hash code 散列函数 + // 此种简单的散列方式存在一定的缺陷,即可能产生冲突,常用的冲突处理方法有:分离链接、线性探查和双散列法 + var loseloseHashCode = function (key) { + var hash = 0; + for (let index = 0; index < key.length; index++) { + hash += key.charCodeAt(index); + } + return hash % 37; + }; - // put this value at the position computed by this key - this.put = function (key, value) { - var position = loseloseHashCode(key); - console.log(position + '-' + key); - table[position] = value; - } +// put this value at the position computed by this key + this.put = function (key, value) { + var position = loseloseHashCode(key); + console.log(position + '-' + key); + table[position] = value; + } // get this value by key this.get = function (key) { @@ -45,9 +47,9 @@ } } - } +} - let hash = new HashTable(); +let hash = new HashTable(); hash.put('John', 'jogn@gmail.com'); hash.put('Tyrion', 'tyrion@gmail.com'); hash.put('Shanny', 'shanny@gmail.com'); @@ -58,6 +60,7 @@ console.log(hash.get('Mike')); console.log(hash.get('Rick')); console.log('------------------------------------'); +// 演示冲突的产生 hash.put('Jonathan', 'jonathan@gmail.com'); hash.put('Jamie', 'jamie@gmail.com'); hash.put('Sue', 'sue@gmail.com'); diff --git a/DataStructures/Dictionary/UseHashTableApart.js b/DataStructures/Dictionary/UseHashTableApart.js index 4c9acb7..45e39c9 100644 --- a/DataStructures/Dictionary/UseHashTableApart.js +++ b/DataStructures/Dictionary/UseHashTableApart.js @@ -3,10 +3,13 @@ * @author SkylineBin * @time 2018-10-16 * @function Create HashTable Structure (Apart Link) by JavaScript + * @function 使用分离链接的方法来处理Hash表的冲突 * * */ +const LinkedList = require('../LinkedList/CreateLinkedList'); + function HashTable() { var table = []; @@ -19,6 +22,7 @@ function HashTable() { return hash % 37; }; + // var ValuePair = function (key, value) { this.key = key; this.value = value; @@ -109,6 +113,7 @@ console.log(hash.get('Mike')); console.log(hash.get('Rick')); console.log('------------------------------------'); + hash.put('Jonathan', 'jonathan@gmail.com'); hash.put('Jamie', 'jamie@gmail.com'); hash.put('Sue', 'sue@gmail.com'); diff --git a/DataStructures/LinkedList/CreateLinkedList.js b/DataStructures/LinkedList/CreateLinkedList.js index dd80716..208d5eb 100644 --- a/DataStructures/LinkedList/CreateLinkedList.js +++ b/DataStructures/LinkedList/CreateLinkedList.js @@ -2,12 +2,158 @@ * @author SkylineBin * @time 2018-9-19 * @function Create a LinkedList structure + * 封装链表结构 * */ +// let + module.exports = class LinkedList { constructor() { // using a Array items to store Queue Datas - this.items = []; + // this.items = []; + this.length = 0; + this.head = null; + this.Node = function (element) { + this.element = element; + this.next = null; + } + } + + + + // append another element after the end of this linkedlist + append(thiselement) { + let node = new this.Node(thiselement), + current; + if (this.head == null) { + this.head = node; + } else { + current = this.head; + while (current.next) { + current = current.next; + } + current.next = node; + } + this.length++; + } + + // insert an element into this position + insert(position, element) { + if (position > -1 && position < this.length) { + let node = new this.Node(element), + current = this.head, + previous, + index = 0; + + if (position === 0) { + // insert element at the head of this LinkedList + node.next = current; + this.head = node; + } else { + while (index++ < position) { + previous = current; + current = current.next; + } + + // insert elemrnt in this position + node.next = current; + previous.next = node; + } + this.length++; + return true; + } else { + return false; + } + }; + + // remove the element at this position + removeAt(position) { + // check Cross-border + if (position > -1 && position < length) { + let current = this.head, + previous, + index = 0; + + if (position === 0) { + this.head = current.next; + } else { + while (index++ < position) { + previous = current; + current = current.next; + } + // current element will be recyclied by JavaScript GC + previous.next = current.next; + } + this.length--; + + return current.element; + } else { + return null; + } + }; + + // remove one element from this linkedlist + remove(element) { + // find the position + // remove this element at the position + let index = this.indexOf(element); + return this.removeAt(index); + }; + + // find the index of this linkedlist + indexOf(element) { + let current = this.head; + index = -1; + while (current) { + if (element === current.element) { + return index; + } + index++; + current = current.next; + } + return -1; + }; + + // check this linkedlist is empty + isEmpty() { + return this.length === 0; + }; + + // get the size of this linkedlist + size() { + return this.length; + } + + // get the head of this LinkedList + getHead() { + return this.head; + } + + // to String + toString() { + let current = this.head; + let string = ''; + while (current) { + string += current.element + (current.next ? '_' : ''); + current = current.next; + } + return string; + + + } + + // print this LinkedList + print() { + let current = this.head; + let outstr = ''; + while (current) { + // console.log(current.element); + outstr += String(current.element) + (current.next ? ' ' : ''); + current = current.next; + } + console.log('------------------------------------'); + console.log(outstr); + console.log('------------------------------------'); } } \ No newline at end of file diff --git a/DataStructures/LinkedList/mainLinkedList.js b/DataStructures/LinkedList/mainLinkedList.js new file mode 100644 index 0000000..d9eca37 --- /dev/null +++ b/DataStructures/LinkedList/mainLinkedList.js @@ -0,0 +1,9 @@ +const LinkedList = require('./CreateLinkedList'); +let list = new LinkedList(); +list.append(10); +list.append(15); +list.append(4); +list.append(16); +list.append(13); + +list.print(); \ No newline at end of file diff --git a/DataStructures/Queue/CreateQueue.js b/DataStructures/Queue/CreateQueue.js index aa8e0be..ef5206e 100644 --- a/DataStructures/Queue/CreateQueue.js +++ b/DataStructures/Queue/CreateQueue.js @@ -5,7 +5,7 @@ * */ - module.exports = class Queue { +module.exports = class Queue { constructor() { // using a Array items to store Queue Datas this.items = []; @@ -40,4 +40,4 @@ console.log(this.items.toString()); } - } \ No newline at end of file +} \ No newline at end of file diff --git a/DataStructures/Set/UseES6Set.js b/DataStructures/Set/UseES6Set.js index f08be7b..6e34b5a 100644 --- a/DataStructures/Set/UseES6Set.js +++ b/DataStructures/Set/UseES6Set.js @@ -8,15 +8,15 @@ * */ - let setA = new Set(); - setA.add(1); - setA.add(2); - setA.add(3); - - let setB = new Set(); - setB.add(2); - setB.add(3); - setB.add(4); +let setA = new Set(); +setA.add(1); +setA.add(2); +setA.add(3); + +let setB = new Set(); +setB.add(2); +setB.add(3); +setB.add(4); // union two sets let unionAb = new Set(); diff --git a/DataStructures/Set/UseSetbySelf.js b/DataStructures/Set/UseSetbySelf.js index b656f03..60eddfc 100644 --- a/DataStructures/Set/UseSetbySelf.js +++ b/DataStructures/Set/UseSetbySelf.js @@ -6,14 +6,14 @@ * */ - function SetS() { - let items = {}; +function SetS() { + let items = {}; - // check if value in this set - this.has = function (value) { - // return value in items; // old function - return items.hasOwnProperty(value); - } +// check if value in this set + this.has = function (value) { + // return value in items; // old function + return items.hasOwnProperty(value); + } // add this value this.add = function (value) { @@ -131,20 +131,20 @@ } } - } +} - let set = new SetS(); - set.add(1); - set.add(2); - set.add(3); - set.add(6); - set.add(7); - console.log('------------------------------------'); - console.log(set.values()); - console.log('------------------------------------'); - console.log(set.has(1)); - console.log('------------------------------------'); +let set = new SetS(); +set.add(1); +set.add(2); +set.add(3); +set.add(6); +set.add(7); +console.log('------------------------------------'); +console.log(set.values()); +console.log('------------------------------------'); +console.log(set.has(1)); +console.log('------------------------------------'); console.log(set.size()); console.log('------------------------------------'); set.add(4); diff --git a/DataStructures/Stack/SolveProblem/SymbolsBalance.js b/DataStructures/Stack/SolveProblem/SymbolsBalance.js index 9e02c76..cc832dd 100644 --- a/DataStructures/Stack/SolveProblem/SymbolsBalance.js +++ b/DataStructures/Stack/SolveProblem/SymbolsBalance.js @@ -6,7 +6,7 @@ */ // import the Stack stucture created by Array - const Stack = require('../CreateStack'); +const Stack = require('../CreateStack'); // Check Symbols Balance function checkSymbolBance(symbolString) { diff --git a/README.md b/README.md index d4d9fe6..76c7931 100644 --- a/README.md +++ b/README.md @@ -5,13 +5,16 @@ This project was originally set up to practice the algorithms on the OJ platform ## Data Structures Using JavaScript to create those data structures. - +DataStructures\Dictionary ## Disk Scheduling Algorithm Carrying out disk scheduling algorithm by Java. +## LeetCode +NowCoder\Leetcode + ## HuaWeiOJ Algorithms Some algorithms solved by Python2.7 from HuaWeiOJ Projects From 6bb1e9eb82563cb8f5de3a9f6864a1099cb8fe8c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 23 Mar 2019 11:27:40 +0800 Subject: [PATCH 095/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=9B=B4=E5=8F=97?= =?UTF-8?q?=E6=AC=A2=E8=BF=8E=E7=9A=84=E6=95=A3=E5=88=97=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Dictionary/UseHashTable.js | 7 ++++++- .../Dictionary/UseHashTableLinerCheck.js | 7 ++++--- DataStructures/Dictionary/betterHashFuction.js | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 DataStructures/Dictionary/betterHashFuction.js diff --git a/DataStructures/Dictionary/UseHashTable.js b/DataStructures/Dictionary/UseHashTable.js index ff39683..c2cfbc5 100644 --- a/DataStructures/Dictionary/UseHashTable.js +++ b/DataStructures/Dictionary/UseHashTable.js @@ -8,6 +8,8 @@ * */ +const djb2HashCode = require('./betterHashFuction'); + function HashTable() { var table = []; @@ -24,6 +26,7 @@ function HashTable() { // put this value at the position computed by this key this.put = function (key, value) { var position = loseloseHashCode(key); + // var position = djb2HashCode(key); console.log(position + '-' + key); table[position] = value; } @@ -31,11 +34,13 @@ function HashTable() { // get this value by key this.get = function (key) { return table[loseloseHashCode(key)]; + // return table[djb2HashCode(key)]; } // remove this value by key this.remove = function (key) { table[loseloseHashCode(key)] = undefined; + // table[djb2HashCode(key)] = undefined; } // print values of this HashTable @@ -57,7 +62,7 @@ hash.put('Mike', 'mike@gmail.com'); console.log('------------------------------------'); console.log(hash.get('Mike')); -console.log(hash.get('Rick')); +console.log(hash.get('John')); console.log('------------------------------------'); // 演示冲突的产生 diff --git a/DataStructures/Dictionary/UseHashTableLinerCheck.js b/DataStructures/Dictionary/UseHashTableLinerCheck.js index 72bf1f7..7849985 100644 --- a/DataStructures/Dictionary/UseHashTableLinerCheck.js +++ b/DataStructures/Dictionary/UseHashTableLinerCheck.js @@ -3,7 +3,7 @@ * @author SkylineBin * @time 2018-10-17 * @function Create HashTable Structure (Liner Check) by JavaScript - * + * @function 使用线性探查的方法解决冲突 * */ @@ -29,6 +29,7 @@ function HashTable() { }; // put this value at the position computed by this key + // 每一个有效值都是 ValuePair 的实例 this.put = function (key, value) { var position = loseloseHashCode(key); if (table[position] == undefined) { @@ -42,7 +43,7 @@ function HashTable() { } }; - // get this value by key + // get this value by key 还是要对比键是否相同 this.get = function (key) { var position = loseloseHashCode(key); @@ -70,7 +71,7 @@ function HashTable() { if (table[position] !== undefined) { if (table[position].key === key) { - table[index] = undefined; + table[position] = undefined; } else { var index = ++position; while (table[index] === undefined || diff --git a/DataStructures/Dictionary/betterHashFuction.js b/DataStructures/Dictionary/betterHashFuction.js new file mode 100644 index 0000000..91adefe --- /dev/null +++ b/DataStructures/Dictionary/betterHashFuction.js @@ -0,0 +1,16 @@ +/**** + * + * @function 更好的散列函数实例 + * 比之前使用的loseloseHashCode 好一些的散列函数 + * + */ + +var djb2HashCode = function (key) { + var hash = 5381; // 变量初始值为一个质数 + for (let index = 0; index < key.length; index++) { + hash = hash * 33 + key.charCodeAt(index); // 33 是此处的魔力数 + } + return hash % 1013; +} + +module.exports = djb2HashCode; \ No newline at end of file From bb7c854aefb1e6741cffcae2b8b04b177dd7eb5e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 25 Mar 2019 12:55:48 +0800 Subject: [PATCH 096/274] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E4=BB=A5=E5=8F=8AES6=E7=9A=84=E5=AD=97=E5=85=B8?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Dictionary/CreateDictionary.js | 64 ++++++++ .../Dictionary/betterHashFuction.js | 51 ++++++- DataStructures/Tree/BinarySearchTree.js | 141 ++++++++++++++++++ 3 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 DataStructures/Dictionary/CreateDictionary.js create mode 100644 DataStructures/Tree/BinarySearchTree.js diff --git a/DataStructures/Dictionary/CreateDictionary.js b/DataStructures/Dictionary/CreateDictionary.js new file mode 100644 index 0000000..5c6e719 --- /dev/null +++ b/DataStructures/Dictionary/CreateDictionary.js @@ -0,0 +1,64 @@ +/**** + * + * @function create dictionary module by JavaScript + * + */ + +module.exports = class Dictionary { + constructor() { + this.items = {}; + } + has(key) { + return key in this.items; + } + // set this value with this key + set(key, value) { + this.items[key] = value; + }; + + // delete this item + delete(key) { + if (this.has(key)) { + delete this.items[key]; + return true; + } + return false; + } + + // get this item by key + get(key) { + return this.has(key) ? this.items[key] : undefined; + } + + // get all values + values() { + var values = []; + for (let k in this.items) { + if (this.has(k)) { + values.push(this.items[k]); + } + } + return values; + }; + + // clear this dictionary + clear() { + this.items = {}; + } + + // get the size of this Set + size() { + return Object.keys(this.items).length; + } + + // get all keys + keys() { + return Object.keys(this.items); // 可直接使用对象的原型方法 + } + + // get this item + getItems() { + return this.items; + } + +} \ No newline at end of file diff --git a/DataStructures/Dictionary/betterHashFuction.js b/DataStructures/Dictionary/betterHashFuction.js index 91adefe..e260598 100644 --- a/DataStructures/Dictionary/betterHashFuction.js +++ b/DataStructures/Dictionary/betterHashFuction.js @@ -5,6 +5,8 @@ * */ +// const Dictionary = require('./CreateDictionary'); + var djb2HashCode = function (key) { var hash = 5381; // 变量初始值为一个质数 for (let index = 0; index < key.length; index++) { @@ -13,4 +15,51 @@ var djb2HashCode = function (key) { return hash % 1013; } -module.exports = djb2HashCode; \ No newline at end of file +module.exports = djb2HashCode; + +// let dictionary = new Dictionary(); +// dictionary.set('John', 'jogn@gmail.com'); +// dictionary.set('Tyrion', 'tyrion@gmail.com'); +// dictionary.set('Shanny', 'shanny@gmail.com'); +// dictionary.set('Mike', 'mike@gmail.com'); + +// console.log('------------------------------------'); +// console.log(dictionary.size()); +// console.log('------------------------------------'); +// console.log(dictionary.keys()); +// console.log(dictionary.values()); +// console.log('------------------------------------'); +// console.log('------------------------------------'); +// console.log(dictionary.delete('Shanny')); +// console.log(dictionary.keys()); +// console.log(dictionary.values()); +// console.log(dictionary.getItems()); +// console.log('------------------------------------'); +// console.log('------------------------------------'); +// console.log(dictionary.get('John')); + +let map = new Map(); +map.set('John', 'jogn@gmail.com'); +map.set('Tyrion', 'tyrion@gmail.com'); +map.set('Shanny', 'shanny@gmail.com'); +map.set('Mike', 'mike@gmail.com'); +console.log(map.delete('Shanny')); +console.log(map.keys()); +console.log(map.values()); +console.log(map.size); + +console.log('------------------------------------'); +console.log('------------------------------------'); + +let weakmap = new WeakMap(); +let obj1 = {name: 'John'}, + obj2 = {name: 'Hasky'}, + obj3 = {name: 'Goldway'}; + +weakmap.set(obj1, 'john@email.com'); +weakmap.set(obj2, 'hasky@email.com'); +weakmap.set(obj3, 'goldway@email.com'); + +console.log(weakmap.has(obj1)); +console.log(weakmap.get(obj2)); +console.log(weakmap.delete(obj3)); \ No newline at end of file diff --git a/DataStructures/Tree/BinarySearchTree.js b/DataStructures/Tree/BinarySearchTree.js new file mode 100644 index 0000000..d7811c5 --- /dev/null +++ b/DataStructures/Tree/BinarySearchTree.js @@ -0,0 +1,141 @@ +/***** + * + * @function 创建二叉搜索树 + * @date 2019-3-23 + * + */ + +function BinarySearchTree() { + + var Node = function (key) { + this.key = key; + this.left = null; + this.right = null; + }; + + var root = null; + + // 向树中插入一个新的键 + this.insert = function (key) { + var newNode = new Node(key); + if (root === null) { + root = newNode; + } else { + insertNode(root, newNode); + } + } + + // 将节点插入非根节点的其他位置(按照二叉搜索树的方式,左侧小于根节点,右侧大于等于根节点) + var insertNode = function (node, newNode) { + if (newNode.key < node.key) { + if (node.left === null) { + node.left = newNode; + } else { + insertNode(node.left, newNode); + } + } else { + if (node.right === null) { + node.right = newNode; + } else { + insertNode(node.right, newNode); + } + } + }; + + // 在树中查找一个键,存在为 true 不存在为 false + this.search = function (key) { + + } + + // 通过中序遍历方式遍历所有节点 + this.inOrderTraverse = function (callback) { + inOrderTraverseNode(root, callback); + } + // ! 中序遍历执行策略 + var inOrderTraverseNode = function (node, callback) { + if (node !== null) { + inOrderTraverseNode(node.left, callback); + callback(node.key); + inOrderTraverseNode(node.right, callback); + } + } + + // 通过先序遍历方式遍历所有节点 + this.preOrderTraverse = function (callback) { + preOrderTraverseNode(root, callback); + } + // ! 先序遍历执行策略 + var preOrderTraverseNode = function (node, callback) { + if (node !== null) { + callback(node.key); + preOrderTraverseNode(node.left, callback); + preOrderTraverseNode(node.right, callback); + } + } + + + // 通过后序遍历方式遍历所有节点 + this.postOrderTraverse = function (callback) { + postOrderTraverseNode(root, callback); + } + // ! 后序遍历执行策略 + var postOrderTraverseNode = function (node, callback) { + if (node !== null) { + postOrderTraverseNode(node.left, callback); + postOrderTraverseNode(node.right, callback); + callback(node.key); + } + } + + // 返回树中最小的值(键) + this.min = function () { + return minNode(root); + } + + var minNode = function (node) { + if (node) { + while (node && node.left !== null){ + node = node.left; + } + return node.key; + } + } + + // 返回树中最大的值(键) + this.max = function () { + + } + + // 从树中移除某个键 + this.remove = function (key) { + + } +} + +function printNode (value) { + console.log(value); +} + +let tree = new BinarySearchTree(); +tree.insert(11); +tree.insert(7); +tree.insert(15); +tree.insert(5); +tree.insert(3); +tree.insert(9); +tree.insert(8); +tree.insert(10); +tree.insert(13); +tree.insert(12); +tree.insert(14); +tree.insert(20); +tree.insert(18); +tree.insert(25); +tree.insert(6); +tree.inOrderTraverse(printNode); +console.log('------------------------------------'); +console.log('------------------------------------'); +tree.preOrderTraverse(printNode); +console.log('------------------------------------'); +console.log('------------------------------------'); +tree.postOrderTraverse(printNode); \ No newline at end of file From d5590c82aab54a86adc238c1f225e037c1aa5a11 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 25 Mar 2019 20:40:27 +0800 Subject: [PATCH 097/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E5=92=8C=E7=A7=BB=E9=99=A4=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E4=BB=A5=E5=8F=8A=E6=9E=84=E5=BB=BA=E5=9B=BE=E7=9A=84=E5=9F=BA?= =?UTF-8?q?=E6=9C=AC=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Graph/UseGraph.js | 58 ++++++++++++++++++++ DataStructures/Tree/BinarySearchTree.js | 73 ++++++++++++++++++++++++- 2 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 DataStructures/Graph/UseGraph.js diff --git a/DataStructures/Graph/UseGraph.js b/DataStructures/Graph/UseGraph.js new file mode 100644 index 0000000..59de5ed --- /dev/null +++ b/DataStructures/Graph/UseGraph.js @@ -0,0 +1,58 @@ +/***** + * + * @function 使用 JavaScript 创建 图数据结构 + * @date 2019-3-25 + * + */ + +const Dictionary = require('../Dictionary/CreateDictionary'); + +function Graph() { + var vertices = []; + var adjList = new Dictionary(); + + // 向图中添加一个新顶点 + this.addVertex = function (v) { + vertices.push(v); + adjList.set(v, []); + } + + // 向图中添加一个边 邻接表的形式 + this.addEdge = function (v, w) { + adjList.get(v).push(w); + adjList.get(w).push(v); + } + + this.toString = function () { + var s = ''; + for (let i = 0; i < vertices.length; i++) { + s += vertices[i] + ' -> '; + var neighbors = adjList.get(vertices[i]); + for (let j = 0; j < neighbors.length; j++) { + s += neighbors[j] + ' '; + } + s += '\n'; + } + return s; + }; +} + +var graph = new Graph(); +var myVertices = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; +for (let index = 0; index < myVertices.length; index++) { + graph.addVertex(myVertices[index]); +} + +graph.addEdge('A', 'B'); +graph.addEdge('A', 'C'); +graph.addEdge('A', 'D'); +graph.addEdge('C', 'D'); +graph.addEdge('C', 'G'); +graph.addEdge('D', 'G'); +graph.addEdge('D', 'H'); +graph.addEdge('B', 'E'); +graph.addEdge('B', 'F'); +graph.addEdge('E', 'I'); + +console.log(graph.toString()); + diff --git a/DataStructures/Tree/BinarySearchTree.js b/DataStructures/Tree/BinarySearchTree.js index d7811c5..a5759ea 100644 --- a/DataStructures/Tree/BinarySearchTree.js +++ b/DataStructures/Tree/BinarySearchTree.js @@ -44,7 +44,20 @@ function BinarySearchTree() { // 在树中查找一个键,存在为 true 不存在为 false this.search = function (key) { + return searchNode(root, key); + } + var searchNode = function (node, key) { + if (node == null) { + return false; + } + if (key < node.key) { + return searchNode(node.left, key); + } else if (key > node.key) { + return searchNode(node.right, key); + } else { + return true; + } } // 通过中序遍历方式遍历所有节点 @@ -99,16 +112,69 @@ function BinarySearchTree() { } return node.key; } + return null; } // 返回树中最大的值(键) this.max = function () { + return maxNode(root); + } + var maxNode = function (node) { + if (node) { + while (node && node.right !== null) { + node = node.right; + } + return node.key; + } + return null; } // 从树中移除某个键 this.remove = function (key) { + root = removeNode(root, key); + } + var removeNode = function(node, key) { + if (node == null) { + return null; + } + if (key < node.key) { + node.left = removeNode(node.left, key); + return node; + } else if (key > node.key){ + node.right = removeNode(node.right, key); + return node; + } else { // 需要删除的键 等于 node 的键 + // 第一种情况--要删除的点是叶子节点 + if (node.left === null && node.right === null) { + node = null; + return node; + } + + // 要移除的节点只有一个子节点 + if (node.left === null) { + node = node.right; + return node; + }else if (node.right === null) { + node = node.right; + return node; + } + + // 要移除的节点 有两个子节点 + var aux = findMinNode(node.right); + node.key = aux.key; + node.right = removeNode(node.right, aux.key); // 将右子树的最小值直接方向当前节点,并且删除右子树中的最小值的那个节点 + return node; + } + } + + // 查找一个BST树中的节点及其子树中的最小节点 + var findMinNode = function (node) { + while (node && node.left !== null) { + node = node.left; + } + return node; } } @@ -138,4 +204,9 @@ console.log('------------------------------------'); tree.preOrderTraverse(printNode); console.log('------------------------------------'); console.log('------------------------------------'); -tree.postOrderTraverse(printNode); \ No newline at end of file +tree.postOrderTraverse(printNode); + +console.log('------------------------------------'); +console.log('------------------------------------'); +console.log(tree.search(1) ? 'Key 1 found.' : 'Key 1 not found'); +console.log(tree.search(8) ? 'Key 8 found.' : 'Key 8 not found'); From 8adcb7c211287aa751998bc50c80650ab3b693a0 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 25 Mar 2019 21:44:57 +0800 Subject: [PATCH 098/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=B9=BF=E5=BA=A6?= =?UTF-8?q?=E4=BC=98=E5=85=88=E9=81=8D=E5=8E=86=E7=9A=84=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Graph/UseGraph.js | 105 ++++++++++++++++++++++++++++ DataStructures/Stack/CreateStack.js | 2 +- 2 files changed, 106 insertions(+), 1 deletion(-) diff --git a/DataStructures/Graph/UseGraph.js b/DataStructures/Graph/UseGraph.js index 59de5ed..006e58b 100644 --- a/DataStructures/Graph/UseGraph.js +++ b/DataStructures/Graph/UseGraph.js @@ -6,6 +6,8 @@ */ const Dictionary = require('../Dictionary/CreateDictionary'); +const Queue = require('../Queue/CreateQueue'); +const Stack = require('../Stack/CreateStack'); function Graph() { var vertices = []; @@ -35,8 +37,82 @@ function Graph() { } return s; }; + + // 初始化 颜色标注矩阵 + var initializeColor = function () { + var color = []; + for (let i = 0; i < vertices.length; i++) { + color[vertices[i]] = 'white'; + } + return color; + }; + + // 广度优先遍历实现过程 + this.bfs = function (v, callback) { + var color = initializeColor(), + queue = new Queue(); + queue.enqueue(v); + + while (!queue.isEmpty()) { + var u = queue.dequeue(), + neighbors = adjList.get(u); + color[u] = 'gray'; // 灰色也可用 grey + for (let i = 0; i < neighbors.length; i++) { + var w = neighbors[i]; + if (color[w] === 'white') { + color[w] = 'gray'; + queue.enqueue(w); + } + } + color[u] = 'black'; + if (callback) { + callback(u); + } + } + } + + // 广度优先遍历改进版本 用于搜索某一顶点到其他节点之间的距离 + this.BFS = function(v) { + var color = initializeColor(), + queue = new Queue(), + d = [], + pred = []; + queue.enqueue(v); + + // 初始化数组 d 与 pred + for (let i = 0; i < vertices.length; i++) { + d[vertices[i]] = 0; + pred[vertices[i]] = null; + } + + while (!queue.isEmpty()) { + var u = queue.dequeue(), + neighbors = adjList.get(u); + color[u] = 'gray'; + for (let i = 0; i < neighbors.length; i++) { + let w = neighbors[i]; + if (color[w] === 'white') { + color[w] = 'gray'; + d[w] = d[u] + 1; + pred[w] = u; + queue.enqueue(w); + } + } + color[u] = 'black'; + } + // 返回了距离数组 和 前溯点数组 + return { + distance: d, + predecessors: pred + }; + } } +function printNode (value) { + console.log('Visited vertex: ' + value); +} + + var graph = new Graph(); var myVertices = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; for (let index = 0; index < myVertices.length; index++) { @@ -55,4 +131,33 @@ graph.addEdge('B', 'F'); graph.addEdge('E', 'I'); console.log(graph.toString()); +console.log('------------------------------------'); +console.log('------------------------------------'); +// 广度优先遍历 +graph.bfs(myVertices[0], printNode); +console.log('------------------------------------'); +console.log('------------------------------------'); + +// 输出图的顶点与其他各点之间的距离,以及各点的前溯点 +var shortestPathA = graph.BFS(myVertices[0]); +console.log(shortestPathA); + +console.log('------------------------------------'); +console.log('------------------------------------'); + +// ! 根据前溯点数组,构建从顶点 A 到 其他顶点的路径 +var fromVertex = myVertices[0]; +for (let i = 1; i < myVertices.length; i++) { + let toVertex = myVertices[i], + path = new Stack(); + for (let v = toVertex; v !== fromVertex; v=shortestPathA.predecessors[v]) { + path.push(v); + } + path.push(fromVertex); + var s = path.pop(); + while (!path.isEmpty()) { + s += ' - ' + path.pop(); + } + console.log(s); +} diff --git a/DataStructures/Stack/CreateStack.js b/DataStructures/Stack/CreateStack.js index a8b9618..0fe721c 100644 --- a/DataStructures/Stack/CreateStack.js +++ b/DataStructures/Stack/CreateStack.js @@ -4,7 +4,7 @@ * @Time 2018-8-20 * @function Create a Stack Structure */ - module.exports = class Stack { +module.exports = class Stack { constructor () { // using a Array items to store Stack Datas From b966f26b01952d5ad7310d7f3e6b53c9d820ce51 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 31 Mar 2019 22:58:10 +0800 Subject: [PATCH 099/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=94=E7=A7=8D?= =?UTF-8?q?=E5=9F=BA=E6=9C=AC=E6=8E=92=E5=BA=8F=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/README.md | 11 +- DataStructures/Sort/ArrayList.js | 224 +++++++++++++++++++++++++++++++ 2 files changed, 233 insertions(+), 2 deletions(-) create mode 100644 DataStructures/Sort/ArrayList.js diff --git a/DataStructures/README.md b/DataStructures/README.md index c1fd73d..7a35d3b 100644 --- a/DataStructures/README.md +++ b/DataStructures/README.md @@ -1,6 +1,7 @@ # DataStructures -This contents includes Stack, Tickets.... +该目录主要是记录 JavaScript 中的数据结构实现方式,包括简单实现以及使用,以及ES6模块化封装的输出.... +主要是书籍 [《学习JavaScript数据结构与算法(第2版)》](http://www.ituring.com.cn/book/2029)的代码实现 ## Stack @@ -20,4 +21,10 @@ Using JavaScript to create the Set Structure ## Dictionary -Using JavaScript to create the Dictionary Structure and HashTable Structure \ No newline at end of file +Using JavaScript to create the Dictionary Structure and HashTable Structure + +## Graph + +Using JavaScript to create the Graph Structure + +## Sort diff --git a/DataStructures/Sort/ArrayList.js b/DataStructures/Sort/ArrayList.js new file mode 100644 index 0000000..613340e --- /dev/null +++ b/DataStructures/Sort/ArrayList.js @@ -0,0 +1,224 @@ +/**** + * + * @function 生成数组结构测试排序和搜索算法 + * + * + */ + +function ArrayList () { + var array = []; + + this.insert = function (item) { + array.push(item); + }; + + this.toString = function (){ + return array.join(); + }; + + var swap = function(array, index1, index2){ + var aux = array[index1]; + array[index1] = array[index2]; + array[index2] = aux; + } + + // 添加冒泡排序 + this.bubbleSort = function () { + var length = array.length; + for (let i = 0; i < length; i++) { + for (let j = 0; j < length-1; j++) { + if (array[j] > array[j+1]) { + swap(array, j, j+1); + } + + } + + } + } + // ! 改进版冒泡排序 + this.modifiedBubbleSort = function () { + var length = array.length; + for (let i = 0; i < length; i++) { + for (let j = 0; j < length-1-i; j++) { + if (array[j] > array[j+1]) { + swap(array, j, j+1); + } + + } + + } + } + + // ! 添加选择排序的代码 + this.selectionSort = function () { + var length = array.length,indexMin; + for (let i = 0; i < length-1; i++) { + indexMin = i; + for (let j = i; j < length; j++) { + if (array[indexMin] > array[j]) { + indexMin = j; + } + if (i !== indexMin) { + swap(array,i,indexMin); + } + } + } + } + + // 添加插入排序算法 + this.insertionSort = function () { + var length = array.length,j,temp; + for (let i = 1; i < length; i++) { + j = i; + temp = array[i]; + while (j>0 && array[j-1] > temp) { + array[j] = array[j-1]; + j--; + } + array[j] = temp; + } + } + + // ! 添加归并排序算法 + // Firefox 使用 归并排序作为 Array.prototype.sort + var merge = function (left, right) { + var result = [], + il = 0, + ir = 0; + + while (il < left.length && ir < right.length) { + if (left[il] < right[ir]) { + result.push(left[il++]); + } else { + result.push(right[ir++]); + } + } + + while (il < left.length) { + result.push(left[il++]); + } + + while (ir < right.length) { + result.push(right[ir++]); + } + + return result; + } + + var mergeSortRec = function (array) { + var length = array.length; + if (length === 1) { + return array; + } + var mid = Math.floor(length / 2), + left = array.slice(0, mid), + right = array.slice(mid, length); + + return merge(mergeSortRec(left), mergeSortRec(right)); + } + + this.mergeSort = function () { + array = mergeSortRec(array); + } + + // 添加快速排序算法 + // Chrome 使用 快速排序作为 Array.prototype.sort + this.quickSort = function () { + quick(array, 0, array.length - 1); + } + + var quick = function (array, left, right) { + var index; + if (array.length > 1) { + index = partition(array, left, right); + + if (left < index - 1) { + quick(array, left, index - 1); + } + + if (index < right) { + quick(array, index, right); + } + } + } + + var partition = function (array, left, right) { + var pivot = array[Math.floor(right + left) , 2], + i = left, + j = right; + + while (i <= j) { + while (array[i] < pivot) { + i++; + } + while (array[j] > pivot) { + j--; + } + if (i <= j) { + swap(array, i, j); + i++; + j--; + } + } + return i; + } + + // 添加堆排序算法 + this.heapSort = function () { + var heapSize = array.length; + buildHeap(array); + + while (heapSize > 1) { + heapSize--; + swap(array, 0, heapSize); + heapify(array, heapSize, 0); + } + } + + var buildHeap = function (array) { + var heapSize = array.length; + for (let i = Math.floor(array.length / 2); i >= 0; i--) { + heapify(array, heapSize, i); + } + } + + var heapify = function (array, heapSize, i) { + var left = i*2 + 1, + right = i*2 + 2; + largest = i; + + if (left < heapSize && array[left] > array[largest]) { + largest = left; + } + + if (right < heapSize && array[right] > array[largest]) { + largest = right; + } + + if (largest !== i) { + swap(array, i, largest); + heapify(array, heapSize, largest); + } + } + + // 计数排序、桶排序、基数排序 + +} + +function createNonSortArray(size) { + var array = new ArrayList(); + for (let i = size; i > 0; i--) { + array.insert(i); + } + return array; +} + +var array = createNonSortArray(8); +console.log(array.toString()); +// array.bubbleSort(); +// array.modifiedBubbleSort(); +// array.selectionSort(); +// array.insertionSort(); +// array.mergeSort(); +array.heapSort(); +console.log(array.toString()); \ No newline at end of file From 34292aaafd4f84616f46cbccb5f0ebb64d8ce91c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 2 Apr 2019 21:27:14 +0800 Subject: [PATCH 100/274] =?UTF-8?q?=E7=99=BE=E5=BA=A6=E5=AE=9E=E4=B9=A0?= =?UTF-8?q?=E7=94=9F=E7=AE=97=E6=B3=95=E6=89=BE=E6=9C=80=E5=B0=8F=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Graph/UseGraph.js | 24 +++++++++++ TestProjects/findminPro.js | 71 ++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 TestProjects/findminPro.js diff --git a/DataStructures/Graph/UseGraph.js b/DataStructures/Graph/UseGraph.js index 006e58b..0a5c1ea 100644 --- a/DataStructures/Graph/UseGraph.js +++ b/DataStructures/Graph/UseGraph.js @@ -106,6 +106,30 @@ function Graph() { predecessors: pred }; } + + // 深度优先遍历搜索过程 + this.dfs = function (callback) { + var color = initializeColor(); + for (let i = 0; i < vertices.length; i++) { + if (color[vertices[i]] === 'white') { + dfsVisit(vertices[i], color, callback); + } + } + } + + // 深度优先遍历访问过程 + this.dfsVisit = function (u, color, callback) { + color[u] = 'gray'; + if (callback) { + callback(u); + } + var neighbors = adjList.get(u); + for (let i = 0; i < neighbors.length; i++) { + var w = neighbors[i]; + + } + } + } function printNode (value) { diff --git a/TestProjects/findminPro.js b/TestProjects/findminPro.js new file mode 100644 index 0000000..b23398b --- /dev/null +++ b/TestProjects/findminPro.js @@ -0,0 +1,71 @@ +/**** + * + * 百度实习生笔试算法题第一题 + * N, P, Q, Array + * 输入包括四个参数 + * + * + */ + +function findMaxNuminArray(array){ + let arrLength = array.length; + let maxId = 0; + for (let i = 0; i < arrLength; i++) { + if (array[i] > array[maxId]) { + maxId = i; + } + } + return maxId; +} + +// 判断是否所有值都为 0 了 +function checkEndArr(array) { + let statArr = true; + if (array[findMaxNuminArray(array)] === 0) { + statArr = false; + } + return statArr; +} + + +function findMinPro(num, projCmpt, restDec, errScore) { + if (errScore.length !== num || errScore.length === 0) { + return null; + } + let proNum = 0; + let maxTemp = findMaxNuminArray(errScore); + let beSub = restDec; + while (checkEndArr(errScore)) { + for (let j = 0; j < errScore.length; j++) { + if (j !== maxTemp) { + beSub = restDec; + }else { + beSub = projCmpt; + } + if (errScore[j] < beSub) { + errScore[j] = 0; + } else { + errScore[j] = errScore[j] - beSub; + } + } + maxTemp = findMaxNuminArray(errScore); + proNum++; + } + + return proNum; +} + + + +var num = 3; +var projCmpt = 2; +var restDec = 1; +var errScore = [4, 3, 2]; +// var num = 4; +// var projCmpt = 3; +// var restDec = 1; +// var errScore = [9, 8, 2, 5]; + +console.log(findMinPro(num, projCmpt, restDec, errScore)); +// 3 +// 5 \ No newline at end of file From 4780fe05950d5840816d235cbdb8a646067a9a28 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Apr 2019 08:37:10 +0800 Subject: [PATCH 101/274] =?UTF-8?q?=E9=80=92=E5=BD=92=E4=B8=8E=E9=9D=9E?= =?UTF-8?q?=E9=80=92=E5=BD=92=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/AlgorithmMode/fibonacci.js | 35 +++++++++++++++++++++++ NowCoder/Leetcode/jumpStep.js | 26 +++++++++++++++-- 2 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 DataStructures/AlgorithmMode/fibonacci.js diff --git a/DataStructures/AlgorithmMode/fibonacci.js b/DataStructures/AlgorithmMode/fibonacci.js new file mode 100644 index 0000000..bbd480e --- /dev/null +++ b/DataStructures/AlgorithmMode/fibonacci.js @@ -0,0 +1,35 @@ +/**** + * + * JavaScript 实现 斐波拉契数列 + * + */ + + +// 递归方式实现 斐波拉契数列 +function fibonacci (num) { + if (num === 1 || num ===2) { + return 1; + } + return fibonacci(num - 1) + fibonacci(num - 2); +} + +// 非递归方式实现斐波拉契数列 +function fib (num) { + var n1 = 1, + n2 = 1, + n = 1; + for (let i = 3; i <= num; i++) { + n = n1 + n2; + n1 = n2; + n2 = n; + } + return n; +} + +// 在其他语言中,递归调用通常比非递归更慢 +// ! ES6 存在尾调用优化,所以递归不会更慢 + +let num = 8; +console.log(fibonacci(num)); +console.log(fib(num)); + diff --git a/NowCoder/Leetcode/jumpStep.js b/NowCoder/Leetcode/jumpStep.js index b1b9753..16bedf4 100644 --- a/NowCoder/Leetcode/jumpStep.js +++ b/NowCoder/Leetcode/jumpStep.js @@ -27,7 +27,29 @@ function jumpFloor(number) { /* * 涉及理论: 递归 * 普通解法: 遍历 - * 改进方向: + * 改进方向:将递归换成非递归 * * - */ \ No newline at end of file + */ + +function jumpF (num) { + if (num <= 0) { + return 0; + }else if (num === 1 || num ===2) { + return num; + }else { + var n1 = 1, + n2 = 2, + n = 1; + for (var i = 3; i <= num; i++) { + n = n1 + n2; + n1 = n2; + n2 = n; + } + return n; + } +} + +var testNum = 10; +console.log(jumpFloor(testNum)); +console.log(jumpF(testNum)); \ No newline at end of file From f69f69b620c47149744e297be515e4dce69d712d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Apr 2019 21:35:56 +0800 Subject: [PATCH 102/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=A7=84=E5=88=92=E5=92=8C=E8=B4=AA=E5=BF=83=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E7=9A=84=E9=83=A8=E5=88=86=E9=A2=98=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AlgorithmMode/dynamicProgramming.js | 31 ++++++ DataStructures/AlgorithmMode/lcs.js | 71 ++++++++++++++ .../AlgorithmMode/littleCoinChange.js | 94 +++++++++++++++++++ .../AlgorithmMode/packageProblem.js | 68 ++++++++++++++ 4 files changed, 264 insertions(+) create mode 100644 DataStructures/AlgorithmMode/dynamicProgramming.js create mode 100644 DataStructures/AlgorithmMode/lcs.js create mode 100644 DataStructures/AlgorithmMode/littleCoinChange.js create mode 100644 DataStructures/AlgorithmMode/packageProblem.js diff --git a/DataStructures/AlgorithmMode/dynamicProgramming.js b/DataStructures/AlgorithmMode/dynamicProgramming.js new file mode 100644 index 0000000..c10a971 --- /dev/null +++ b/DataStructures/AlgorithmMode/dynamicProgramming.js @@ -0,0 +1,31 @@ +/**** + * + * JavaScript 实现动态规划 + * + * ! 分而治之是把问题分解成相互独立的子问题 + * ! 动态规划是把问题分解成相互依赖的子问题 + * + * 经典动态规划问题实例: + * 背包问题 + * 最长公共子序列 + * 矩阵链相乘 + * 硬币找零 + * 图的全源最短路径 + */ + +function mainProblem(){ + var veris; + subProblem(); +} + +// 定义子问题的实现方案 +function subProblem() { + while (checkIfEnd) { + subProblem(); + } +} + +// 识别并求解出边界条件 +function checkIfEnd(){ + +} \ No newline at end of file diff --git a/DataStructures/AlgorithmMode/lcs.js b/DataStructures/AlgorithmMode/lcs.js new file mode 100644 index 0000000..dc8fa08 --- /dev/null +++ b/DataStructures/AlgorithmMode/lcs.js @@ -0,0 +1,71 @@ +/***** + * + * 使用动态规划实现 最长公共子序列(LCS) + * + * + */ + +/** + * 两字符串的最长公共子序列,子序列不要求连续 + * + * @param {*} wordX + * @param {*} wordY + */ +function lcs(wordX, wordY) { + var m = wordX.length; + var n = wordY.length; + var l = []; + var i, j, a, b; + var solution = []; + + for (i = 0; i <= m; ++i) { + l[i] = []; + solution[i]=[]; + for (j = 0; j <= n; ++j) { + l[i][j] = 0; + solution[i][j] = '0'; + } + } + + for (i = 0; i <= m; i++) { + for (j = 0; j <= n; j++) { + if (i === 0 || j === 0) { + l[i][j] = 0; + } else if (wordX[i-1] == wordY[j-1]) { + l[i][j] = l[i-1][j-1] + 1; + solution[i][j] = 'diaginal'; + } else { + a = l[i-1][j]; + b = l[i][j-1]; + l[i][j] = (a>b) ? a:b; + solution[i][j] = (l[i][j] == l[i-1][j]) ? 'top':'left'; + } + } + } + printSolution(solution, l, wordX, wordY, m, n); + return l[m][n]; +} + +function printSolution(solution, l, wordX, wordY, m, n) { + var a=m, b=n, i, j; + var x = solution[a][b]; + var answer = ''; + + while (x !== '0') { + if (solution[a][b] === 'diaginal') { + answer = wordX[a-1] + answer; + a--; + b--; + } else if (solution[a][b] === 'left') { + b--; + } else if (solution[a][b] === 'top') { + a--; + } + x = solution[a][b]; + } + console.log('lcs: '+ answer); +} + +var wordone = 'acbaede'; +var wordtwo = 'abcadf'; +console.log(lcs(wordone, wordtwo)); \ No newline at end of file diff --git a/DataStructures/AlgorithmMode/littleCoinChange.js b/DataStructures/AlgorithmMode/littleCoinChange.js new file mode 100644 index 0000000..1c4f1f0 --- /dev/null +++ b/DataStructures/AlgorithmMode/littleCoinChange.js @@ -0,0 +1,94 @@ +/***** + * 用 JavaScript 实现硬币找零 问题 + * 按照 动态规划的思路 + * + * 问题描述: 给出面额 d1,d2,...,dn 的一定数量的硬币,和要找零的总钱数 + * 找出有多少种找零的方法 + * + */ + + +/** + * 将硬币找零问题变换为最少硬币个数的问题 + * @param {*} coins + * ! 使用动态规划思想解决 + * 找到 n 所需的最小硬币数,先找到对每个 x < n 的解, + * 将 n 的解建立在更小的值的解的基础上 + */ +function MinCoinChange (coins) { + var coins = coins; + var cache = {}; + + // 递归函数实现找零问题 + // ! amount 表示需要找零的总金额 + this.makeChange = function (amount) { + var that = this; + if (!amount) { + return []; + } + + // cache 里存的是已有的解决方案 + if (cache[amount]) { + return cache[amount]; + } + + var min = [], newMin, newAmount; + // 基于硬币的面额解决问题 + for (let i = 0; i < coins.length; i++) { + var coin = coins[i]; + newAmount = amount - coin; + if (newAmount >= 0) { + newMin = that.makeChange(newAmount); + } + + // ! 问题的关键 对每个小于 amount 的数 都计算 makeChange 的结果 + // 判断 newAmount 是否有效, minValue 是否是最优解,minValue 和 newAmount 的值是否合理 + if (newAmount >= 0 && (newMin.length < min.length - 1 || !min.length) && (newMin.length || !newAmount)) { + min = [coin].concat(newMin); + console.log('new Min ' + min + ' for ' + amount); + // console.log(cache); // 辅助理解 + } + } + return (cache[amount] = min); + } + +} + +var coins = [1, 5, 10, 25] +var minCoinChange = new MinCoinChange(coins); +console.log(minCoinChange.makeChange(23)); + + + +/** + * 使用贪心算法解决最少硬币问题 + * + * @param {*} coins + */ +function MinCoinChangeHun(coins){ + var coins = coins; + this.makeChange = function (amount) { + var change = [], + total = 0; + // 从最大的面额开始,其实要保证面额是有序的从小到大 + for (let i = coins.length; i >= 0; i--) { + var coin = coins[i]; + while (total + coin <= amount) { + change.push(coin); + total += coin; + } + } + return change; + } +} + + +var coinsH = [1, 5, 10, 25] +var minCoinChangeH = new MinCoinChangeHun(coins); +console.log(minCoinChangeH.makeChange(23)); + +// 贪心算法并不是总是最优的 +// 如果硬币 是 [1, 3, 4] +// 需要找零的硬币是 6 +// 使用贪心算法 会得到 [4, 1, 1] +// 使用动态规划会得到 [3, 3] \ No newline at end of file diff --git a/DataStructures/AlgorithmMode/packageProblem.js b/DataStructures/AlgorithmMode/packageProblem.js new file mode 100644 index 0000000..81d52e9 --- /dev/null +++ b/DataStructures/AlgorithmMode/packageProblem.js @@ -0,0 +1,68 @@ +/**** + * + * 使用 动态规划的思想 实现 背包问题 + * 背包问题实质是 组合优化问题 + * 问题描述: + * 给定固定大小可携重W的背包,及一组有价值和重量的物品 + * 使总重量不超过W,且总价值最大 + * 物品 重量 价值 + * 1 2 3 + * 2 3 4 + * 3 4 5 + * + * + */ + +/** + * 使用动态规划解决 0-1 版本的背包问题 + * + * @param {*} capacity 允许负重大小 + * @param {*} weights 重量数组 + * @param {*} values 价值数组 + * @param {*} n + */ +function knapSack (capacity, weights, values, n) { + var i, w, a, b, kS = []; + for (let i = 0; i <= n; i++) { + kS[i] = []; + } + + for (let j = 0; j <= n; j++) { + for (let w = 0; w <= capacity; w++) { + if (j == 0 || w == 0) { + kS[j][w] = 0; + } else if (weights[j-1] <= w) { + a = values[j-1] + kS[j-1][w-weights[j-1]]; + b = kS[j-1][w]; // 当找到可以构成解决方案的物品时,选择价值较大的那一个 + kS[j][w] = (a > b) ? a : b; // max(a,b) + } else { + kS[j][w] = kS[j-1][w]; + } + } + } + findValues(n, capacity, kS, weights, values); + return kS[n][capacity]; +} + + +function findValues(n, capacity, kS, weights, values) { + var i = n; + var k = capacity; + console.log('解决方案包含以下物品:'); + + while (i > 0 && k > 0) { + if (kS[i][k] !== kS[i-1][k]) { + console.log('物品'+i+',重量: ' + weights[i-1] + ',价值: '+ values[i-1]); + i--; + k = k - kS[i][k]; + } else { + i--; + } + } +} + +var values = [3, 4, 5]; +var weights = [2, 3, 4]; +var capacity = 7; +var n = values.length; +console.log(knapSack(capacity, weights, values, n)); \ No newline at end of file From bd9bbfb074d617dfaf6e2bf3e73b3cfc1365dad1 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 3 Apr 2019 22:11:06 +0800 Subject: [PATCH 103/274] temp --- Leetcode/addTwonums.js | 76 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Leetcode/addTwonums.js diff --git a/Leetcode/addTwonums.js b/Leetcode/addTwonums.js new file mode 100644 index 0000000..92ef6db --- /dev/null +++ b/Leetcode/addTwonums.js @@ -0,0 +1,76 @@ +/*** +* +* +* +* +***/ +// ! 本质涉及: + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ + +function ListNode(val) { + this.val = val; + this.next = null; +} + + +var addTwoNumbers = function (l1, l2) { + var num1 =0; + var num2 =0; + var i=0,j=0; + while (l1 !== null) { + num1 = num1 + l1.val * Math.pow(10, i); + l1 = l1.next; + i++; + } + while (l2 !== null) { + num2 = num2 + l2.val * Math.pow(10, j); + l2 = l2.next; + j++; + } + var lastnum = num1 + num2; + console.log(lastnum); + console.log(j); + var backlink = new ListNode(lastnum % 10); + for (let x = 1; x <= j; x++) { + var node = new ListNode(lastnum % Math.pow(10, x)); + current = backlink; + while (current.next) { + current = current.next; + } + current.next = node; + console.log(current); + // if(lastnum % Math.pow(10, x) > 10){ + // backlink.val = lastnum % Math.pow(10, x+1); + // } else { + // backlink.val = lastnum % Math.pow(10, x); + // } + // temp.next = backlink; + } + + return backlink; +}; + +// Test Algorithm +// var testNum = 5; +console.log(); +var nodeone = new ListNode(2); +nodeone.next = new ListNode(4); +nodeone.next.next = new ListNode(3); + +var nodetwo = new ListNode(5); +nodetwo.next = new ListNode(6); +nodetwo.next.next = new ListNode(4); + +console.log(addTwoNumbers(nodeone, nodetwo)); \ No newline at end of file From df99aec58674be723df3c93b57ccf898cb32a3b8 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 4 Apr 2019 00:05:53 +0800 Subject: [PATCH 104/274] =?UTF-8?q?=E5=B0=81=E8=A3=85=E4=BA=86=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9A=84=E5=B7=A5=E5=85=B7=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/addTwonums.js | 60 +++++++++++++++++++++++--------------- Leetcode/tools/LinkNode.js | 40 +++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 23 deletions(-) create mode 100644 Leetcode/tools/LinkNode.js diff --git a/Leetcode/addTwonums.js b/Leetcode/addTwonums.js index 92ef6db..cb985d8 100644 --- a/Leetcode/addTwonums.js +++ b/Leetcode/addTwonums.js @@ -19,13 +19,15 @@ * @return {ListNode} */ +const arrayToLinkNode = require('./tools/LinkNode'); + function ListNode(val) { this.val = val; this.next = null; } - -var addTwoNumbers = function (l1, l2) { +// 思路错误,不是先算完求和再转换成链表 +var addTwoNumbersold = function (l1, l2) { var num1 =0; var num2 =0; var i=0,j=0; @@ -40,37 +42,49 @@ var addTwoNumbers = function (l1, l2) { j++; } var lastnum = num1 + num2; - console.log(lastnum); - console.log(j); - var backlink = new ListNode(lastnum % 10); - for (let x = 1; x <= j; x++) { - var node = new ListNode(lastnum % Math.pow(10, x)); - current = backlink; + var strnum = lastnum.toString(); + var arrnum = strnum.split(''); + console.log(arrnum); + arrnum = arrnum.reverse(); + console.log(arrnum); + var arrInt = [],j=0; + + arrnum.map(i=> arrInt[j++] = parseInt(i)); + let linkNode = new ListNode(arrInt[0]); + for (let i = 1; i < arrInt.length; i++) { + let node = new ListNode(arrInt[i]); + let current; + if (linkNode == null){ + linkNode = node; + } else { + current = linkNode; while (current.next) { current = current.next; } current.next = node; - console.log(current); - // if(lastnum % Math.pow(10, x) > 10){ - // backlink.val = lastnum % Math.pow(10, x+1); - // } else { - // backlink.val = lastnum % Math.pow(10, x); - // } - // temp.next = backlink; + } } - return backlink; + return linkNode; }; // Test Algorithm // var testNum = 5; console.log(); -var nodeone = new ListNode(2); -nodeone.next = new ListNode(4); -nodeone.next.next = new ListNode(3); +// var nodeone = arrayToLinkNode([2,4,3]); +// var nodetwo = arrayToLinkNode([5,6,4]); +var nodeone = arrayToLinkNode([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); +var nodetwo = arrayToLinkNode([5,6,4]); + +console.log(addTwoNumbersold(nodeone, nodetwo)); -var nodetwo = new ListNode(5); -nodetwo.next = new ListNode(6); -nodetwo.next.next = new ListNode(4); -console.log(addTwoNumbers(nodeone, nodetwo)); \ No newline at end of file +var addTwoNumbers = function (l1, l2) { + // 定义进位 + var carry = 0; + var p = l1,q=l2; + while (p.next != null || q.next != null) { + + } + +} \ No newline at end of file diff --git a/Leetcode/tools/LinkNode.js b/Leetcode/tools/LinkNode.js new file mode 100644 index 0000000..e542fe5 --- /dev/null +++ b/Leetcode/tools/LinkNode.js @@ -0,0 +1,40 @@ + +/** + * + * 封装将数组转换成链表的方法 + * @param {*} array + * @returns linkNode + */ + +function ListNode(val) { + this.val = val; + this.next = null; +} + +function arrayToLinkNode(array) { + if (array.length <= 0) { + return null; + } + let linkNode = new ListNode(array[0]); + for (let i = 1; i < array.length; i++) { + let node = new ListNode(array[i]); + let current; + if (linkNode == null){ + linkNode = node; + } else { + current = linkNode; + while (current.next) { + current = current.next; + } + current.next = node; + } + } + + + return linkNode; +} + +let arr = [1,2,3,4,5]; +console.log(arrayToLinkNode(arr)); + +module.exports = arrayToLinkNode; \ No newline at end of file From 7a6288ecc1c458fa2042c2aae2521493b613d1d2 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 10 Apr 2019 12:38:14 +0800 Subject: [PATCH 105/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E8=AF=A6=E7=BB=86=E6=8F=8F=E8=BF=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../basic_algorithm/SmallSumbyJavaScript.js | 34 +++++++++---------- Leetcode/tools/LinkNode.js | 2 -- README.md | 18 ++++++++-- 3 files changed, 32 insertions(+), 22 deletions(-) diff --git a/Algorithms/basic_algorithm/SmallSumbyJavaScript.js b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js index 03ef4e3..bc96c38 100644 --- a/Algorithms/basic_algorithm/SmallSumbyJavaScript.js +++ b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js @@ -7,22 +7,22 @@ */ - function smallSum(arrays) { - if (arrays == null || arrays.length < 2) { - return 0; - } +function smallSum(arrays) { +if (arrays == null || arrays.length < 2) { + return 0; +} return camergeSort(arrays, 0, arrays.length -1); - } +} - function camergeSort(arrays, ln, rn) { - if (ln == rn) { - return 0; - } - let midn = ln + ((rn - ln) >> 1); - return camergeSort(arrays, ln, midn) + camergeSort(arrays, midn + 1, rn) + caMerge(arrays, ln, midn, rn); - } +function camergeSort(arrays, ln, rn) { + if (ln == rn) { + return 0; + } + let midn = ln + ((rn - ln) >> 1); + return camergeSort(arrays, ln, midn) + camergeSort(arrays, midn + 1, rn) + caMerge(arrays, ln, midn, rn); +} - function caMerge(arrays, ln, midn, rn){ +function caMerge(arrays, ln, midn, rn){ let temparrays = new Array(); let ti = 0; let pone = ln; @@ -46,9 +46,9 @@ arrays[ln + index] = temparrays[index]; } return resultsum; - } +} - let testArrays = [1, 3, 4, 2, 5]; - console.log('this array is: '+ testArrays); - console.log('the small sum of this array is: ' + smallSum(testArrays)); \ No newline at end of file +let testArrays = [1, 3, 4, 2, 5]; +console.log('this array is: '+ testArrays); +console.log('the small sum of this array is: ' + smallSum(testArrays)); \ No newline at end of file diff --git a/Leetcode/tools/LinkNode.js b/Leetcode/tools/LinkNode.js index e542fe5..dda1015 100644 --- a/Leetcode/tools/LinkNode.js +++ b/Leetcode/tools/LinkNode.js @@ -29,8 +29,6 @@ function arrayToLinkNode(array) { current.next = node; } } - - return linkNode; } diff --git a/README.md b/README.md index 76c7931..b8148f1 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,34 @@ # Algorithm Prictice +此项目是学习 数据结构与算法 过程中的练习笔记以及一些算法题的解决方案,主要实现语言是 JavaScript,有部分代码也有 Java 实现,以及少量的 Python This project was originally set up to practice the algorithms on the OJ platform, and then summarized some understanding and connection about algorithms. ## Data Structures +数据结构部分,主要使用 JavaScript 实现并封装了 常用的数据结构,包括但不限于: +- [链表](./DataStructures/LinkedList/) +- [队列](./DataStructures/Queue/) +- [集合](./DataStructures/Set/) +- [栈](./DataStructures/Stack/) +- [字典](./DataStructures/Dictionary/) +- [树](./DataStructures/Tree/) +- [常用排序算法](./DataStructures/Sort/) +- [算法模式](./DataStructures/AlgorithmMode/) Using JavaScript to create those data structures. DataStructures\Dictionary -## Disk Scheduling Algorithm +## Algorithms +此项目还包括一些基础算法的实现思路记录,以及计算机原理里面的磁盘调度算法,群智能优化算法等等 Carrying out disk scheduling algorithm by Java. ## LeetCode -NowCoder\Leetcode -## HuaWeiOJ Algorithms +`LeetCode` 与 `NowCoder\Leetcode` 目录中都是 LeetCode 算法题的实现 +## HuaWeiOJ Algorithms +很久以前华为OJ平台的一些算法题实现 Some algorithms solved by Python2.7 from HuaWeiOJ Projects From 64a74552fe72cf76089c4a3bbfb2917ea72439d4 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 10 Apr 2019 22:06:38 +0800 Subject: [PATCH 106/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E6=A1=B6=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=E7=9A=84=E6=80=9D=E6=83=B3=E8=A7=A3=E5=86=B3=E5=AE=9E?= =?UTF-8?q?=E9=99=85=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJava/MaxGap.java | 46 ++++++++++ .../SortAlgorithmsbyJavaScript/MaxGap.js | 46 ++++++++++ TestProjects/Comparator/Comparator.js | 83 +++++++++++++++++++ 3 files changed, 175 insertions(+) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJava/MaxGap.java create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MaxGap.js create mode 100644 TestProjects/Comparator/Comparator.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/MaxGap.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/MaxGap.java new file mode 100644 index 0000000..044f369 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/MaxGap.java @@ -0,0 +1,46 @@ +// package basic_algorithm; + +public class MaxGap { + + // 使用桶排序的思想,求一个数组排序后相邻两数之差的最大值 + public static int maxGap(int[] nums) { + if(nums == null || nums.length < 2){ + return 0; + } + int len = nums.length; + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + for (int i = 0; i < len; i++){ + min = Math.min(min, nums[i]); + max = Math.max(max, nums[i]); + } + if (min == max){ + return 0; + } + boolean[] hasNum = new boolean[len + 1]; + int[] maxs = new int[len + 1]; + int[] mins = new int[len + 1]; + int bid = 0; + for (int j = 0; j < len; j++) { + bid = bucket(nums[j], len, min, max); // 确定当前数它属于几号桶 + mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[j]) : nums[j]; + maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[j]) : nums[j]; + hasNum[bid] = true; + } + int res = 0; + int lastMax = maxs[0]; + int count = 1; + for (;count <= len; count++) { + if (hasNum[count]) { + // 找全局最大差值 + res = Math.max(res, mins[count] - lastMax); + lastMax = maxs[count]; + } + } + return res; + } + + public static int bucket(long num, long len, long min, long max) { + return (int) ((num - min) * len / (max - min)); + } +} \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MaxGap.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MaxGap.js new file mode 100644 index 0000000..2f62da8 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MaxGap.js @@ -0,0 +1,46 @@ +/**** + * + * 使用桶排序的思想找出一个数组排序后,相邻两数差值的最大值 + * + */ + +function findMaxGap(nums){ + if (nums === null || nums.length < 2) { + return 0; + } + var len = nums.length; + var min = Number.MAX_VALUE; + var max = Number.MIN_VALUE; + for (let i = 0; i < len; i++) { + min = Math.min(min, nums[i]); + max = Math.max(max, nums[i]); + } + if (min === max) { + return 0; + } + var hasNum = []; + var maxs = []; + var mins = []; + var bid = 0; + for (let j = 0; j < len; j++) { + bid = parseInt((nums[j] - min) * len / (max - min)); // 确定这个数放在哪个桶里面 + mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[j]) : nums[j]; + maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[j]) : nums[j]; + hasNum[bid] = true; + } + var res = 0; + var lastMax = maxs[0]; + var count = 1; + for (; count <= len; count++) { + if (hasNum[count]) { + // 对每一个 非空桶都要判断 它的最小值与前一个非空桶的最大值之间的差值,找到全局最大值 + res = Math.max(res, mins[count] - lastMax); + lastMax = maxs[count]; + } + } + return res; +} + + +var testarr = [1,3,6,15,27,32]; +console.log(findMaxGap(testarr)); \ No newline at end of file diff --git a/TestProjects/Comparator/Comparator.js b/TestProjects/Comparator/Comparator.js new file mode 100644 index 0000000..55efbcd --- /dev/null +++ b/TestProjects/Comparator/Comparator.js @@ -0,0 +1,83 @@ +/**** + * + * 使用比较器 + * + */ + +function Student(name, grade, age) { + this.name = name; + this.grade = grade; + this.age = age; +} + +// 自定义的比较器 + +function compare(obj1, obj2){ + // 返回负数 认为第一个参数放在前面 + // 返回正数 认为第二个参数放在前面 + // 返回零,认为两者相等 + + // 按照grade从小到大排列 + // if (obj1.grade < obj2.grade) { + // return -1; + // } else if (obj2.grade < obj1.grade) { + // return 1; + // } else { + // return 0; + // } + + return obj1.grade - obj2.grade; + // 如果 obj1 的 grade 更小, 减完后就是负的 + // 如果 obj2 的 grade 更小,减完后就是正的 +} + +// 按照 name 字段降序排列的比较器 +function compare_name (obj1, obj2){ + return obj1.name > obj2.name; + // ! 对于字符串 要比较大小 +} + +// 按照 age 字段降序排列的比较器 +function compare_age (obj1, obj2){ + return obj1.age - obj2.age; +} + + +// 自定义的打印方法 +function printStudent(oldarr){ + for (let i = 0; i < oldarr.length; i++) { + var temp = oldarr[i]; + var thisstr = ""; + for (var one in temp) { + thisstr = thisstr + one + " : " + temp[one] + " "; + } + console.log(thisstr); + + } +} + +var student1 = new Student("A", 3, 23); +var student2 = new Student("B", 2, 21); +var student3 = new Student("C", 1, 22); + +var students = [student1, student2, student3]; +console.log("--------------init array--------------"); +printStudent(students); + +console.log("-------------按 grade 属性排序---------------"); + +// 传递比较器进入系统的方法 +students.sort(compare); +printStudent(students); + +console.log("-------------按 age 属性排序---------------"); + +// 传递比较器进入系统的方法 +students.sort(compare_age); +printStudent(students); + +console.log("-------------按 name 属性排序---------------"); + +// 传递比较器进入系统的方法 +students.sort(compare_name); +printStudent(students); From ae42286b40dcd4da4e49946c789e0c616c984dc3 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 16 Apr 2019 09:28:32 +0800 Subject: [PATCH 107/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E5=9F=BA=E7=A1=80=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../basic_algorithm/SmallSumbyJavaScript.js | 1 + .../SortAlgorithmsbyJavaScript/ArrayStack.js | 32 +++++++++++++++++ DataStructures/Heap/CreateHeap.js | 17 +++++++++ TestProjects/Tools/random.js | 35 +++++++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/ArrayStack.js create mode 100644 DataStructures/Heap/CreateHeap.js create mode 100644 TestProjects/Tools/random.js diff --git a/Algorithms/basic_algorithm/SmallSumbyJavaScript.js b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js index bc96c38..25ec57d 100644 --- a/Algorithms/basic_algorithm/SmallSumbyJavaScript.js +++ b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js @@ -3,6 +3,7 @@ * @author SkylineBin * @time 2018-10-6 * @function use mergesort to caculate small sum of one array + * 使用归并排序去计算一个数组中的最小值 * */ diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/ArrayStack.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/ArrayStack.js new file mode 100644 index 0000000..f2cd775 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/ArrayStack.js @@ -0,0 +1,32 @@ +/**** + * + * 用数组实现栈结构 + * + */ + +var ArrayStack = function (initsize){ + var arr = []; + var size = 0; + var init = initsize; + + this.peek = function () { + if (size === 0) { + return null; + } + return arr[size - 1]; + } + + this.push = function (obj) { + if (size === init) { + throw new ErrorEvent("this stack is full"); + } + arr[size++] = obj; + } + + this.pop = function () { + if (size === 0) { + throw new ErrorEvent("this stack is empty"); + } + return arr[--size]; + } +} \ No newline at end of file diff --git a/DataStructures/Heap/CreateHeap.js b/DataStructures/Heap/CreateHeap.js new file mode 100644 index 0000000..ec57cc3 --- /dev/null +++ b/DataStructures/Heap/CreateHeap.js @@ -0,0 +1,17 @@ +/** + * @author SkylineBin + * @Time 2019-4-10 + * @function Create a Heap Structure + */ + +module.exports = class Heap { + constructor() { + // using a Array items to store Heap Datas + this.items = []; + } + + poll () { + return this.items[this.items.length - 1]; + } + +} \ No newline at end of file diff --git a/TestProjects/Tools/random.js b/TestProjects/Tools/random.js new file mode 100644 index 0000000..4081a25 --- /dev/null +++ b/TestProjects/Tools/random.js @@ -0,0 +1,35 @@ +/**** + * + * 常用的随机函数生成器 + * + * + */ + +/** + * 返回一个 0~maxNum 之间的整数 + * @param {*} maxNum + */ +function backInMax(maxNum) { + return Math.floor(Math.random() * Math.floor(maxNum)); +} + + +/** + * 生成指定长度和取值范围的数组 + * @param {*} size + * @param {*} value + */ +function generateRandomArray(size, value) { + let randomArrays = []; + // 生成长度随机的数组 + let arrayLength = parseInt((size + 1) * Math.random()); + for (let index = 0; index < arrayLength; index++) { + randomArrays[index] = parseInt((value + 1) * Math.random()) - parseInt(value * Math.random()); + } + + if (randomArrays.length === 0) { + arrayLength = generateRandomArray(size, value); + } + + return randomArrays; +} \ No newline at end of file From 0ad1eb386366d3c1d7d1a50d1872ad3432a59f7a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 16 Apr 2019 09:29:09 +0800 Subject: [PATCH 108/274] =?UTF-8?q?=E4=BB=85=E4=BD=BF=E7=94=A8=E4=BD=8D?= =?UTF-8?q?=E8=BF=90=E7=AE=97=E5=AE=9E=E7=8E=B0=E4=B8=A4=E4=B8=AA=E6=95=B4?= =?UTF-8?q?=E6=95=B0=E7=9B=B8=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/addTwoNum.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 NowCoder/Leetcode/addTwoNum.js diff --git a/NowCoder/Leetcode/addTwoNum.js b/NowCoder/Leetcode/addTwoNum.js new file mode 100644 index 0000000..64d245a --- /dev/null +++ b/NowCoder/Leetcode/addTwoNum.js @@ -0,0 +1,20 @@ +/**** + * + * 不使用四则运算符实现两个整数相加 + * + * + */ + +function Add(num1, num2) { + + while (num2 !== 0){ + var temp = num1 ^ num2; + num2 = (num1 & num2) << 1; + num1 = temp; + } + return num1; +} + +var num1 = 3; +var num2 = 13; +console.log(Add(num1, num2)); \ No newline at end of file From 0bae032aafcee46ee9be4fee0d8b69f7eaea41f6 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 17 Apr 2019 20:48:44 +0800 Subject: [PATCH 109/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=B1=82=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E6=B7=B1=E5=BA=A6=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/treeDepth.js | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 NowCoder/Leetcode/treeDepth.js diff --git a/NowCoder/Leetcode/treeDepth.js b/NowCoder/Leetcode/treeDepth.js new file mode 100644 index 0000000..756badd --- /dev/null +++ b/NowCoder/Leetcode/treeDepth.js @@ -0,0 +1,49 @@ +/**** + * + * 已知一个二叉树,求二叉树的深度 + * 输入一棵二叉树, 求该树的深度。 从根结点到叶结点依次经过的结点( 含根、 叶结点) 形成树的一条路径, 最长路径的长度为树的深度。 + * + */ + + +// 递归解法 + +/* function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} */ +function TreeDepth(pRoot) { + // write code here + if (pRoot !== null) { + return Math.max(TreeDepth(pRoot.left), TreeDepth(pRoot.right))+1; + } else { + return 0; + } +} + +// 非递归解法 +// 层次遍历法 + +function TreeDepth(pRoot) { + if (pRoot === null) { + return 0; + } + let treearr = []; + treearr.push(pRoot); + let depth = 0; + while(treearr.length !== 0) { + depth++; + for (let i = 0; i < treearr.length; i++) { + let tempNode = treearr[0]; + treearr = treearr.slice(1); + if (tempNode.left !== null) { + treearr.push(tempNode.left); + } + if (tempNode.right !== null) { + treearr.push(tempNode.right); + } + } + } + return depth; +} \ No newline at end of file From 21ea684b27bf7066e85a0bb3ee40b4470621bd37 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 17 Apr 2019 20:49:31 +0800 Subject: [PATCH 110/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E6=88=90=E5=B9=B3=E8=A1=A1=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=96=B9=E6=B3=95=E5=BA=93=E4=BB=A5=E5=8F=8A?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=A8=8B=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 50 ++++++++++++++++++++++++++++++++++++++ Leetcode/tools/LinkNode.js | 4 +-- Leetcode/tools/treeNode.js | 32 ++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 Leetcode/testAlg.js create mode 100644 Leetcode/tools/treeNode.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js new file mode 100644 index 0000000..9858898 --- /dev/null +++ b/Leetcode/testAlg.js @@ -0,0 +1,50 @@ +/**** + * + * 此方法用于函数测试 + * + * + */ + +const arrayToTreeNode = require('./tools/treeNode'); + +function TreeDepth(pRoot) { + // write code here + if (pRoot !== null) { + return Math.max(TreeDepth(pRoot.left), TreeDepth(pRoot.right)) + 1; + } else { + return 0; + } +} + +// 非递归解法 +// 层次遍历法 + +function treeDep(pRoot) { + if (pRoot === null) { + return 0; + } + var treearr = []; + treearr.push(pRoot); + var count = 0; + while (treearr.length !== 0) { + count++; + for (let i = 0; i < treearr.length; i++) { + var temp = treearr[0]; + treearr = treearr.slice(1); + if (temp.left !== null) { + treearr.push(temp.left); + } + if (temp.right !== null) { + treearr.push(temp.right); + } + } + } + return count; +} + +let arr = [1, 2, 3, 4, 5]; + +var tempTree = arrayToTreeNode(arr); + +console.log('递归版本深度:', TreeDepth(tempTree)); +console.log('非递归版本深度:', treeDep(tempTree)); \ No newline at end of file diff --git a/Leetcode/tools/LinkNode.js b/Leetcode/tools/LinkNode.js index dda1015..997b08f 100644 --- a/Leetcode/tools/LinkNode.js +++ b/Leetcode/tools/LinkNode.js @@ -32,7 +32,7 @@ function arrayToLinkNode(array) { return linkNode; } -let arr = [1,2,3,4,5]; -console.log(arrayToLinkNode(arr)); +// let arr = [1,2,3,4,5]; +// console.log(arrayToLinkNode(arr)); module.exports = arrayToLinkNode; \ No newline at end of file diff --git a/Leetcode/tools/treeNode.js b/Leetcode/tools/treeNode.js new file mode 100644 index 0000000..39c11a0 --- /dev/null +++ b/Leetcode/tools/treeNode.js @@ -0,0 +1,32 @@ +/***** + * + * 封装将 数组转换成成二叉树的方法(平衡二叉树) + * + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +function arraytoTreeNode(array){ + if (array.length <= 0) { + return null; + } + if (array.length === 1) { + return new TreeNode(array[0]); + } + + var mid = parseInt(array.length / 2); + var node = new TreeNode(array[mid]); + node.left = arraytoTreeNode(array.slice(0, mid)); + node.right = arraytoTreeNode(array.slice(mid+1)); + return node; +} + +// let arr = [1, 2, 3, 4, 5]; +// console.log(arraytoTreeNode(arr)); + +module.exports = arraytoTreeNode; \ No newline at end of file From 9f7ec566275a111b3ff6c16201ef49615e703b9f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 17 Apr 2019 21:55:34 +0800 Subject: [PATCH 111/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E6=98=AF=E5=B9=B3=E8=A1=A1=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 85 +++++++++++++++++++---------- NowCoder/Leetcode/isBalancedTree.js | 39 +++++++++++++ NowCoder/Leetcode/treeDepth.js | 5 +- 3 files changed, 97 insertions(+), 32 deletions(-) create mode 100644 NowCoder/Leetcode/isBalancedTree.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 9858898..79ac04d 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -7,44 +7,69 @@ const arrayToTreeNode = require('./tools/treeNode'); -function TreeDepth(pRoot) { - // write code here - if (pRoot !== null) { - return Math.max(TreeDepth(pRoot.left), TreeDepth(pRoot.right)) + 1; - } else { - return 0; - } -} +// function TreeDepth(pRoot) { +// // write code here +// if (pRoot !== null) { +// return Math.max(TreeDepth(pRoot.left), TreeDepth(pRoot.right)) + 1; +// } else { +// return 0; +// } +// } -// 非递归解法 -// 层次遍历法 +// // 非递归解法 +// // 层次遍历法 -function treeDep(pRoot) { +// function treeDep(pRoot) { +// if (pRoot === null) { +// return 0; +// } +// var treearr = []; +// treearr.push(pRoot); +// var count = 0; +// while (treearr.length !== 0) { +// count++; +// let thisLen = treearr.length; +// for (let i = 0; i < thisLen; i++) { +// var temp = treearr[0]; +// treearr = treearr.slice(1); +// if (temp.left !== null) { +// treearr.push(temp.left); +// } +// if (temp.right !== null) { +// treearr.push(temp.right); +// } +// } +// } +// return count; +// } + +function IsBalanced_Solution(pRoot) { + // write code here if (pRoot === null) { - return 0; + return true; } - var treearr = []; - treearr.push(pRoot); - var count = 0; - while (treearr.length !== 0) { - count++; - for (let i = 0; i < treearr.length; i++) { - var temp = treearr[0]; - treearr = treearr.slice(1); - if (temp.left !== null) { - treearr.push(temp.left); - } - if (temp.right !== null) { - treearr.push(temp.right); - } + + this.getDepth = function (rootNode) { + if (rootNode === null) { + return 0; + } + let left = this.getDepth(rootNode.left); + if (left === -1) { + return -1; } + let right = this.getDepth(rootNode.right); + if (right === -1) { + return -1; + } + return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1; } - return count; + + return this.getDepth(pRoot) !== -1; } -let arr = [1, 2, 3, 4, 5]; +let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var tempTree = arrayToTreeNode(arr); -console.log('递归版本深度:', TreeDepth(tempTree)); -console.log('非递归版本深度:', treeDep(tempTree)); \ No newline at end of file +console.log('递归版本是否平衡二叉树:', IsBalanced_Solution(tempTree)); +// console.log('非递归版本深度:', treeDep(tempTree)); \ No newline at end of file diff --git a/NowCoder/Leetcode/isBalancedTree.js b/NowCoder/Leetcode/isBalancedTree.js new file mode 100644 index 0000000..3f7ba03 --- /dev/null +++ b/NowCoder/Leetcode/isBalancedTree.js @@ -0,0 +1,39 @@ +/**** + * + * 判断一个树是否是平衡二叉树 + * 输入一棵二叉树, 判断该二叉树是否是平衡二叉树。 + * + */ + + +/* function TreeNode(x) { +this.val = x; +this.left = null; +this.right = null; +} */ +function IsBalanced_Solution(pRoot) { + // write code here + if (pRoot === null) { + return true; + } + + // 获取深度的子函数,获取深度的过程中对同一个子节点进行判断 + // 如果有一个子节点左右节点深度不一样都会返回 -1 + this.getDepth = function (rootNode){ + if (rootNode === null) { + return 0; + } + // 只要有一个等于 -1 ,整个树就不是平衡二叉树 + let left = this.getDepth(rootNode.left); + if (left === -1) { + return -1; + } + let right = this.getDepth(rootNode.right); + if (right === -1) { + return -1; + } + return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1; + } + + return this.getDepth(pRoot) !== -1; +} \ No newline at end of file diff --git a/NowCoder/Leetcode/treeDepth.js b/NowCoder/Leetcode/treeDepth.js index 756badd..497285c 100644 --- a/NowCoder/Leetcode/treeDepth.js +++ b/NowCoder/Leetcode/treeDepth.js @@ -34,9 +34,10 @@ function TreeDepth(pRoot) { let depth = 0; while(treearr.length !== 0) { depth++; - for (let i = 0; i < treearr.length; i++) { + let tempLen = treearr.length; // 这一层是两个结点还是有一个结点 + for (let i = 0; i < tempLen; i++) { let tempNode = treearr[0]; - treearr = treearr.slice(1); + treearr = treearr.slice(1); // 以上两步实现的是队列的 pop 操作 if (tempNode.left !== null) { treearr.push(tempNode.left); } From a187df143a44ee69aff0dc1ab0a1fe8b03cf038a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 17 Apr 2019 21:56:06 +0800 Subject: [PATCH 112/274] =?UTF-8?q?=E6=89=BE=E5=87=BA=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E4=B8=AD=E5=8F=AA=E5=87=BA=E7=8E=B0=E4=B8=80=E6=AC=A1=E7=9A=84?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/findNumsAppearOnce.js | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 NowCoder/Leetcode/findNumsAppearOnce.js diff --git a/NowCoder/Leetcode/findNumsAppearOnce.js b/NowCoder/Leetcode/findNumsAppearOnce.js new file mode 100644 index 0000000..ba8c927 --- /dev/null +++ b/NowCoder/Leetcode/findNumsAppearOnce.js @@ -0,0 +1,30 @@ +/**** + * + * + * 一个整型数组里除了两个数字之外, 其他的数字都出现了两次。 请写程序找出这两个只出现一次的数字。 + * + * + */ + +function FindNumsAppearOnce(array) { + let nums = []; + for (let i = 0; i < array.length; i++) { + if (nums[array[i]]) { + nums[array[i]]++; + }else { + nums[array[i]] = 1; + } + } + + let list = []; + for (let index in nums) { + if (nums[index] === 1) { + list.push(parseInt(index)); + } + } + return list; +} + +let arr = [1,1,2,4,4,5,6,6,7,7,8,8]; + +console.log(FindNumsAppearOnce(arr)); \ No newline at end of file From 4c45016c2c051a09541a645b9c86ddc424b40d42 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Apr 2019 21:26:41 +0800 Subject: [PATCH 113/274] =?UTF-8?q?=E6=89=BE=E5=87=BA=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E4=B8=AD=E9=87=8D=E5=A4=8D=E7=9A=84=E6=95=B0=E7=9A=84=E4=B8=A4?= =?UTF-8?q?=E7=A7=8D=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/duplicate.js | 64 ++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 NowCoder/Leetcode/duplicate.js diff --git a/NowCoder/Leetcode/duplicate.js b/NowCoder/Leetcode/duplicate.js new file mode 100644 index 0000000..e1dc32d --- /dev/null +++ b/NowCoder/Leetcode/duplicate.js @@ -0,0 +1,64 @@ +/****** + * + * 找数组中重复的数字 + * + * 在一个长度为n的数组里的所有数字都在0到n - 1 的范围内。 + * 数组中某些数字是重复的, 但不知道有几个数字是重复的。 也不知道每个数字重复几次。 + * 请找出数组中任意一个重复的数字。 + * 例如, 如果输入长度为7的数组 {2, 3, 1, 0, 2, 5, 3 },那么对应的输出是第一个重复的数字 2。 + * + * + */ + +function duplicate(numbers, duplication) { + // write code here + //这里要特别注意~找到任意重复的一个值并赋值到duplication[0] + //函数返回True/False + var len = numbers.length; + var temparr = []; + for (let i = 0; i < len; i++) { + if(temparr[numbers[i]]) { + temparr[numbers[i]]++; + } else { + temparr[numbers[i]] = 1; + } + } + + for (var index in temparr) { + if (temparr[index] !== 1) { + duplication[0] = parseInt(index); + return 'true'; + } + } + return 'false'; +} + +// 11ms 占用 5356k + + +// var arr = [2, 3, 1, 0, 2, 5, 3]; +var arr = [2, 1, 3, 1, 4]; +console.log(duplicate(arr)); + +// 以上过程较为复杂,可以简化 +function duplicateOnce(numbers, duplication) { + // write code here + //这里要特别注意~找到任意重复的一个值并赋值到duplication[0] + //函数返回True/False + var temparr = []; + for (let i = 0; i < numbers.length; i++) { + if (temparr[numbers[i]]) { + temparr[numbers[i]]++; + if (temparr[numbers[i]] === 2) { + duplication[0] = numbers[i]; + return true; + } + } else { + temparr[numbers[i]] = 1; + } + } + return 'false'; +} + +// 运行时间: 15 ms +// 占用内存: 7572 k \ No newline at end of file From b3198e1064c9725288ebef576a0093260b373f59 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Apr 2019 21:27:17 +0800 Subject: [PATCH 114/274] =?UTF-8?q?=E4=B8=A4=E6=95=B0=E7=BB=84=E7=9A=84?= =?UTF-8?q?=E4=B9=98=E6=B3=95=E6=9E=84=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/multiply.js | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 NowCoder/Leetcode/multiply.js diff --git a/NowCoder/Leetcode/multiply.js b/NowCoder/Leetcode/multiply.js new file mode 100644 index 0000000..4dd8b04 --- /dev/null +++ b/NowCoder/Leetcode/multiply.js @@ -0,0 +1,62 @@ +/**** + * + * + * 给定一个数组A[0, 1, ..., n - 1], 请构建一个数组B[0, 1, ..., n - 1], + * 其中B中的元素B[i] = A[0] * A[1] * ... * A[i - 1] * A[i + 1] * ... * A[n - 1]。 + * 不能使用除法。 + * + */ + +// 解题思路:要先初始化,只有不等的时候才乘 + + +function multiply(array) { + // write code here + if (array === null) { + return null; + } + var arrayB = []; + for (let i = 0; i < array.length; i++) { + arrayB[i] = 1; + for (let j = 0; j < array.length; j++) { + if (i !== j) { + arrayB[i] = arrayB[i] * array[j]; + } + } + } + return arrayB; +} + + +// 运行时间: 16 ms +// 占用内存: 5320 k + +// test +var arr = [1,2,3]; +console.log(multiply(arr)); + + +// ! 算法复杂度更低的解法 +// 分析:可以看作 n*n 的矩阵,对角全是 1, B[i] 是每一行 相乘的结果,矩阵每一行都是 A[0]...A[n-1] +// 先计算下三角部分的值,再倒过来计算上三角的值 + + +function multiply2(array) { + + let arrayB = []; + arrayB[0] = 1; + // 计算下三角的值 + for (let i = 1; i < array.length; i++) { + arrayB[i] = arrayB[i-1] * array[i-1]; + } + let temp = 1; + // 倒过来乘一遍计算上三角的值 + for (let j = array.length - 2; j >=0; j--) { + temp *= array[j+1]; + arrayB[j] *= temp; + } + return arrayB; +} + +var arr2 = [1, 2, 3]; +console.log(multiply2(arr2)); \ No newline at end of file From 20e933df2b0e826cd67d08ce75ab1f59e275c874 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Apr 2019 21:28:07 +0800 Subject: [PATCH 115/274] =?UTF-8?q?=E6=AD=A3=E5=88=99=E8=A1=A8=E8=BE=BE?= =?UTF-8?q?=E5=BC=8F=E7=9A=84=E5=8C=B9=E9=85=8D=E9=A2=98=EF=BC=8C=E9=80=9A?= =?UTF-8?q?=E8=BF=87=E7=8E=87=2097%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/matchParren.js | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 NowCoder/Leetcode/matchParren.js diff --git a/NowCoder/Leetcode/matchParren.js b/NowCoder/Leetcode/matchParren.js new file mode 100644 index 0000000..e70e487 --- /dev/null +++ b/NowCoder/Leetcode/matchParren.js @@ -0,0 +1,54 @@ +/******* + * + * 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 + * 在本题中,匹配是指字符串的所有字符匹配整个模式。 + * 例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配, + * 但是与"aa.a"和"ab*a"均不匹配 + * + * + * + */ + +function match(s, pattern) { + // write code here + s === undefined ? '': s; + pattern === undefined ? '' : pattern; + if (s === '' && pattern === '') { + return true; + } + if (s !== '' && pattern === '') { + return false; + } + if (s === '' && pattern === '.') { + return false; + } + var i = 0; + // 当 pattern 的下一个字符不是 *,则字符次序不会变化 + pattern[i + 1] === undefined ? '' : pattern[i + 1]; + if (pattern[i+1] !== '*') { + if (s[i] === pattern[i] || ( s[i] !== '' && pattern[i] === '.')) { + return match(s.slice(1), pattern.slice(1)); + } else { + return false; + } + } else { + // 当 pattern 的下一个字符是 * + if (s[i] === pattern[i] || (s[i] !== '' && pattern[i] === '.')) { // 都表示当前的这个字符是相同的 + if (pattern[i] === '.') { + return match(String(s[s.length - 1]), String(pattern[pattern.length - 1])); + } + return match(s, pattern.slice(2)) || match(s.slice(1), pattern); + } else { + // 当前字符不相同,下一个是*,*前面的字符可能出现 0 次 + return match(s, pattern.slice(2)); + } + } +} + +// "bcbbabab",".*a*a" +// var arr1 = 'a'; +// var arr2 = '.'; +var arr1 = 'bcbbabab'; +console.log(arr1[-1]); +var arr2 = '.*a*a'; +console.log(match(arr1, arr2)); \ No newline at end of file From 41ac171c52513d63ea42b79d000d2f08cb8d5f25 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Apr 2019 21:55:39 +0800 Subject: [PATCH 116/274] =?UTF-8?q?1-n=20=E5=87=BA=E7=8E=B01=E7=9A=84?= =?UTF-8?q?=E4=B8=AA=E6=95=B0=EF=BC=8C=E6=9A=B4=E5=8A=9B=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/matchParren.js | 4 +- .../numberOf1Between1AndN_Solution.js | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 NowCoder/Leetcode/numberOf1Between1AndN_Solution.js diff --git a/NowCoder/Leetcode/matchParren.js b/NowCoder/Leetcode/matchParren.js index e70e487..6414918 100644 --- a/NowCoder/Leetcode/matchParren.js +++ b/NowCoder/Leetcode/matchParren.js @@ -45,10 +45,12 @@ function match(s, pattern) { } } +// 上述代码未通过 + + // "bcbbabab",".*a*a" // var arr1 = 'a'; // var arr2 = '.'; var arr1 = 'bcbbabab'; -console.log(arr1[-1]); var arr2 = '.*a*a'; console.log(match(arr1, arr2)); \ No newline at end of file diff --git a/NowCoder/Leetcode/numberOf1Between1AndN_Solution.js b/NowCoder/Leetcode/numberOf1Between1AndN_Solution.js new file mode 100644 index 0000000..881f437 --- /dev/null +++ b/NowCoder/Leetcode/numberOf1Between1AndN_Solution.js @@ -0,0 +1,39 @@ +/**** + * + * 求 1~n 直接 出现 1 的数的个数 + * + * 求出1~13 的整数中1出现的次数, 并算出100~1300 的整数中1出现的次数? + * 为此他特别数了一下1~13 中包含1的数字有1、 10、 11、 12、 13 因此共出现6次, 但是对于后面问题他就没辙了。 + * ACMer希望你们帮帮他, 并把问题更加普遍化, 可以很快的求出任意非负整数区间中1出现的次数( 从1 到 n 中1出现的次数)。 + * + */ + +// ! 非原理性解法(暴力解法) + +function NumberOf1Between1AndN_Solution(n) { + // write code here + if (n <= 0) { + return 0; + } + var count = 0; + for (let i = 1; i <= n; i++) { + var tempData = String(i).match('1'); + if (tempData !== null) { + var tempArr = String(i); + for (var j in tempArr) { + if (tempArr[j] === '1') { + count++; + } + + } + // count += tempData.length; + } + } + return count; +} + +var num = 13; +console.log(NumberOf1Between1AndN_Solution(num)); + +// 原理性解法 +// 判断一个数里面有几个 1 \ No newline at end of file From fb0bba045299112c7dea469320da833520eb1e91 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 21 Apr 2019 22:05:07 +0800 Subject: [PATCH 117/274] =?UTF-8?q?=20=E5=90=88=E5=B9=B6=E4=B8=A4=E6=9C=89?= =?UTF-8?q?=E5=BA=8F=E7=9A=84=E9=93=BE=E8=A1=A8=20=E4=BB=A5=E5=8F=8A=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E9=93=BE=E8=A1=A8=E8=BD=AC=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E5=B7=A5=E5=85=B7=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 103 +++++++++++++++++++----- Leetcode/tools/LinkNodetoArray.js | 29 +++++++ NowCoder/Leetcode/mergeTwosortedLink.js | 59 ++++++++++++++ 3 files changed, 172 insertions(+), 19 deletions(-) create mode 100644 Leetcode/tools/LinkNodetoArray.js create mode 100644 NowCoder/Leetcode/mergeTwosortedLink.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 79ac04d..71e8747 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -5,7 +5,9 @@ * */ -const arrayToTreeNode = require('./tools/treeNode'); +// const arrayToTreeNode = require('./tools/treeNode'); +const arrayToLinkNode = require('./tools/LinkNode'); +const linkToArray = require('./tools/LinkNodetoArray'); // function TreeDepth(pRoot) { // // write code here @@ -43,33 +45,96 @@ const arrayToTreeNode = require('./tools/treeNode'); // return count; // } -function IsBalanced_Solution(pRoot) { +// function IsBalanced_Solution(pRoot) { +// // write code here +// if (pRoot === null) { +// return true; +// } + +// this.getDepth = function (rootNode) { +// if (rootNode === null) { +// return 0; +// } +// let left = this.getDepth(rootNode.left); +// if (left === -1) { +// return -1; +// } +// let right = this.getDepth(rootNode.right); +// if (right === -1) { +// return -1; +// } +// return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1; +// } + +// return this.getDepth(pRoot) !== -1; +// } + +function ListNode(x){ + this.val = x; + this.next = null; +} +function Merge(pHead1, pHead2) +{ // write code here - if (pRoot === null) { - return true; + if (pHead1 === null && pHead2 === null) { + return null; + } + if (pHead1 !== null && pHead2 === null) { + return pHead1; + } + if (pHead1 === null && pHead2 !== null) { + return pHead2; } - this.getDepth = function (rootNode) { - if (rootNode === null) { - return 0; + var outputLink; + + if (pHead1.val <= pHead2.val){ + outputLink = new ListNode(pHead1.val); + pHead1 = pHead1.next; + }else { + outputLink = new ListNode(pHead2.val); + pHead2 = pHead2.next; + } + while (pHead1 !==null || pHead2 !== null){ + var tempLink; + tempLink = outputLink; + while (tempLink.next !== null) { + tempLink = tempLink.next; } - let left = this.getDepth(rootNode.left); - if (left === -1) { - return -1; + if (pHead1 === null) { + tempLink.next = pHead2; + break; } - let right = this.getDepth(rootNode.right); - if (right === -1) { - return -1; + if (pHead2 === null) { + tempLink.next = pHead1; + break; + } + if (pHead1.val <= pHead2.val){ + tempLink.next = new ListNode(pHead1.val); + pHead1 = pHead1.next; + }else { + tempLink.next = new ListNode(pHead2.val); + pHead2 = pHead2.next; } - return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1; - } - return this.getDepth(pRoot) !== -1; + } + return outputLink; } -let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +let arr2 = [2, 3, 5, 6, 10, 12, 15]; + +var tempLink1 = arrayToLinkNode(arr1); +var tempLink2 = arrayToLinkNode(arr2); +console.log(tempLink1); +console.log(tempLink2); +var mergeLink = Merge(tempLink1, tempLink2); + +console.log(mergeLink); + +var toArray = linkToArray(mergeLink); -var tempTree = arrayToTreeNode(arr); +console.log(toArray); -console.log('递归版本是否平衡二叉树:', IsBalanced_Solution(tempTree)); +// console.log('递归版本是否平衡二叉树:', IsBalanced_Solution(tempTree)); // console.log('非递归版本深度:', treeDep(tempTree)); \ No newline at end of file diff --git a/Leetcode/tools/LinkNodetoArray.js b/Leetcode/tools/LinkNodetoArray.js new file mode 100644 index 0000000..f8f149c --- /dev/null +++ b/Leetcode/tools/LinkNodetoArray.js @@ -0,0 +1,29 @@ +/****** + * + * 输入链表返回 按照链表顺序的数组 + * + * + */ + +function ListNode(val) { + this.val = val; + this.next = null; +} + +function linkNodeToArray(linkNode) { + if (linkNode === null) { + return []; + } + let array = []; + + while(linkNode !== null){ + array.push(linkNode.val); + linkNode = linkNode.next; + } + return array; +} + +// let arr = [1,2,3,4,5]; +// console.log(arrayToLinkNode(arr)); + +module.exports = linkNodeToArray; \ No newline at end of file diff --git a/NowCoder/Leetcode/mergeTwosortedLink.js b/NowCoder/Leetcode/mergeTwosortedLink.js new file mode 100644 index 0000000..a1d8478 --- /dev/null +++ b/NowCoder/Leetcode/mergeTwosortedLink.js @@ -0,0 +1,59 @@ +/******* + * + * 合并两有序的链表 + * + * 输入两个单调递增的链表,输出两个链表合成后的链表, + * 当然我们需要合成后的链表满足单调不减规则。 + * + */ + +function ListNode(x){ + this.val = x; + this.next = null; +} +function Merge(pHead1, pHead2) +{ + if (pHead1 === null && pHead2 === null) { + return null; + } + if (pHead1 !== null && pHead2 === null) { + return pHead1; + } + if (pHead1 === null && pHead2 !== null) { + return pHead2; + } + + var outputLink; + + if (pHead1.val <= pHead2.val){ + outputLink = new ListNode(pHead1.val); + pHead1 = pHead1.next; + }else { + outputLink = new ListNode(pHead2.val); + pHead2 = pHead2.next; + } + while (pHead1 !==null || pHead2 !== null){ + var tempLink; + tempLink = outputLink; + while (tempLink.next !== null) { + tempLink = tempLink.next; + } + if (pHead1 === null) { + tempLink.next = pHead2; + break; + } + if (pHead2 === null) { + tempLink.next = pHead1; + break; + } + if (pHead1.val <= pHead2.val){ + tempLink.next = new ListNode(pHead1.val); + pHead1 = pHead1.next; + }else { + tempLink.next = new ListNode(pHead2.val); + pHead2 = pHead2.next; + } + + } + return outputLink; +} \ No newline at end of file From 9990e54c6f9df8fdeff8c846f1462fcc62cece5b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 21 Apr 2019 22:30:29 +0800 Subject: [PATCH 118/274] =?UTF-8?q?=E5=88=A4=E6=96=AD=E4=B8=80=E6=A3=B5?= =?UTF-8?q?=E6=A0=91=E6=98=AF=E4=B8=8D=E6=98=AF=E5=8F=A6=E4=B8=80=E6=A3=B5?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=AD=90=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/hasSubtree.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 NowCoder/Leetcode/hasSubtree.js diff --git a/NowCoder/Leetcode/hasSubtree.js b/NowCoder/Leetcode/hasSubtree.js new file mode 100644 index 0000000..dc7cdc3 --- /dev/null +++ b/NowCoder/Leetcode/hasSubtree.js @@ -0,0 +1,30 @@ +/**** + * + * 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) + * + * 思路解析:判断两棵树是否相等 + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function HasSubtree(pRoot1, pRoot2) +{ + // write code here + if(pRoot1 === null || pRoot2 === null){ + return false; + } + + this.checkIfEqual = function(tree1, tree2){ + if (tree1 === tree2) { + return true; + } else { + return false; + } + } + + +} \ No newline at end of file From bb210841663b176ec502af196244eb65d687a050 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 21 Apr 2019 23:45:20 +0800 Subject: [PATCH 119/274] =?UTF-8?q?=E5=AE=8C=E6=88=90=20=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E6=98=AF=E5=AD=90=E4=BA=8C=E5=8F=89=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 88 ++++++++++++++------------------- NowCoder/Leetcode/hasSubtree.js | 24 +++++++-- 2 files changed, 56 insertions(+), 56 deletions(-) diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 71e8747..2f92b97 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -5,9 +5,9 @@ * */ -// const arrayToTreeNode = require('./tools/treeNode'); -const arrayToLinkNode = require('./tools/LinkNode'); -const linkToArray = require('./tools/LinkNodetoArray'); +const arrayToTreeNode = require('./tools/treeNode'); +// const arrayToLinkNode = require('./tools/LinkNode'); +// const linkToArray = require('./tools/LinkNodetoArray'); // function TreeDepth(pRoot) { // // write code here @@ -69,72 +69,56 @@ const linkToArray = require('./tools/LinkNodetoArray'); // return this.getDepth(pRoot) !== -1; // } -function ListNode(x){ +function TreeNode(x) { this.val = x; - this.next = null; + this.left = null; + this.right = null; } -function Merge(pHead1, pHead2) +function HasSubtree(pRoot1, pRoot2) { // write code here - if (pHead1 === null && pHead2 === null) { - return null; + if(pRoot1 === null || pRoot2 === null){ + return false; } - if (pHead1 !== null && pHead2 === null) { - return pHead1; - } - if (pHead1 === null && pHead2 !== null) { - return pHead2; - } - - var outputLink; - - if (pHead1.val <= pHead2.val){ - outputLink = new ListNode(pHead1.val); - pHead1 = pHead1.next; - }else { - outputLink = new ListNode(pHead2.val); - pHead2 = pHead2.next; - } - while (pHead1 !==null || pHead2 !== null){ - var tempLink; - tempLink = outputLink; - while (tempLink.next !== null) { - tempLink = tempLink.next; - } - if (pHead1 === null) { - tempLink.next = pHead2; - break; - } - if (pHead2 === null) { - tempLink.next = pHead1; - break; + var tempState = false; + + this.checkIfhastree2 = function(tree1, tree2){ + if (tree2 === null) { + return true; + } + if (tree1 === null) { + return false; } - if (pHead1.val <= pHead2.val){ - tempLink.next = new ListNode(pHead1.val); - pHead1 = pHead1.next; - }else { - tempLink.next = new ListNode(pHead2.val); - pHead2 = pHead2.next; + + if (tree1.val !== tree2.val ) { + return false; } + return this.checkIfhastree2(tree1.left, tree2.left) && this.checkIfhastree2(tree1.right, tree2.right); + } + if (pRoot1.val === pRoot2.val) { + tempState = this.checkIfhastree2(pRoot1, pRoot2); + } + if (!tempState) { + tempState = HasSubtree(pRoot1.left, pRoot2); } - return outputLink; + if (!tempState) { + tempState = HasSubtree(pRoot1.right, pRoot2); + } + return tempState; } let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; -let arr2 = [2, 3, 5, 6, 10, 12, 15]; +let arr2 = [1, 2, 3, 4, 5]; + +var tempLink1 = arrayToTreeNode(arr1); +var tempLink2 = arrayToTreeNode(arr2); -var tempLink1 = arrayToLinkNode(arr1); -var tempLink2 = arrayToLinkNode(arr2); -console.log(tempLink1); -console.log(tempLink2); -var mergeLink = Merge(tempLink1, tempLink2); +var mergeLink = HasSubtree(tempLink1, tempLink2); console.log(mergeLink); -var toArray = linkToArray(mergeLink); -console.log(toArray); // console.log('递归版本是否平衡二叉树:', IsBalanced_Solution(tempTree)); // console.log('非递归版本深度:', treeDep(tempTree)); \ No newline at end of file diff --git a/NowCoder/Leetcode/hasSubtree.js b/NowCoder/Leetcode/hasSubtree.js index dc7cdc3..125480c 100644 --- a/NowCoder/Leetcode/hasSubtree.js +++ b/NowCoder/Leetcode/hasSubtree.js @@ -17,14 +17,30 @@ function HasSubtree(pRoot1, pRoot2) if(pRoot1 === null || pRoot2 === null){ return false; } + var tempState = false; - this.checkIfEqual = function(tree1, tree2){ - if (tree1 === tree2) { + this.checkIfhastree2 = function(tree1, tree2){ + if (tree2 === null) { return true; - } else { + } + if (tree1 === null) { return false; } + + if (tree1.val !== tree2.val ) { + return false; + } + return this.checkIfhastree2(tree1.left, tree2.left) && this.checkIfhastree2(tree1.right, tree2.right); } - + if (pRoot1.val === pRoot2.val) { + tempState = this.checkIfhastree2(pRoot1, pRoot2); + } + if (!tempState) { + tempState = HasSubtree(pRoot1.left, pRoot2); + } + if (!tempState) { + tempState = HasSubtree(pRoot1.right, pRoot2); + } + return tempState; } \ No newline at end of file From 98a91fec7438838bc8a976a616ed8fd9fe0c5bea Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 22 Apr 2019 20:38:38 +0800 Subject: [PATCH 120/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E9=95=9C=E5=83=8F=E7=9A=84=E9=80=92=E5=BD=92=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/mirrorTree.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 NowCoder/Leetcode/mirrorTree.js diff --git a/NowCoder/Leetcode/mirrorTree.js b/NowCoder/Leetcode/mirrorTree.js new file mode 100644 index 0000000..4c44c1f --- /dev/null +++ b/NowCoder/Leetcode/mirrorTree.js @@ -0,0 +1,32 @@ +/****** + * + * 操作给定的二叉树, 将其变换为源二叉树的镜像。 + * + * + * + */ + +// 解题思路,递归的经典解法 + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function Mirror(root) { + // write code here + if (root === null) { + return null; + } + + this.swap = function(treeNode) { + let temp = treeNode.left; + treeNode.left = treeNode.right; + treeNode.right = temp; + } + this.swap(root); + + Mirror(root.left); + Mirror(root.right); + +} \ No newline at end of file From efc9324fa3b1c0dcbe59069b179297cfb8515b8b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 23 Apr 2019 15:00:03 +0800 Subject: [PATCH 121/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=A1=BA=E6=97=B6?= =?UTF-8?q?=E9=92=88=E6=89=93=E5=8D=B0=E7=9F=A9=E9=98=B5=E7=9A=84=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/printMatrixbyClockwise.js | 59 +++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 NowCoder/Leetcode/printMatrixbyClockwise.js diff --git a/NowCoder/Leetcode/printMatrixbyClockwise.js b/NowCoder/Leetcode/printMatrixbyClockwise.js new file mode 100644 index 0000000..abc5c5c --- /dev/null +++ b/NowCoder/Leetcode/printMatrixbyClockwise.js @@ -0,0 +1,59 @@ +/****** + * + * 顺时针打印矩阵 + * + * 输入一个矩阵, 按照从外向里以顺时针的顺序依次打印出每一个数字, + * 例如, 如果输入如下4 X 4 矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + * 则依次打印出数字1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10. + * + */ + +function printMatrix(matrix) { + // write code here + // 设想为 n*m 的 矩阵 + var nlen = matrix.length; + var mlen = matrix[0].length; + var output = []; + if (mlen === 0 || nlen === 0) { + return output; + } + var top=0,left=0,right=mlen-1,bottom=nlen-1; + // 转圈圈的循环条件 + while(top<=bottom && left <= right){ + + // 从 左上到右上 + for (let i = left; i <=right; i++) { + output.push(matrix[top][i]); + } + // 从右上到右下 + for (let i = top+1; i <=bottom; i++) { + output.push(matrix[i][right]); + } + // 从右下到左下 + for (let j = right-1; j >=left && top < bottom; j--) { + output.push(matrix[bottom][j]); + } + // 从左下到左上 + for (let j = bottom - 1; j > top && right > left; j--) { + output.push(matrix[j][left]); + } + top++; + left++; + bottom--; + right--; + } + + return output; +} + +var matrix = []; +// matrix[0] = [1,2,3,4]; +// matrix[1] = [5,6,7,8]; +// matrix[2] = [9,10,11,12]; +// matrix[3] = [13,14,15,16]; +matrix[0] = [1,2]; +matrix[1] = [3,4]; +matrix[2] = [5,6]; +matrix[3] = [7,8]; + +console.log(printMatrix(matrix)); \ No newline at end of file From 6438ecf35fb448a907c25911fa31f376b1a6c237 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 23 Apr 2019 21:27:55 +0800 Subject: [PATCH 122/274] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92?= =?UTF-8?q?=E7=9A=84=E6=80=9D=E6=83=B3=E8=A7=A3=E5=86=B3=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E8=BF=9E=E7=BB=AD=E5=AD=90=E5=BA=8F=E5=88=97=E7=9A=84=E5=92=8C?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Leetcode/findGreatestSumOfSubArray.js | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 NowCoder/Leetcode/findGreatestSumOfSubArray.js diff --git a/NowCoder/Leetcode/findGreatestSumOfSubArray.js b/NowCoder/Leetcode/findGreatestSumOfSubArray.js new file mode 100644 index 0000000..36c3886 --- /dev/null +++ b/NowCoder/Leetcode/findGreatestSumOfSubArray.js @@ -0,0 +1,38 @@ +/***** + * + * 最大连续子序列的和 + * + * 在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。 + * 但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢? + * 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。 + * 给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1) + * + * + * + */ + + +// 解题思路:动态规划思想 +// max 表示以array[i]为末尾元素的子数组的和的最大值,子数组的元素的相对位置不变 +// res 表示所有子数组和的最大值 + +function FindGreatestSumOfSubArray(array) { + // write code here + if (array.length<=0 ) { + return; + } + if (array.length === 0) { + return array[0]; + } + var res = array[0]; + var max = array[0]; + for (let i = 1; i < array.length; i++) { + max = Math.max(max + array[i], array[i]); + res = Math.max(max, res); + } + return res; +} + +var arr = [-5, -3, 6, -3, -2, 7, -15, 1, 2, 2]; + +console.log(FindGreatestSumOfSubArray(arr)); \ No newline at end of file From 2c7c6203ee6359b1d351070e9a56108822ef1ebe Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 23 Apr 2019 22:17:06 +0800 Subject: [PATCH 123/274] =?UTF-8?q?=E6=89=93=E5=8D=B0=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E6=8B=BC=E6=8E=A5=E6=9C=80=E5=B0=8F=E7=9A=84=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Leetcode/PrintConnectMinNumberofArray.js | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 NowCoder/Leetcode/PrintConnectMinNumberofArray.js diff --git a/NowCoder/Leetcode/PrintConnectMinNumberofArray.js b/NowCoder/Leetcode/PrintConnectMinNumberofArray.js new file mode 100644 index 0000000..801ad50 --- /dev/null +++ b/NowCoder/Leetcode/PrintConnectMinNumberofArray.js @@ -0,0 +1,27 @@ +/****** + * + * 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 + * 例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。 + * + * + * + */ + +function PrintMinNumber(numbers) { + // write code here + if (numbers === null) { + return null; + } + var count = ''; + numbers.sort(function(num1, num2){ + return String(num1) + String(num2) > String(num2) + String(num1); + }) + numbers.forEach(element => { + count += element; + }); + + return count; +} + +var arr = [3, 32, 321]; +console.log(PrintMinNumber(arr)); \ No newline at end of file From 5655f5d2c9f1829dcb524210e735d84ea4aa2278 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 24 Apr 2019 22:17:55 +0800 Subject: [PATCH 124/274] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=95=B0=E5=AD=97?= =?UTF-8?q?=E7=BC=96=E8=A7=A3=E7=A0=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TestProjects/decodePassword.js | 73 ++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 TestProjects/decodePassword.js diff --git a/TestProjects/decodePassword.js b/TestProjects/decodePassword.js new file mode 100644 index 0000000..68065c9 --- /dev/null +++ b/TestProjects/decodePassword.js @@ -0,0 +1,73 @@ +/****** + * + * 初始密码是一段升序的数字 + * 已有的加密算法会 将数字转换成英文拼接成字符串,并改变字符串的大小写以及顺序 + * 现已知加密后的密码还原出原有的密码 + * + * + */ + +// 思路:应该就是转换小写后统计每个字母出现的次数,根据是个数字的英文进行匹配,最后调整成升序就好吧 + + +// 分析每个英文字母的特征 进行统计整理 + +// 0 z +// 2 w +// 4 u +// 6 x +// 8 g +// 7 s - x +// 3 h - g +// 5 v - (s-x) +// 1 o - z - w - u +// 9 i - x - g - v + (s-x) + + + +function DecodePassword(newPass){ + var dealedstr = newPass.toLowerCase(); + var numstrs = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; + var num = []; + + + for (let index = 0; index <= 9; index++) { + num[index] =0; + } + + for (let i = 0; i < dealedstr.length; i++) { + switch (dealedstr[i]) { + case 'z': num[0]++;break; + case 'o': num[1]++;break; + case 'w': num[2]++;break; + case 'h': num[3]++;break; + case 'u': num[4]++;break; + case 'v': num[5]++;break; + case 'x': num[6]++;break; + case 's': num[7]++;break; + case 'g': num[8]++;break; + case 'i': num[9]++;break; + default: + break; + } + } + num[7] = num[7] - num[6]; + num[3] = num[3] - num[8]; + num[5] = num[5] - num[7]; + num[1] = num[1] - num[0] - num[2] - num[4]; + num[9] = num[9] - num[6] - num[8] - num[5]; + + var outstr = ''; + for (let j = 0; j <=9; j++) { + while(num[j]){ + outstr+= j; + num[j]--; + } + } + return outstr; +} + +// var encode = 'NeNohuiroNNiNeteefersix'; // 测试集1 +var encode = 'oNEthrEEfoursixNiNENiEN'; // 测试集1 + +console.log(DecodePassword(encode)); \ No newline at end of file From 9ec81d9ab133af320d97b3761e7f869b67bd37a4 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 24 Apr 2019 23:42:15 +0800 Subject: [PATCH 125/274] =?UTF-8?q?=E6=89=BE=E5=88=B0=E7=AC=AC=20N=20?= =?UTF-8?q?=E4=B8=AA=E4=B8=91=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/getUglyNumber_Solution.js | 36 +++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 NowCoder/Leetcode/getUglyNumber_Solution.js diff --git a/NowCoder/Leetcode/getUglyNumber_Solution.js b/NowCoder/Leetcode/getUglyNumber_Solution.js new file mode 100644 index 0000000..d1a525e --- /dev/null +++ b/NowCoder/Leetcode/getUglyNumber_Solution.js @@ -0,0 +1,36 @@ +/****** + * + * 把只包含质因子2、3和5的数称作丑数(Ugly Number)。 + * 例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。 + * 求按从小到大的顺序的第N个丑数。 + * + * + */ + +function GetUglyNumber_Solution(index) +{ + if (index < 7) { + return index; + } + + let result = []; + result[0] = 1; + let with2=0,with3=0,with5=0; + for (let i = 1; i < index; i++) { + result[i] = Math.min(result[with2]*2, Math.min(result[with3]*3, result[with5]*5)); + if (result[i] === result[with2]*2) { + with2++; + } + if (result[i] === result[with3]*3) { + with3++; + } + if (result[i] === result[with5]*5) { + with5++; + } + } + return result[index - 1]; +} + +let index = 10; + +console.log(GetUglyNumber_Solution(index)); \ No newline at end of file From a6f328106df5bbc051c879aaeeb16a3e92e2a88b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 25 Apr 2019 14:29:28 +0800 Subject: [PATCH 126/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=A0=86=E6=A0=88=E7=BB=93=E6=9E=84=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E8=87=AA=E5=AE=9A=E4=B9=89=E8=BF=94=E5=9B=9E=E5=BD=93?= =?UTF-8?q?=E5=89=8D=E6=9C=80=E5=B0=8F=E5=80=BC=E7=9A=84=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/createMinStackStructure.js | 65 ++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 NowCoder/Leetcode/createMinStackStructure.js diff --git a/NowCoder/Leetcode/createMinStackStructure.js b/NowCoder/Leetcode/createMinStackStructure.js new file mode 100644 index 0000000..f77f82c --- /dev/null +++ b/NowCoder/Leetcode/createMinStackStructure.js @@ -0,0 +1,65 @@ +/******* + * + * + * 定义栈的数据结构, 请在该类型中实现一个能够得到栈中所含最小元素的min函数 + * ( 时间复杂度应为O( 1))。 + * + * + */ + +// 解题思路:使用两个数组,一个存栈的数据,另一个存当前最小值 +// 压栈的时候 判断压入的是否比当前最小值小,如果比它小就压入当前值,如果不比它小则压入min数组的最顶端的值 +// 弹出的时候,一起弹出栈顶的数据 + +let arrdata = []; +let mindata = []; + +function push(node) { + // write code here + if (arrdata.length === 0) { + arrdata[0] = node; + mindata[0] = node; + } else if (node <= mindata[mindata.length-1]) { + arrdata[arrdata.length] = node; + mindata[mindata.length] = node; + } else { + arrdata[arrdata.length] = node; + mindata[mindata.length] = mindata[mindata.length - 1]; + } +} + +function pop() { + // write code here + if (arrdata.length === 0) { + return; + } + mindata.pop(); + return arrdata.pop(); +} + +function top() { + // write code here + if (arrdata.length === 0) { + return; + } + return arrdata[arrdata.length-1]; +} + +function min() { + if (arrdata.length === 0) { + return; + } + return mindata[mindata.length- 1]; +} + + +push(4); +push(2); +push(3); +push(1); +push(6); + +console.log(min()); +console.log(top()); +console.log(pop()); +console.log(top()); \ No newline at end of file From f0ecdaeeca380e7ae7ea77f064ebe3eaea4cce5f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 25 Apr 2019 16:36:50 +0800 Subject: [PATCH 127/274] =?UTF-8?q?=E5=B7=B2=E7=9F=A5=E5=85=A5=E6=A0=88?= =?UTF-8?q?=E9=98=9F=E5=88=97=EF=BC=8C=E5=88=A4=E6=96=AD=E5=87=BA=E6=A0=88?= =?UTF-8?q?=E9=98=9F=E5=88=97=E7=9A=84=E6=98=AF=E5=90=A6=E6=AD=A3=E7=A1=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/isPopOrder.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 NowCoder/Leetcode/isPopOrder.js diff --git a/NowCoder/Leetcode/isPopOrder.js b/NowCoder/Leetcode/isPopOrder.js new file mode 100644 index 0000000..9f745a1 --- /dev/null +++ b/NowCoder/Leetcode/isPopOrder.js @@ -0,0 +1,32 @@ +/***** + * + * 输入两个整数序列, 第一个序列表示栈的压入顺序, 请判断第二个序列是否可能为该栈的弹出顺序。 + * 假设压入栈的所有数字均不相等。 例如序列1, 2, 3, 4, 5 是某栈的压入顺序, 序列4, 5, 3, 2, 1 是该压栈序列对应的一个弹出序列, + * 但4, 3, 5, 1, 2 就不可能是该压栈序列的弹出序列。( 注意: 这两个序列的长度是相等的) + * + * + * + */ + +// 解题思路:如果发现有入栈的元素 弹出栈了,就不保留该元素,并把出栈队列的指针指向下一个 + +function IsPopOrder(pushV, popV) { + if (pushV.length !== popV.length) { + return false; + } + let len = pushV.length; + let tempStack = []; + let j = 0; + for (let i = 0; i < len; i++) { + tempStack.push(pushV[i]); + while ( tempStack.length !==0 && tempStack[tempStack.length - 1] === popV[j]) { + tempStack.pop(); + j++; + } + } + return tempStack.length === 0; +} + +let pushV = [1, 2, 3, 4, 5]; +let popV = [4, 5, 3, 1, 2]; +console.log(IsPopOrder(pushV, popV)); \ No newline at end of file From 1d03a6a8d8c507fcfcf47d3f713af05451e6a5fb Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 25 Apr 2019 17:20:25 +0800 Subject: [PATCH 128/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=20=E5=B1=82=E6=AC=A1?= =?UTF-8?q?=E9=81=8D=E5=8E=86=E6=B3=95=20=E5=AE=8C=E6=88=90=E4=BB=8E?= =?UTF-8?q?=E4=B8=8A=E5=88=B0=E4=B8=8B=E6=89=93=E5=8D=B0=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 93 +++++++++++++------ NowCoder/Leetcode/printTreeFromTopToBottom.js | 65 +++++++++++++ 2 files changed, 128 insertions(+), 30 deletions(-) create mode 100644 NowCoder/Leetcode/printTreeFromTopToBottom.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 2f92b97..5c3eb10 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -69,43 +69,74 @@ const arrayToTreeNode = require('./tools/treeNode'); // return this.getDepth(pRoot) !== -1; // } +// function TreeNode(x) { +// this.val = x; +// this.left = null; +// this.right = null; +// } +// function HasSubtree(pRoot1, pRoot2) +// { +// // write code here +// if(pRoot1 === null || pRoot2 === null){ +// return false; +// } +// var tempState = false; + +// this.checkIfhastree2 = function(tree1, tree2){ +// if (tree2 === null) { +// return true; +// } +// if (tree1 === null) { +// return false; +// } + +// if (tree1.val !== tree2.val ) { +// return false; +// } +// return this.checkIfhastree2(tree1.left, tree2.left) && this.checkIfhastree2(tree1.right, tree2.right); +// } + +// if (pRoot1.val === pRoot2.val) { +// tempState = this.checkIfhastree2(pRoot1, pRoot2); +// } +// if (!tempState) { +// tempState = HasSubtree(pRoot1.left, pRoot2); +// } +// if (!tempState) { +// tempState = HasSubtree(pRoot1.right, pRoot2); +// } +// return tempState; +// } + function TreeNode(x) { this.val = x; this.left = null; this.right = null; } -function HasSubtree(pRoot1, pRoot2) -{ + +// 考虑使用层次遍历法 + +function PrintFromTopToBottom(root) { // write code here - if(pRoot1 === null || pRoot2 === null){ - return false; + if (root === null) { + return []; } - var tempState = false; - - this.checkIfhastree2 = function(tree1, tree2){ - if (tree2 === null) { - return true; - } - if (tree1 === null) { - return false; + let tempList = []; + let outprint = []; + tempList.push(root); + while (tempList.length !== 0) { + let tempNode = tempList[0]; + outprint.push(tempNode.val); + tempList = tempList.slice(1); + if (tempNode.left !== null) { + tempList.push(tempNode.left); } - - if (tree1.val !== tree2.val ) { - return false; + if (tempNode.right !== null) { + tempList.push(tempNode.right); } - return this.checkIfhastree2(tree1.left, tree2.left) && this.checkIfhastree2(tree1.right, tree2.right); } + return outprint; - if (pRoot1.val === pRoot2.val) { - tempState = this.checkIfhastree2(pRoot1, pRoot2); - } - if (!tempState) { - tempState = HasSubtree(pRoot1.left, pRoot2); - } - if (!tempState) { - tempState = HasSubtree(pRoot1.right, pRoot2); - } - return tempState; } let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; @@ -113,10 +144,12 @@ let arr2 = [1, 2, 3, 4, 5]; var tempLink1 = arrayToTreeNode(arr1); var tempLink2 = arrayToTreeNode(arr2); - -var mergeLink = HasSubtree(tempLink1, tempLink2); - -console.log(mergeLink); +console.log(tempLink1); +console.log(tempLink2); +var list1 = PrintFromTopToBottom(tempLink1); +console.log(list1); +var list2 = PrintFromTopToBottom(tempLink2); +console.log(list2); diff --git a/NowCoder/Leetcode/printTreeFromTopToBottom.js b/NowCoder/Leetcode/printTreeFromTopToBottom.js new file mode 100644 index 0000000..6f43712 --- /dev/null +++ b/NowCoder/Leetcode/printTreeFromTopToBottom.js @@ -0,0 +1,65 @@ +/**** + * + * + * 从上往下打印出二叉树的每个节点, 同层节点从左至右打印。 + * + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +// 考虑使用层次遍历法, 将每一层的先压入栈中,用完就抛弃 + +function PrintFromTopToBottom(root) { + // write code here + if (root === null) { + return []; + } + let tempList = []; + let outprint = []; + tempList.push(root); + while(tempList.length !== 0){ + let tempLen = tempList.length; + for (let i = 0; i < tempLen; i++) { + let tempNode = tempList[0]; + outprint.push(tempNode.val); + tempList = tempList.slice(1); + if (tempNode.left !== null) { + tempList.push(tempNode.left); + } + if (tempNode.right !== null) { + tempList.push(tempNode.right); + } + } + } + return outprint; + +} + +// 简化版本的层次遍历法 + +function PrintFromTopToBottom2(root) { + // write code here + if (root === null) { + return []; + } + let tempList = []; + let outprint = []; + tempList.push(root); + while (tempList.length !== 0) { + let tempNode = tempList[0]; + outprint.push(tempNode.val); + tempList = tempList.slice(1); + if (tempNode.left !== null) { + tempList.push(tempNode.left); + } + if (tempNode.right !== null) { + tempList.push(tempNode.right); + } + } + return outprint; +} \ No newline at end of file From b889939979e00b0efd478ac11f6566e5456426fa Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 25 Apr 2019 21:47:33 +0800 Subject: [PATCH 129/274] =?UTF-8?q?=E5=AD=97=E5=85=B8=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E6=8E=92=E6=95=B0=20DFS=E5=86=85=E5=AD=98=E5=8D=A0=E7=94=A8?= =?UTF-8?q?=E8=BE=83=E5=A4=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/verifySquenceOfBST.js | 12 +++++++ TestProjects/Tools/selfTest.js | 33 +++++++++++++++++ TestProjects/dictionarySortList.js | 47 +++++++++++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 NowCoder/Leetcode/verifySquenceOfBST.js create mode 100644 TestProjects/Tools/selfTest.js create mode 100644 TestProjects/dictionarySortList.js diff --git a/NowCoder/Leetcode/verifySquenceOfBST.js b/NowCoder/Leetcode/verifySquenceOfBST.js new file mode 100644 index 0000000..7ed9de8 --- /dev/null +++ b/NowCoder/Leetcode/verifySquenceOfBST.js @@ -0,0 +1,12 @@ +/****** + * + * + * 输入一个整数数组, 判断该数组是不是某二叉搜索树的后序遍历的结果。 + * 如果是则输出Yes, 否则输出No。 假设输入的数组的任意两个数字都互不相同。 + * + * + */ + +function VerifySquenceOfBST(sequence) { + // write code here +} \ No newline at end of file diff --git a/TestProjects/Tools/selfTest.js b/TestProjects/Tools/selfTest.js new file mode 100644 index 0000000..bc68917 --- /dev/null +++ b/TestProjects/Tools/selfTest.js @@ -0,0 +1,33 @@ +function dictionarySortList(n, m) { + if (n < m) { + return null; + } + var sortArr = []; + + this.dfs = function (current, n, sortArr) { + if (current > n) { + return; + } + sortArr.push(current); + for (let i = 0; i <= 9; i++) { + if (10 * current + i > n) { + return; + } + this.dfs(10 * current + i, n, sortArr); + } + } + for (let j = 1; j <= 9; j++) { + this.dfs(j, n, sortArr); + } + + return sortArr[m - 1]; +} + + +while (line = readline()) { + var lines = line.split(' '); + var a = parseInt(lines[0]); + var b = parseInt(lines[1]); + var m = dictionarySortList(a, b); + print(m); +} \ No newline at end of file diff --git a/TestProjects/dictionarySortList.js b/TestProjects/dictionarySortList.js new file mode 100644 index 0000000..b83c229 --- /dev/null +++ b/TestProjects/dictionarySortList.js @@ -0,0 +1,47 @@ +/******* + * + * 输入 N,M,对 1~N 按照特定规则排序,求排序后的第M个数 + * + * + * + */ + + // sortArr[0] = '1'; + // for (let i = 2; i <=n; i++) { + // sortArr[i-1] = String(i); + // } + // sortArr.sort(function(a,b){ + // return a>b; + // }) + + // console.log(sortArr); + // return parseInt(sortArr[m-1]); + + + +function dictionarySortList(n, m){ + if (n < m) { + return null; + } + var sortArr = []; + + this.dfs = function(current, n, sortArr){ + if (current > n) { + return; + } + sortArr.push(current); + for (let i = 0; i <=9; i++) { + if (10* current + i > n) { + return; + } + this.dfs(10*current + i, n, sortArr); + } + } + for (let j = 1; j <= 9; j++) { + this.dfs(j, n, sortArr); + } + + return sortArr[m-1]; +} + +console.log(dictionarySortList(200, 25)); \ No newline at end of file From 6c17a5fff007f6138dc3da012ce09522f9596465 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 26 Apr 2019 17:10:44 +0800 Subject: [PATCH 130/274] =?UTF-8?q?=E9=AA=8C=E8=AF=81=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E5=90=8E=E7=BB=AD=E9=81=8D?= =?UTF-8?q?=E5=8E=86=E5=BA=8F=E5=88=97=E6=98=AF=E5=90=A6=E5=90=88=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 递归方法 --- NowCoder/Leetcode/verifySquenceOfBST.js | 30 +++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/NowCoder/Leetcode/verifySquenceOfBST.js b/NowCoder/Leetcode/verifySquenceOfBST.js index 7ed9de8..31bed97 100644 --- a/NowCoder/Leetcode/verifySquenceOfBST.js +++ b/NowCoder/Leetcode/verifySquenceOfBST.js @@ -8,5 +8,31 @@ */ function VerifySquenceOfBST(sequence) { - // write code here -} \ No newline at end of file + if (sequence.length === 0) { + return false; + } + if (sequence.length === 1) { + return true; + } + var len = sequence.length; + var rootNode = sequence[len-1]; + var i; + for (i = 0; i < len-1; i++) { + if (sequence[i] > rootNode) { + break; + } + } + // i 为右子树的划分点 + for (var j = i; j < len-1; j++) { + if (sequence[j] < rootNode) { + return false; + } + } + + var checkLeft = (i > 0) ? VerifySquenceOfBST(sequence.slice(0,i)):true; + var checkRight = (i < len-1)? VerifySquenceOfBST(sequence.slice(i, len-1)):true; + return (checkLeft && checkRight); +} + +var seq = [1,5,7,6,3,9,8]; // 二叉搜索树的后续遍历序列 +console.log(VerifySquenceOfBST(seq)); \ No newline at end of file From 0c0747951bfea68cb9f07058f257626d61cbf8d5 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 26 Apr 2019 21:26:42 +0800 Subject: [PATCH 131/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=E4=BC=98=E5=85=88=E9=81=8D=E5=8E=86=E7=9A=84=E6=80=9D=E6=83=B3?= =?UTF-8?q?=20=E5=AE=8C=E6=88=90=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E5=85=B8=E5=BA=8F=E6=8E=92=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/permutationString.js | 54 ++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 NowCoder/Leetcode/permutationString.js diff --git a/NowCoder/Leetcode/permutationString.js b/NowCoder/Leetcode/permutationString.js new file mode 100644 index 0000000..4f527f9 --- /dev/null +++ b/NowCoder/Leetcode/permutationString.js @@ -0,0 +1,54 @@ +/********** + * + * + * 输入一个字符串, 按字典序打印出该字符串中字符的所有排列。 + * 例如输入字符串abc, 则打印出由字符a, b, c所能排列出来的所有字符串abc, acb, bac, bca, cab和cba。 + * + * 输入一个字符串, 长度不超过9(可能有字符重复), 字符只包括大小写字母。 + * + */ + +// 记得数组去重,使用深度优先遍历的思想 + +function Permutation(str) { + // write code here + var output = []; + if (str.length === 0) { + return output; + } + var table = str.split(''); + var len = table.length; + this.dfs = function (tempStr, tempTable, output) { + if (tempStr.length === len) { + if (!output.includes(tempStr)) { + output.push(tempStr); + } + return; + } + for (let i = 0; i < tempTable.length; i++) { + var otherTable = []; + for (let k = 0; k < tempTable.length; k++) { + if (k !== i) { + otherTable.push(tempTable[k]); + } + } + this.dfs(tempStr+String(tempTable[i]), otherTable, output); + } + } + + for (let j = 0; j < table.length; j++) { + var tempTable = []; + for (let k = 0; k < table.length; k++) { + if (k !== j) { + tempTable.push(table[k]); + } + } + this.dfs(String(table[j]), tempTable, output); + } + + return output; +} + +var str = 'aa'; + +console.log(Permutation(str)); \ No newline at end of file From 46971e86da8be50eaaa697222c1aa67c4fdeca0b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 27 Apr 2019 09:03:45 +0800 Subject: [PATCH 132/274] =?UTF-8?q?=E7=89=9B=E5=AE=A2=E7=BD=91=E7=9A=84Jav?= =?UTF-8?q?aScript=20=E6=95=B0=E6=8D=AE=E8=AF=BB=E5=8F=96=E6=93=8D?= =?UTF-8?q?=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TestProjects/scanStringfromTerminal.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 TestProjects/scanStringfromTerminal.js diff --git a/TestProjects/scanStringfromTerminal.js b/TestProjects/scanStringfromTerminal.js new file mode 100644 index 0000000..82b1645 --- /dev/null +++ b/TestProjects/scanStringfromTerminal.js @@ -0,0 +1,16 @@ +/****** + * + * 牛客网 OJ 平台自测代码使用 + * + * + */ + +// 从命令行读取数据完成数据输入 +while (line = readline()) { + var lines = line.split(' '); + var a = parseInt(lines[0]); + var b = parseInt(lines[1]); + // 读取参数完成方法调用 + var m = dictionarySortList(a, b); + print(m); +} \ No newline at end of file From 9a83093675a1fcd337ffd0a92b6d511076114cb1 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 27 Apr 2019 19:49:25 +0800 Subject: [PATCH 133/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E8=AF=BB=E8=A1=8C=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TestProjects/readandPrint.js | 35 ++++++++++++++++++++++++++ TestProjects/scanStringfromTerminal.js | 28 ++++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 TestProjects/readandPrint.js diff --git a/TestProjects/readandPrint.js b/TestProjects/readandPrint.js new file mode 100644 index 0000000..0e2a831 --- /dev/null +++ b/TestProjects/readandPrint.js @@ -0,0 +1,35 @@ +function countChoose(locations, distance) { + if (locations.length <= 2) { + return 0; + } + var allFunction = []; + var realDistance = distance; + var glen = locations.length; + if (glen == 3) { + return 1; + } + + this.countDistance = function (a, b) { + if (Math.abs(a - b) <= realDistance) { + return true; + } else { + return false; + } + } + + return glen * (glen - 1) * (glen - 2) / 6; + +} + +var initPre = readline().split(" "); +var countN = parseInt(initPre[0]); +var countD = parseInt(initPre[1]); + +var datas = readline().split(" "); +var realdatas = []; + +for (var i = 0; i < countN; i++) { + realdatas.push(parseInt(datas[i])); +} +var result = countChoose(realdatas, countD); +print(result); \ No newline at end of file diff --git a/TestProjects/scanStringfromTerminal.js b/TestProjects/scanStringfromTerminal.js index 82b1645..327d94a 100644 --- a/TestProjects/scanStringfromTerminal.js +++ b/TestProjects/scanStringfromTerminal.js @@ -13,4 +13,30 @@ while (line = readline()) { // 读取参数完成方法调用 var m = dictionarySortList(a, b); print(m); -} \ No newline at end of file +} + + +// 本题为考试多行输入输出规范示例,无需提交,不计分。 +var n = parseInt(readline()); +var ans = 0; +for (var i = 0; i < n; i++) { + lines = readline().split(" ") + for (var j = 0; j < lines.length; j++) { + ans += parseInt(lines[j]); + } +} +print(ans); + + + +// Node.js 版本的读取命令行数据 + +var readline = require('readline'); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); +rl.on('line', function (line) { + var tokens = line.split(' '); + console.log(parseInt(tokens[0]) + parseInt(tokens[1])); +}); \ No newline at end of file From 2442f0f06d52b1d7a50a20932b4f9ec163b85a04 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 28 Apr 2019 11:14:58 +0800 Subject: [PATCH 134/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E5=A4=B4?= =?UTF-8?q?=E6=9D=A1=E7=AC=94=E8=AF=95=E7=9A=84=E5=A5=B6=E7=89=9B=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E5=92=8C=E9=BA=BB=E5=B0=86=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 奶牛问题已解决,麻将问题待解决 --- TestProjects/ByteDance/20190427CowNum.js | 70 +++++++++++++++++++++++ TestProjects/ByteDance/20190427MaJiang.js | 44 ++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 TestProjects/ByteDance/20190427CowNum.js create mode 100644 TestProjects/ByteDance/20190427MaJiang.js diff --git a/TestProjects/ByteDance/20190427CowNum.js b/TestProjects/ByteDance/20190427CowNum.js new file mode 100644 index 0000000..915850f --- /dev/null +++ b/TestProjects/ByteDance/20190427CowNum.js @@ -0,0 +1,70 @@ +/****** + * + * 字节跳动 春招技术类实习生笔试第一题 + * 奶牛生小牛问题 + * 3-7 岁每年生一头母牛 + * 第11年死亡 + * 一只母牛第 n 年有多少牛 + * + * + */ + +function CowNum(n){ + if (n<=0) { + return 0; + } + + // 面向对象解题 + var Cow = function (age,state,birth){ + this.age = age; + this.state = state; + this.birth = birth; + } + var allCow = []; + allCow.push(new Cow(1,true,false)); + // 用于每年更新所有奶牛的状态 + this.caculate = function (allCow){ + for (var every in allCow) { + allCow[every].age++; + if (allCow[every].age > 10) { + allCow[every].state = false; + } + // 更新奶牛的可生育状态 + if (allCow[every].age >= 3 && allCow[every].age <=7) { + allCow[every].birth = true; + } else { + allCow[every].birth = false; + } + // 如果该奶牛当前可生育 + if (allCow[every].birth) { + allCow.push(new Cow(1, true, false)); + } + } + } + // 计算活着的奶牛数量 + this.countNum = function (Cows){ + var tempcount = 0; + for (var every in Cows){ + if (Cows[every].state) { + tempcount++; + } + } + return tempcount; + } + + for (let i = 2; i <= n; i++) { + this.caculate(allCow); + } + return this.countNum(allCow); + +} + +// 测试案例通过 +// 1 1 +// 2 1 +// 3 2 +// 4 3 +// 5 5 +// 12 123 +var year = 4; +console.log(CowNum(year)); diff --git a/TestProjects/ByteDance/20190427MaJiang.js b/TestProjects/ByteDance/20190427MaJiang.js new file mode 100644 index 0000000..47a024e --- /dev/null +++ b/TestProjects/ByteDance/20190427MaJiang.js @@ -0,0 +1,44 @@ +/***** + * + * 字节跳动 春招技术类实习生笔试第二题 + * + * 36 张牌(9*4)的麻将打法 + * + * 输入 13 张牌,问再取一张牌,取哪几种数字可以 和牌 + * + * 和牌条件:一个雀头(对子),四个顺子(234,456)或刻子(111,333) + * 和牌例子:1 1 1 2 2 2 6 6 6 7 7 7 9 9 + * + * ! 问题描述:输入 13 张牌, 问再取一张牌, 可以取哪几种数字达到和牌的条件 + * 输出为 数字的 集合 + */ + +// 解析: 将问题转换成 判断是否和牌的问题 + +function countWinWays(cardArr){ + var effecArr = []; + if (cardArr.length !== 13){ + return effecArr; + } + + // 用于判断 14 张牌是否能够和牌 + this.checkIfWin = function (tempArr) { + if (tempArr.length !== 14) { + return false; + } + // 统计每种数字的数量 + + } + + for (let i = 1; i <=9; i++) { + var tempArr = cardArr; + tempArr.push(i); + if (this.checkIfWin(tempArr)) { + effecArr.push(i); + } + } + return effecArr; +} + +var cardArr = [1, 1, 1, 1, 2, 2, 3, 3, 5, 6, 7, 8, 9]; +console.log(countWinWays(cardArr)); \ No newline at end of file From 801e48abffb5114e846d84ec3ff864dc91a603d3 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 28 Apr 2019 16:43:32 +0800 Subject: [PATCH 135/274] =?UTF-8?q?=E7=9C=9F=E5=AE=9E=E7=AC=94=E8=AF=95?= =?UTF-8?q?=E9=A2=98=E5=BD=92=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 麻将胡牌解法,已通过两个案例 --- TestProjects/{ => Baidu}/findminPro.js | 7 +- TestProjects/ByteDance/20190427MaJiang.js | 108 +++++++++++++++++++- TestProjects/{ => HuaWei}/decodePassword.js | 6 +- 3 files changed, 115 insertions(+), 6 deletions(-) rename TestProjects/{ => Baidu}/findminPro.js (87%) rename TestProjects/{ => HuaWei}/decodePassword.js (92%) diff --git a/TestProjects/findminPro.js b/TestProjects/Baidu/findminPro.js similarity index 87% rename from TestProjects/findminPro.js rename to TestProjects/Baidu/findminPro.js index b23398b..4400d4e 100644 --- a/TestProjects/findminPro.js +++ b/TestProjects/Baidu/findminPro.js @@ -1,9 +1,14 @@ /**** - * + * 2019.04.02 * 百度实习生笔试算法题第一题 * N, P, Q, Array * 输入包括四个参数 * + * num 表示项目成员人数 N 的整数 + * projCmpt 成功完成项目的成员得分减少的值 + * restDec 错误分数大于零的团队成员的错误分数减少的值 + * errScore 初始错误分数列表 + * * */ diff --git a/TestProjects/ByteDance/20190427MaJiang.js b/TestProjects/ByteDance/20190427MaJiang.js index 47a024e..73dd04e 100644 --- a/TestProjects/ByteDance/20190427MaJiang.js +++ b/TestProjects/ByteDance/20190427MaJiang.js @@ -21,18 +21,117 @@ function countWinWays(cardArr){ return effecArr; } - // 用于判断 14 张牌是否能够和牌 + // ! 用于判断 14 张牌是否能够和牌 this.checkIfWin = function (tempArr) { if (tempArr.length !== 14) { return false; } // 统计每种数字的数量 + var countArr = []; + countArr[0] = 0; + for (let i = 1; i <= 9; i++) { + countArr[i] = 0; + } + for (let j = 0; j < tempArr.length; j++) { + countArr[tempArr[j]]++; + } + + // 对 统计的结果 countArr 进行判断是否和牌 + // console.log(countArr); + var proDouble = []; + for (let i = 1; i <=9; i++) { + // 存在 5 个 一样的是不合法的数据,不能胡牌 + if (countArr[i]>= 5) { + return false; + } + + // 存在 有 对子的 先存起来 + if (countArr[i] >= 2) { + proDouble.push(i); + } + } + // console.log(proDouble); + if (proDouble.length === 0) { + return false; + } + + var lastResult = false; + // 循环判断 去除 雀头 后是否为 4 个 顺子或 刻子 + for (let k = 0; k < proDouble.length; k++) { + var lastArr = countArr.slice(0); + lastArr[proDouble[k]]-= 2; + if (this.checkIfOrderorTri(lastArr)) { + // console.log('someone like u'); + lastResult = true; + } + } + + return lastResult; + + } + + // ! 用于判断是否是 4 个 顺子或刻子 + this.checkIfOrderorTri = function (lastArr) { + // console.log('lastArr', lastArr); + var resultState = false; + var countResult = 0; + var tempOrder = []; + var backOrder = []; + var bace; + for (let i = 1; i <=9; i++) { + if (lastArr[i] !== 0) { + if (lastArr[i] === 4) { + countResult++; + tempOrder.push(i); + } + if (lastArr[i] === 3) { + countResult++; + } + if (lastArr[i] === 2) { + tempOrder.push(i); + backOrder.push(i); + } + if (lastArr[i] === 1) { + tempOrder.push(i); + backOrder = []; + bace = true; + } + + if (tempOrder.length === 3) { + if ((tempOrder[1] === tempOrder[0] + 1) && (tempOrder[2] === tempOrder[1] + 1)) { + countResult++; + tempOrder = []; + if (bace && lastArr[i] === 2) { + tempOrder.push(i); + bace = false; + } + + } else { + return resultState; + } + } + if (backOrder.length === 3) { + if ((backOrder[1] === backOrder[0] + 1) && (backOrder[2] === backOrder[1] + 1)) { + countResult++; + backOrder = []; + } + } + + + } + } + if (countResult === 4) { + resultState = true; + } + return resultState; } + for (let i = 1; i <=9; i++) { - var tempArr = cardArr; + var tempArr = cardArr.slice(0); tempArr.push(i); + // console.log(tempArr); if (this.checkIfWin(tempArr)) { effecArr.push(i); } @@ -40,5 +139,6 @@ function countWinWays(cardArr){ return effecArr; } -var cardArr = [1, 1, 1, 1, 2, 2, 3, 3, 5, 6, 7, 8, 9]; -console.log(countWinWays(cardArr)); \ No newline at end of file +var cardArr = [1, 1, 1, 1, 2, 2, 3, 3, 5, 6, 7, 8, 9]; // 4,7 +var cardArr2 = [1, 1, 1, 2, 2, 2, 5, 5, 5, 6, 6, 6, 9]; // 9 +console.log(countWinWays(cardArr2)); \ No newline at end of file diff --git a/TestProjects/decodePassword.js b/TestProjects/HuaWei/decodePassword.js similarity index 92% rename from TestProjects/decodePassword.js rename to TestProjects/HuaWei/decodePassword.js index 68065c9..53cac30 100644 --- a/TestProjects/decodePassword.js +++ b/TestProjects/HuaWei/decodePassword.js @@ -1,8 +1,12 @@ /****** + * + * 2019.04.24 + * 华为 实习生笔试题算法题第3题 * * 初始密码是一段升序的数字 * 已有的加密算法会 将数字转换成英文拼接成字符串,并改变字符串的大小写以及顺序 - * 现已知加密后的密码还原出原有的密码 + * + * ! 问题描述:现已知加密后的密码还原出原有的密码 * * */ From fac36a33cc7a95898bbfdfc5f0f2143709eca09b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 28 Apr 2019 20:16:38 +0800 Subject: [PATCH 136/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=A1=BA=E6=97=B6?= =?UTF-8?q?=E9=92=88=E6=89=93=E5=8D=B0=E7=9F=A9=E9=98=B5=E7=9A=84=E7=BB=8F?= =?UTF-8?q?=E5=85=B8=E6=80=9D=E8=B7=AF=E8=A7=A3=E6=B3=95=E4=BB=A5=E5=8F=8A?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=A1=BA=E6=97=B6=E9=92=88=E6=97=8B=E8=BD=AC?= =?UTF-8?q?=E7=9F=A9=E9=98=B5=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rotateSquareMatrix.js | 42 +++++++++++++++ NowCoder/Leetcode/printMatrixbyClockwise.js | 52 ++++++++++++++++++- 2 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 Algorithms/basic_algorithm/applicationAlgorithms/rotateSquareMatrix.js diff --git a/Algorithms/basic_algorithm/applicationAlgorithms/rotateSquareMatrix.js b/Algorithms/basic_algorithm/applicationAlgorithms/rotateSquareMatrix.js new file mode 100644 index 0000000..6d80559 --- /dev/null +++ b/Algorithms/basic_algorithm/applicationAlgorithms/rotateSquareMatrix.js @@ -0,0 +1,42 @@ +/****** + * + * + * 将正方形矩阵顺时针旋转 90 度 + * + * 主要是明白 外面的一个框怎么旋转 + * + */ + +function rotateSquareMatrix(matrix) { + var lr = 0; + var lc = 0; + var rr = matrix.length - 1; + var rc = matrix[0].length - 1; + + this.rotateEdge = function (matrix, tlr, tlc, trr, trc){ + var allnum = trr - tlr; + var tempdata = 0; + for (let i = 0; i < allnum; i++) { + tempdata = matrix[tlr][tlc + i]; + matrix[tlr][tlc + i] = matrix[trr - i][tlc]; + matrix[trr - i][tlc] = matrix[trr][trc - i]; + matrix[trr][trc - i] = matrix[tlr + i][trc]; + matrix[tlr + i][trc] = tempdata; + } + } + + while (lr < rr){ + this.rotateEdge(matrix, lr++, lc++, rr--, rc--); + } + + return matrix; +} + + +var matrix = []; +matrix[0] = [1, 2, 3, 4]; +matrix[1] = [5, 6, 7, 8]; +matrix[2] = [9, 10, 11, 12]; +matrix[3] = [13, 14, 15, 16]; + +console.log(rotateSquareMatrix(matrix)); \ No newline at end of file diff --git a/NowCoder/Leetcode/printMatrixbyClockwise.js b/NowCoder/Leetcode/printMatrixbyClockwise.js index abc5c5c..0ceb732 100644 --- a/NowCoder/Leetcode/printMatrixbyClockwise.js +++ b/NowCoder/Leetcode/printMatrixbyClockwise.js @@ -46,6 +46,55 @@ function printMatrix(matrix) { return output; } + +// 使用经典思路解答矩阵打印问题 +function printMatrix2(matrix) { + var lr = 0,lc=0; // lr = left row, lc = left column 左上角开始的坐标 + var rr = matrix.length-1; // rr = right row + var rc = matrix[0].length-1; // rc = right column 右下角坐标 + var output = []; + + this.printEdge = function(matrix, tlr,tlc,trr,trc){ + if (tlr === trr) { + for (let i = tlc; i <=trc; i++) { + output.push(matrix[tlr][i]); + } + } else if (tlc === trc) { + for (let i = tlr; i <=trr; i++) { + output.push(matrix[i][tlc]); + } + } else { + var curlr = tlr; // 获取当前行 + var curlc = tlc; // 获取当前列 + while (curlc !== trc) { + output.push(matrix[tlr][curlc]); + curlc++; + } + while(curlr !== trr) { + output.push(matrix[curlr][trc]); + curlr++; + } + while(curlc !== tlc){ + output.push(matrix[trr][curlc]); + curlc--; + } + while(curlr !== tlr){ + output.push(matrix[curlr][tlc]); + curlr--; + } + } + } + + // 每次打印由左上角和右下角组成的一个框 + // 左上角的行 小于等于 右下角的行 左上角的列 小于等于 右下角的列 + while(lr <= rr && lc <= rc){ + this.printEdge(matrix, lr++, lc++, rr--, rc--); + } + return output; +} + + + var matrix = []; // matrix[0] = [1,2,3,4]; // matrix[1] = [5,6,7,8]; @@ -56,4 +105,5 @@ matrix[1] = [3,4]; matrix[2] = [5,6]; matrix[3] = [7,8]; -console.log(printMatrix(matrix)); \ No newline at end of file +console.log(printMatrix(matrix)); +console.log(printMatrix2(matrix)); \ No newline at end of file From cfee399575bcbee73d283545f23b69d4214c926f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 28 Apr 2019 21:56:00 +0800 Subject: [PATCH 137/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B9=8B=E5=AD=97?= =?UTF-8?q?=E5=BD=A2=E6=89=93=E5=8D=B0=E7=9F=A9=E9=98=B5=E7=9A=84=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 宏观代替微观解法,先分析现有的状况,简化条件 --- .../printMatrixbyZhiZi.js | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js diff --git a/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js b/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js new file mode 100644 index 0000000..e1b2224 --- /dev/null +++ b/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js @@ -0,0 +1,74 @@ +/****** + * + * 之字形打印矩阵 + * + * + * + */ + +// ! 解题思路:从宏观来看,可转换成已知矩阵右上与左下两点,打印对角线上的数 +// A,B 两点 A 向右走,遇到边向下走 +// B 点向下走,遇到边向右走 + +function printMatrixbyZhiZi(matrix){ + var lr = 0; + var lc = 0; + var rr = matrix.length-1; + var rc = matrix[0].length-1; + var a = [lr,lc]; + var b = [lr,lc]; + + var output = []; + var rttolb = true; // 用来标记是从右上向左下打印(true),还是从左下向右上打印(false) + + + this.printDiagonal = function (matrix, trr,trc,tlr,tlc, rtol) { + if (rtol) { + // 从 右上 到 左下 打印 + while (tlc <= trc && trr <= tlr) { + output.push(matrix[trr][trc]); + trr++; + trc--; + } + } else { + // 从 左下 到 右上 打印 + while (tlc <= trc && trr <= tlr) { + output.push(matrix[tlr][tlc]); + tlr--; + tlc++; + } + } + } + + this.printDiagonal(matrix, a[0], a[1], b[0], b[1], rttolb); + while(true){ + rttolb = !rttolb; + if (a[1] < rc) { + a[1] = a[1]+1; + } else if(a[1]===rc && a[0] < rr){ + a[0] = a[0] + 1; + } + + if (b[0] < rr) { + b[0] = b[0] + 1; + } else if (b[0] === rr && b[1] < rc){ + b[1] = b[1] + 1; + } + + + this.printDiagonal(matrix, a[0], a[1], b[0], b[1], rttolb); + if (a[0] === rr && a[1] === rc) { + break; + } + } + return output; + +} + +var matrix = []; +matrix[0] = [1, 2, 3, 4]; +matrix[1] = [5, 6, 7, 8]; +matrix[2] = [9, 10, 11, 12]; +matrix[3] = [13, 14, 15, 16]; + +console.log(printMatrixbyZhiZi(matrix)); \ No newline at end of file From 533bb0c3ddfb1592c556068b4aa24e567e2ccef0 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 29 Apr 2019 19:49:58 +0800 Subject: [PATCH 138/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=AE=80=E6=B4=81?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E7=9A=84=E4=B9=8B=E5=AD=97=E5=BD=A2=E6=89=93?= =?UTF-8?q?=E5=8D=B0=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../printMatrixbyZhiZi.js | 59 ++++++++++++++++--- 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js b/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js index e1b2224..65f5fa9 100644 --- a/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js +++ b/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js @@ -41,7 +41,7 @@ function printMatrixbyZhiZi(matrix){ } this.printDiagonal(matrix, a[0], a[1], b[0], b[1], rttolb); - while(true){ + while (a[0] !== rr) { rttolb = !rttolb; if (a[1] < rc) { a[1] = a[1]+1; @@ -54,12 +54,10 @@ function printMatrixbyZhiZi(matrix){ } else if (b[0] === rr && b[1] < rc){ b[1] = b[1] + 1; } - - this.printDiagonal(matrix, a[0], a[1], b[0], b[1], rttolb); - if (a[0] === rr && a[1] === rc) { - break; - } + // if (a[0] === rr && a[1] === rc) { + // break; + // } } return output; @@ -71,4 +69,51 @@ matrix[1] = [5, 6, 7, 8]; matrix[2] = [9, 10, 11, 12]; matrix[3] = [13, 14, 15, 16]; -console.log(printMatrixbyZhiZi(matrix)); \ No newline at end of file +console.log(printMatrixbyZhiZi(matrix)); + + +// 简洁版本的写法 +function printMatrixbyZhiZi2(matrix) { + var ar = 0; + var ac = 0; + var br = 0; + var bc = 0; + var endr = matrix.length - 1; + var endc = matrix[0].length - 1; + + + var output = []; + var rttolb = true; // 用来标记是从右上向左下打印(true),还是从左下向右上打印(false) + + + this.printDiagonal = function (matrix, trr, trc, tlr, tlc, rtol) { + if (rtol) { + // 从 右上 到 左下 打印 + while (tlc <= trc && trr <= tlr) { + output.push(matrix[trr][trc]); + trr++; + trc--; + } + } else { + // 从 左下 到 右上 打印 + while (tlc <= trc && trr <= tlr) { + output.push(matrix[tlr][tlc]); + tlr--; + tlc++; + } + } + } + + while(ar !== endr + 1){ + this.printDiagonal(matrix, ar, ac, br, bc, rttolb); + ar = ac === endc ? ar + 1 : ar; + ac = ac === endc ? ac : ac + 1; + bc = br === endr ? bc + 1 : bc; + br = br === endc ? br : br + 1; + rttolb = !rttolb; + } + + return output; +} + +console.log(printMatrixbyZhiZi2(matrix)); \ No newline at end of file From 13927ab684b0ed73eca6da4fd6b686bcbd45e697 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 29 Apr 2019 19:52:43 +0800 Subject: [PATCH 139/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=BD=92=E5=B9=B6?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=B1=82=E9=80=86=E5=BA=8F=E5=AF=B9=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/inversePairsNum.js | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 NowCoder/Leetcode/inversePairsNum.js diff --git a/NowCoder/Leetcode/inversePairsNum.js b/NowCoder/Leetcode/inversePairsNum.js new file mode 100644 index 0000000..f6c653c --- /dev/null +++ b/NowCoder/Leetcode/inversePairsNum.js @@ -0,0 +1,68 @@ +/***** + * + * 求数组逆序对总数 + * + * 在数组中的两个数字, 如果前面一个数字大于后面的数字, 则这两个数字组成一个逆序对。 输入一个数组, 求出这个数组中的逆序对的总数P。 + * + * 并将 P对 1000000007取模的结果输出。 即输出P % 1000000007 + * + * + */ + +// 解析:数组逆序对问题可以使用归并算法来解决 + +function InversePairs(data) { + if (data === null || data.length < 2) { + return; + } + + let count = 0; + this.sortProgress = function (arrays, Ln, Rn) { + if (Ln == Rn) { + return; + } + let midn = Ln + ((Rn - Ln) >> 1); + sortProgress(arrays, Ln, midn); + sortProgress(arrays, midn + 1, Rn); + this.merge(arrays, Ln, midn, Rn); + } + + this.merge = function (arrays, Ln, midn, Rn) { + let temparrays = new Array(); + let ti = 0; + let pone = Ln; + let ptwo = midn + 1; + while (pone <= midn && ptwo <= Rn) { + // outside sort, insert it which is small than another + if (arrays[pone] <= arrays[ptwo]) { + temparrays[ti++] = arrays[pone++]; + } else { + // 如果左边的有一个比 右边大,因为这样排序默认左边是从小到大排列,则此时有 midn - pone + 1 个数比 arrays[ptwo] 大 + count += midn - pone + 1; + temparrays[ti++] = arrays[ptwo++]; + } + } + + while (pone <= midn) { + temparrays[ti++] = arrays[pone++]; + } + + while (ptwo <= Rn) { + temparrays[ti++] = arrays[ptwo++]; + } + + for (let index = 0; index < temparrays.length; index++) { + arrays[Ln + index] = temparrays[index]; + } + } + + this.sortProgress(data, 0, data.length - 1); + // console.log(data); + return count % 1000000007; + +} + +// var data = [364, 637, 341, 406, 747, 995, 234, 971, 571, 219, 993, 407, 416, 366, 315, 301, 601, 650, 418, 355, 460, 505, 360, 965, 516, 648, 727, 667, 465, 849, 455, 181, 486, 149, 588, 233, 144, 174, 557, 67, 746, 550, 474, 162, 268, 142, 463, 221, 882, 576, 604, 739, 288, 569, 256, 936, 275, 401, 497, 82, 935, 983, 583, 523, 697, 478, 147, 795, 380, 973, 958, 115, 773, 870, 259, 655, 446, 863, 735, 784, 3, 671, 433, 630, 425, 930, 64, 266, 235, 187, 284, 665, 874, 80, 45, 848, 38, 811, 267, 575]; +var data = [1, 2, 3, 4, 5, 6, 7, 0]; + +console.log(InversePairs(data)); From 484145de4d2a14ac2d48f721128b8ba4db26612b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 29 Apr 2019 20:32:27 +0800 Subject: [PATCH 140/274] =?UTF-8?q?=E6=89=BE=E5=87=BA=20N=20=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E4=B8=AD=E6=9C=80=E5=B0=8F=E7=9A=84=20K=E4=B8=AA?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/getLeastNumbers_Solution.js | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 NowCoder/Leetcode/getLeastNumbers_Solution.js diff --git a/NowCoder/Leetcode/getLeastNumbers_Solution.js b/NowCoder/Leetcode/getLeastNumbers_Solution.js new file mode 100644 index 0000000..fa58ca9 --- /dev/null +++ b/NowCoder/Leetcode/getLeastNumbers_Solution.js @@ -0,0 +1,36 @@ +/****** + * + * 输入n个整数, 找出其中最小的K个数。 + * + * 例如输入4, 5, 1, 6, 2, 7, 3, 8 这8个数字, 则最小的4个数字是1, 2, 3, 4, 。 + * + * + */ + +// 基础方法实现 + +function GetLeastNumbers_Solution(input, k) { + if (input === null) { + return []; + } + if (input.length < k) { + return []; + } + let output = []; + input.sort(function(a,b){ + return a - b; + }) + for (let i = 0; i < k; i++) { + output.push(input[i]); + } + return output; +} + +let arr = [4, 5, 1, 6, 2, 7, 3, 8]; +console.log(GetLeastNumbers_Solution(arr, 8)); + +// 快速排序方法待补充 + + + +// 堆排序方法可以尝试 From 084441e3eb9ac9c79cedc58c186ece9b52dfac51 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 30 Apr 2019 13:58:32 +0800 Subject: [PATCH 141/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E6=A1=B6=E7=9A=84?= =?UTF-8?q?=E6=80=9D=E6=83=B3=E8=A7=A3=E5=86=B3=E6=89=BE=E5=87=BA=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E5=87=BA=E7=8E=B0=E7=9A=84=E6=AC=A1=E6=95=B0=E8=B6=85?= =?UTF-8?q?=E8=BF=87=E6=95=B0=E7=BB=84=E9=95=BF=E5=BA=A6=E7=9A=84=E4=B8=80?= =?UTF-8?q?=E5=8D=8A=E7=9A=84=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/moreThanHalfNum_Solution.js | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 NowCoder/Leetcode/moreThanHalfNum_Solution.js diff --git a/NowCoder/Leetcode/moreThanHalfNum_Solution.js b/NowCoder/Leetcode/moreThanHalfNum_Solution.js new file mode 100644 index 0000000..2a3a806 --- /dev/null +++ b/NowCoder/Leetcode/moreThanHalfNum_Solution.js @@ -0,0 +1,34 @@ +/****** + * + * + * 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 + * 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。 + * 如果不存在则输出0。 + * + * + */ + +function MoreThanHalfNum_Solution(numbers) { + // write code here + if (numbers.length <=0) { + return null; + } + if (numbers.length === 1) { + return numbers[0]; + } + var countArr = []; + for (let i = 0; i < numbers.length; i++) { + if (countArr[numbers[i]]) { + countArr[numbers[i]] = countArr[numbers[i]] + 1; + if (countArr[numbers[i]] > numbers.length/2) { + return numbers[i]; + } + } else { + countArr[numbers[i]] = 1; + } + } + return 0; +} + +let numbers = [1, 2, 3, 2, 2, 2, 5, 4, 2]; +console.log(MoreThanHalfNum_Solution(numbers)); \ No newline at end of file From 78d2d199bbdc0a8b7b1f80d03c4f5aca254ee89b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 30 Apr 2019 14:17:59 +0800 Subject: [PATCH 142/274] =?UTF-8?q?=E8=BF=98=E6=98=AF=E7=94=A8=E6=A1=B6?= =?UTF-8?q?=E7=9A=84=E6=80=9D=E6=83=B3=E8=A7=A3=E5=86=B3=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E4=B8=AD=E7=AC=AC=E4=B8=80=E6=AC=A1=E5=8F=AA=E5=87=BA?= =?UTF-8?q?=E7=8E=B0=E4=B8=80=E6=AC=A1=E5=AD=97=E7=AC=A6=E7=9A=84=E4=BD=8D?= =?UTF-8?q?=E7=BD=AE=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/firstNotRepeatingChar.js | 33 ++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 NowCoder/Leetcode/firstNotRepeatingChar.js diff --git a/NowCoder/Leetcode/firstNotRepeatingChar.js b/NowCoder/Leetcode/firstNotRepeatingChar.js new file mode 100644 index 0000000..ebbb73f --- /dev/null +++ b/NowCoder/Leetcode/firstNotRepeatingChar.js @@ -0,0 +1,33 @@ +/******* + * + * + * 在一个字符串(0 <= 字符串长度 <= 10000, 全部由字母组成) + * 中找到第一个只出现一次的字符, 并返回它的位置, + * 如果没有则返回 - 1( 需要区分大小写). + * + * + */ + +function FirstNotRepeatingChar(str) { + if (str.length <= 0 || str === '' || str === null) { + return -1; + } + + let countArr = []; + for (let i = 0; i <= str.length-1; i++) { + if (countArr[str[i]]) { + countArr[str[i]] = countArr[str[i]] + 1; + } else { + countArr[str[i]] = 1; + } + } + for (let j = 0; j <= str.length-1; j++) { + if (countArr[str[j]] === 1) { + return j; + } + } + return -1; +} + +let str = 'asdfdjdniasdan'; +console.log(FirstNotRepeatingChar(str)); \ No newline at end of file From 9cf0204534f807bb339dce1c9d5e7a17479aeb3e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 30 Apr 2019 14:46:50 +0800 Subject: [PATCH 143/274] =?UTF-8?q?=E6=9A=B4=E5=8A=9B=E8=A7=A3=E6=B3=95?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=89=BE=E5=87=BA=E4=B8=A4=E4=B8=AA=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9A=84=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E7=BB=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Leetcode/findFirstCommonNodeofLinkNode.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 NowCoder/Leetcode/findFirstCommonNodeofLinkNode.js diff --git a/NowCoder/Leetcode/findFirstCommonNodeofLinkNode.js b/NowCoder/Leetcode/findFirstCommonNodeofLinkNode.js new file mode 100644 index 0000000..828f452 --- /dev/null +++ b/NowCoder/Leetcode/findFirstCommonNodeofLinkNode.js @@ -0,0 +1,33 @@ +/***** + * + * 输入两个链表,找出它们的第一个公共结点。 + * + * + */ + +function ListNode(x){ + this.val = x; + this.next = null; +} + +// 初级解法:暴力解法 把1个链表所有的节点先用数组存起来,然后每个节点与另一个链表进行比较 + +function FindFirstCommonNode(pHead1, pHead2) { + // write code here + let current1 = []; + + while(pHead1 !== null) { + current1.push(pHead1); + pHead1 = pHead1.next; + } + + while (pHead2 !== null) { + for (let i = 0; i < current1.length; i++) { + if (pHead2 === current1[i]) { + return pHead2; + } + } + pHead2 = pHead2.next; + } + return null; +} \ No newline at end of file From 18f05bb861470143df4d0344da35f4fd7d1fa207 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 30 Apr 2019 16:22:15 +0800 Subject: [PATCH 144/274] =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E5=9C=A8=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E4=B8=AD=E5=87=BA=E7=8E=B0=E7=9A=84=E6=AC=A1=E6=95=B0=20?= =?UTF-8?q?=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE=E7=9A=84=E9=80=92=E5=BD=92?= =?UTF-8?q?=E4=B8=8E=E9=9D=9E=E9=80=92=E5=BD=92=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/getNumberOfK.js | 106 ++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 NowCoder/Leetcode/getNumberOfK.js diff --git a/NowCoder/Leetcode/getNumberOfK.js b/NowCoder/Leetcode/getNumberOfK.js new file mode 100644 index 0000000..9d0f5a8 --- /dev/null +++ b/NowCoder/Leetcode/getNumberOfK.js @@ -0,0 +1,106 @@ +/***** + * + * 统计一个数字在排序数组中出现的次数。 + * + * + */ + +function GetNumberOfK(data, k) { + // write code here + if (data.length === 0) { + return 0; + } + let dataLen = data.length; + + // 使用二分查找的方法确定 数组的首位 + this.getNumLeft = function(data, k, ln, rn){ + if (ln > rn) { + return -1; + } + let midn = (rn + ln) >> 1; + if (data[midn] > k) { + return this.getNumLeft(data, k, ln, midn - 1); + } else if(data[midn] < k) { + return this.getNumLeft(data, k, midn + 1, rn); + } else if (midn-1 >= ln && data[midn-1] === k) { + return this.getNumLeft(data, k, ln, midn - 1); + } else { + return midn; + } + } + + // 左侧二分查找的非递归写法 + this.getNumLeftNonrecurrent = function (data, k, ln, rn) { + if (ln > rn) { + return -1; + } + let midn = (ln + rn) >> 1; + while (ln <= rn) { + if (data[midn] > k) { + rn = midn - 1; + } else if (data[midn] < k) { + ln = midn + 1; + } else if (midn - 1 >= ln && data[midn - 1] === k) { + rn = midn - 1; + } else { + return midn; + } + midn = (ln + rn) >> 1; + } + return -1; + } + + this.getNumRight = function (data, k, ln, rn) { + if (ln > rn) { + return -1; + } + let midn = (rn + ln) >> 1; + if (data[midn] > k) { + return this.getNumRight(data, k, ln, midn - 1); + } else if (data[midn] < k) { + return this.getNumRight(data, k, midn + 1, rn); + } else if (midn+1 <= rn && data[midn + 1] === k) { + return this.getNumRight(data, k, midn + 1, rn); + } else { + return midn; + } + } + + // 二分查找的非递归写法 + this.getNumRightNonrecurrent = function (data, k, ln, rn) { + if (ln > rn){ + return -1; + } + let midn = (ln + rn) >> 1; + let end = data.length - 1; + while(ln <= rn){ + if (data[midn] > k) { + rn = midn - 1; + } else if (data[midn] < k) { + ln = midn + 1; + } else if (midn + 1 <= rn && data[midn + 1] === k){ + ln = midn + 1; + } else { + return midn; + } + midn = (ln + rn) >> 1; + } + return -1; + } + + + let left = this.getNumLeft(data, k, 0, dataLen - 1); + let right = this.getNumRight(data, k, 0, dataLen - 1); + // let left = this.getNumLeftNonrecurrent(data, k, 0, dataLen - 1); + // let right = this.getNumRightNonrecurrent(data, k, 0, dataLen - 1); + if (left >= 0 && right <= dataLen-1) { + return right - left + 1; + } + return 0; + +} + +let data = [1,2,3,3,3,3,3,3,4,5,6,7,8]; +let data2 = [3,3,3,3,3,3,3,3,3,3,3,3,3]; +let k = 3; +console.log(GetNumberOfK(data, k)); \ No newline at end of file From 298ef658cb0a6ad306b8a4b4da6349c7d42c171c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 30 Apr 2019 22:08:39 +0800 Subject: [PATCH 145/274] =?UTF-8?q?=E6=B1=821+2+3+...+n=20=E4=BA=8C?= =?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BE=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/strToInt.js | 21 +++++++++++++ NowCoder/Leetcode/sum_Solution.js | 50 +++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 NowCoder/Leetcode/strToInt.js create mode 100644 NowCoder/Leetcode/sum_Solution.js diff --git a/NowCoder/Leetcode/strToInt.js b/NowCoder/Leetcode/strToInt.js new file mode 100644 index 0000000..c4a1df6 --- /dev/null +++ b/NowCoder/Leetcode/strToInt.js @@ -0,0 +1,21 @@ +/****** + * + * 将一个字符串转换成一个整数(实现Integer.valueOf(string) 的功能, + * 但是string不符合数字要求时返回0), + * 要求不能使用字符串转换整数的库函数。 + * 数值为0或者字符串不是一个合法的数值则返回0。 + * + * + * + */ + +function StrToInt(str) { + + if (str === null || str.length === 0 || str === '+' || str === '-') { + return 0; + } + let start = 0; + let pn = 0; // 用于判断该数是正是负 + + +} \ No newline at end of file diff --git a/NowCoder/Leetcode/sum_Solution.js b/NowCoder/Leetcode/sum_Solution.js new file mode 100644 index 0000000..51b2224 --- /dev/null +++ b/NowCoder/Leetcode/sum_Solution.js @@ -0,0 +1,50 @@ +/***** + * + * 求1+2+3+...+n, + * 要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C) + * + * + */ + +// 逻辑与的 短路求值原理 +// 即:&& 符号 前面如果为 false 后面就不计算 所以减到 0 之后就不会继续调用 + +function Sum_Solution(n) { + let result = n; + let state = result && (result += Sum_Solution(n-1)); + return result; +} + +console.log(Sum_Solution(4)); + +// 使用 Math 运算 模拟 n*(n+1)/2 + +function Sum_Solution2(n) { + let result = n; + result = (Math.pow(n,2) + n) >> 1; + return result; +} + +console.log(Sum_Solution2(4)); + +// 使用 递归 和 位运算模拟 n*(n+1)/2 + +function Sum_Solution3(n) { + let result = 0; + + // 用位运算模拟两个数的乘法 + this.multify = function(a, b){ + let res = 0; + let state1 = ((a & 1) === 1) && (res += b) > 0; + a = a >> 1; + b = b << 1; + let state2 = (a !== 0) && (res += this.multify(a, b)) > 0; + return res; + } + + result = this.multify(n,n+1); + result >>= 1; + return result; +} + +console.log(Sum_Solution3(4)); \ No newline at end of file From 7220f7cf1480f490b404e0d5773e0e302066113d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 1 May 2019 14:50:19 +0800 Subject: [PATCH 146/274] =?UTF-8?q?=E5=B0=86=E4=B8=80=E4=B8=AA=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E8=BD=AC=E6=8D=A2=E6=88=90=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=95=B4=E6=95=B0=E7=9A=84=E8=A7=A3=E5=86=B3=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/strToInt.js | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/NowCoder/Leetcode/strToInt.js b/NowCoder/Leetcode/strToInt.js index c4a1df6..9590836 100644 --- a/NowCoder/Leetcode/strToInt.js +++ b/NowCoder/Leetcode/strToInt.js @@ -9,6 +9,8 @@ * */ +// 后续可以加上是否溢出的判断 + function StrToInt(str) { if (str === null || str.length === 0 || str === '+' || str === '-') { @@ -16,6 +18,28 @@ function StrToInt(str) { } let start = 0; let pn = 0; // 用于判断该数是正是负 + if (str[0] === '+'){ + pn = 0; + }else if (str[0] === '-') { + pn = 1; + } else if (str[0] < '0' || str[0] > '9') { + return 0; + }else { + start = str[0] - '0'; + } + let i = 1; + while (str[i]) { + if (str[i] >= '0' && str[i] <= '9') { + start = start * 10 + (str[i] - '0'); + } else { + return 0; + } + i++; + } + start = pn === 1? -1*start:start; + return start; +} - -} \ No newline at end of file +let str = '+2147483647'; +let str1 = '1a33'; +console.log(StrToInt(str1)); \ No newline at end of file From 078c3a357399d2656541242ea2140d3f984d01fa Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 1 May 2019 15:08:48 +0800 Subject: [PATCH 147/274] =?UTF-8?q?=E6=89=BE=E5=87=BA=E9=80=92=E5=A2=9E?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E4=B8=AD=E5=92=8C=E4=B8=BA=20S=20=E7=9A=84?= =?UTF-8?q?=E4=B8=A4=E4=B8=AA=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/findNumbersWithSum.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/NowCoder/Leetcode/findNumbersWithSum.js b/NowCoder/Leetcode/findNumbersWithSum.js index 9f3438a..d86d20d 100644 --- a/NowCoder/Leetcode/findNumbersWithSum.js +++ b/NowCoder/Leetcode/findNumbersWithSum.js @@ -8,8 +8,28 @@ ***/ // ! 本质涉及: 排序算法 +// ! 和均为S的两个数,乘积最小的数在递增序列的两侧 + function FindNumbersWithSum(array, sum) { // write code here + let result = []; + if (array.length <= 1) { + return result; + } + let i = 0; + let j = array.length -1; + while(i < j){ + if (array[i] + array[j] === sum) { + result.push(array[i]); + result.push(array[j]); + break; + } else if (array[i] + array[j] < sum) { + i++; + } else { + j--; + } + } + return result; } // Test Algorithm From cbdbbfc6620536a390af2c8bf821d56adbfaab56 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 1 May 2019 18:48:56 +0800 Subject: [PATCH 148/274] =?UTF-8?q?=E6=89=BE=E5=87=BA=E6=89=80=E6=9C=89?= =?UTF-8?q?=E5=92=8C=E4=B8=BAS=E7=9A=84=E8=BF=9E=E7=BB=AD=E6=AD=A3?= =?UTF-8?q?=E6=95=B0=E5=BA=8F=E5=88=97=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/findContinuousSequence.js | 44 +++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 NowCoder/Leetcode/findContinuousSequence.js diff --git a/NowCoder/Leetcode/findContinuousSequence.js b/NowCoder/Leetcode/findContinuousSequence.js new file mode 100644 index 0000000..38e5a7b --- /dev/null +++ b/NowCoder/Leetcode/findContinuousSequence.js @@ -0,0 +1,44 @@ +/****** + * + * 小明很喜欢数学, 有一天他在做数学作业时, 要求计算出9~16 的和, 他马上就写出了正确答案是100。 + * 但是他并不满足于此, 他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。 + * 没多久, 他就得到另一组连续正数和为100的序列: 18, 19, 20, 21, 22。 + * 现在把问题交给你, 你能不能也很快的找出所有和为S的连续正数序列 ? Good Luck! + * + * + * 输出所有和为S的连续正数序列。 序列内按照从小至大的顺序, 序列间按照开始数字从小到大的顺序 + * + */ + +// 算法复杂度 O(n^2) 解法 + +function FindContinuousSequence(sum) { + let output = []; + if (sum <= 0) { + return output; + } + let count = 0; + for (let i = 1; i <=sum; i++) { + let sumArr = 0; + for (let j = i; j <= sum; j++) { + sumArr+=j; + if (sumArr === sum) { + if (j > i) { + output[count] = []; + let tempstart = i; + for (let k = 0; k <= j - i; k++) { + output[count][k] = tempstart++; + } + count++; + break; + } + } + + } + } + return output; +} + +// let sum = 1; +let sum = 100; +console.log(FindContinuousSequence(sum)); \ No newline at end of file From fdce83315da1d9b308a1676285bcb415bccb9e08 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 1 May 2019 19:02:53 +0800 Subject: [PATCH 149/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=89=BE=E5=87=BA?= =?UTF-8?q?=E6=89=80=E6=9C=89=E5=92=8C=E4=B8=BAS=E7=9A=84=E8=BF=9E?= =?UTF-8?q?=E7=BB=AD=E6=AD=A3=E6=95=B0=E5=BA=8F=E5=88=97=20=E5=8F=8C?= =?UTF-8?q?=E6=8C=87=E9=92=88=E6=80=9D=E8=B7=AF=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/findContinuousSequence.js | 34 ++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/NowCoder/Leetcode/findContinuousSequence.js b/NowCoder/Leetcode/findContinuousSequence.js index 38e5a7b..7050b9f 100644 --- a/NowCoder/Leetcode/findContinuousSequence.js +++ b/NowCoder/Leetcode/findContinuousSequence.js @@ -41,4 +41,36 @@ function FindContinuousSequence(sum) { // let sum = 1; let sum = 100; -console.log(FindContinuousSequence(sum)); \ No newline at end of file +console.log(FindContinuousSequence(sum)); + +// 双指针思路解法,算法复杂度较低 + +function FindContinuousSequence2(sum) { + let output = []; + if (sum <= 0) { + return output; + } + let left = 1; + let right = 2; + while(left < right){ + let currentSum = (left + right)*(right - left + 1)/2; + if (currentSum < sum) { + right++; + } + if (currentSum === sum) { + let list = []; + for (let i = left; i <=right; i++) { + list.push(i); + } + output.push(list); + left++; + } + if (currentSum > sum) { + left++; + } + } + return output; +} + +let sum2 = 100; +console.log(FindContinuousSequence2(sum2)); \ No newline at end of file From 6f7ec07a72f8fd7179664fc18f89c8cf54c2499c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 1 May 2019 19:46:05 +0800 Subject: [PATCH 150/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E8=B0=83=E6=95=B4?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E6=96=B9=E6=B3=95=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E5=9C=86=E5=9C=88=E4=B8=AD=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/lastRemaining_Solution.js | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 NowCoder/Leetcode/lastRemaining_Solution.js diff --git a/NowCoder/Leetcode/lastRemaining_Solution.js b/NowCoder/Leetcode/lastRemaining_Solution.js new file mode 100644 index 0000000..695b608 --- /dev/null +++ b/NowCoder/Leetcode/lastRemaining_Solution.js @@ -0,0 +1,62 @@ +/****** + * + * 圆圈中最后一个数 + * + * 每年六一儿童节, 牛客都会准备一些小礼物去看望孤儿院的小朋友, 今年亦是如此。 HF作为牛客的资深元老, 自然也准备了一些小游戏。 + * 其中, 有个游戏是这样的: + * 首先, 让小朋友们围成一个大圈。 然后, 他随机指定一个数m, 让编号为0的小朋友开始报数。 + * 每次喊到m - 1 的那个小朋友要出列唱首歌, 然后可以在礼品箱中任意的挑选礼物, 并且不再回到圈中, + * 从他的下一个小朋友开始, 继续0...m - 1 报数....这样下去....直到剩下最后一个小朋友, + * 最后一个小朋友可以不用表演, 并且拿到牛客名贵的“ 名侦探柯南” 典藏版(名额有限哦!! ^ _ ^ )。 + * + * 请你试着想下, 哪个小朋友会得到这份礼品呢?(注: 小朋友的编号是从0到n - 1) + * + * + * + */ + +// 思路转换成找拿到礼物先后顺序的序列 (0 ~ n-1) + +function LastRemaining_Solution(n, m) { + if (n===0 || m===0) { + return -1; + } + let giftList = []; + let children = []; + let tempLen = 0; + for (let i = 0; i < n; i++) { + children.push(i); + } + this.adjustArr = function (arr, tempNo) { + let tempTable = []; + for (let k = 0; k < arr.length; k++) { + if (k > tempNo) { + tempTable.push(arr[k]); + } + } + for (let j = 0; j < tempNo; j++) { + tempTable.push(arr[j]); + } + return tempTable; + } + for (let i = 0; i < n; i++) { + tempLen = children.length; + let tempWho = 0; + if (m >= tempLen) { + tempWho = (m-1) % tempLen; + } else { + tempWho = m-1; + } + giftList.push(children[tempWho]); + children = this.adjustArr(children, tempWho); + // console.log(children); + } + + + return giftList[giftList.length - 1]; + // return giftList; +} + +let n = 5; +let m = 2; +console.log(LastRemaining_Solution(n, m)); \ No newline at end of file From 8d64c42c19df32118ab083b4e3e895184ab551c5 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 1 May 2019 22:17:48 +0800 Subject: [PATCH 151/274] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E4=B8=AD=E9=87=8D=E5=A4=8D=E7=9A=84=E7=BB=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 107 +++++++++++++----- .../Leetcode/deleteDuplicationLinkNode.js | 57 ++++++++++ 2 files changed, 136 insertions(+), 28 deletions(-) create mode 100644 NowCoder/Leetcode/deleteDuplicationLinkNode.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 5c3eb10..25ab7fa 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -5,9 +5,9 @@ * */ -const arrayToTreeNode = require('./tools/treeNode'); -// const arrayToLinkNode = require('./tools/LinkNode'); -// const linkToArray = require('./tools/LinkNodetoArray'); +// const arrayToTreeNode = require('./tools/treeNode'); +const arrayToLinkNode = require('./tools/LinkNode'); +const linkToArray = require('./tools/LinkNodetoArray'); // function TreeDepth(pRoot) { // // write code here @@ -116,40 +116,91 @@ function TreeNode(x) { // 考虑使用层次遍历法 -function PrintFromTopToBottom(root) { - // write code here - if (root === null) { - return []; +// function PrintFromTopToBottom(root) { +// // write code here +// if (root === null) { +// return []; +// } +// let tempList = []; +// let outprint = []; +// tempList.push(root); +// while (tempList.length !== 0) { +// let tempNode = tempList[0]; +// outprint.push(tempNode.val); +// tempList = tempList.slice(1); +// if (tempNode.left !== null) { +// tempList.push(tempNode.left); +// } +// if (tempNode.right !== null) { +// tempList.push(tempNode.right); +// } +// } +// return outprint; + +// } + +function ListNode(x) { + this.val = x; + this.next = null; +} + +function deleteDuplication(pHead) { + + if (pHead === null) { + return null; } - let tempList = []; - let outprint = []; - tempList.push(root); - while (tempList.length !== 0) { - let tempNode = tempList[0]; - outprint.push(tempNode.val); - tempList = tempList.slice(1); - if (tempNode.left !== null) { - tempList.push(tempNode.left); - } - if (tempNode.right !== null) { - tempList.push(tempNode.right); + let backLink = pHead; + let sameVal = []; + let current = pHead; + + // 找出链表值重复的节点的值 + while (current.next) { + let currVal = current.val; + current = current.next; + if (currVal == current.val && sameVal.indexOf(currVal) === -1) { + sameVal.push(currVal); } } - return outprint; + // 删除重复数组里的值的链表节点 + let position = 0; + let backHead; + while (backLink) { + + let currNode; + if (sameVal.indexOf(backLink.val) === -1) { + if (position === 0) { + backHead = new ListNode(backLink.val); + currNode = backHead; + position++; + } else { + currNode = backHead; + while (currNode.next) { + currNode = currNode.next; + } + currNode.next = new ListNode(backLink.val); + } + } + backLink = backLink.next; + } + return backHead; } -let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; -let arr2 = [1, 2, 3, 4, 5]; -var tempLink1 = arrayToTreeNode(arr1); -var tempLink2 = arrayToTreeNode(arr2); +let arr1 = [1, 2, 2, 3, 3, 4, 5, 6, 6,7]; +// let arr2 = [1, 2, 3, 4, 5]; + +var tempLink1 = arrayToLinkNode(arr1); +// var tempLink2 = arrayToTreeNode(arr2); +console.log(tempLink1); + +tempLink1 = deleteDuplication(tempLink1); console.log(tempLink1); -console.log(tempLink2); -var list1 = PrintFromTopToBottom(tempLink1); +// console.log(tempLink2); +var list1 = linkToArray(tempLink1); console.log(list1); -var list2 = PrintFromTopToBottom(tempLink2); -console.log(list2); +// var list2 = PrintFromTopToBottom(tempLink2); +// console.log(list2); diff --git a/NowCoder/Leetcode/deleteDuplicationLinkNode.js b/NowCoder/Leetcode/deleteDuplicationLinkNode.js new file mode 100644 index 0000000..abcad44 --- /dev/null +++ b/NowCoder/Leetcode/deleteDuplicationLinkNode.js @@ -0,0 +1,57 @@ +/****** + * + * 删除链表中重复的节点 + * + * 在一个排序的链表中, 存在重复的结点, 请删除该链表中重复的结点, 重复的结点不保留, 返回链表头指针。 + * + * 例如, 链表1 - > 2 - > 3 - > 3 - > 4 - > 4 - > 5 处理后为 1 - > 2 - > 5 + * + * + */ + + +function ListNode(x){ +this.val = x; +this.next = null; +} +function deleteDuplication(pHead) { + + if (pHead === null) { + return null; + } + let backLink = pHead; + let sameVal = []; + let current = pHead; + + // 找出链表值重复的节点的值 + while (current.next) { + let currVal = current.val; + current = current.next; + if (currVal == current.val && sameVal.indexOf(currVal) === -1) { + sameVal.push(currVal); + } + } + + // 删除重复数组里的值的链表节点 + let position = 0; + let backHead; + while (backLink) { + + let currNode; + if (sameVal.indexOf(backLink.val) === -1) { + if (position === 0) { + backHead = new ListNode(backLink.val); + currNode = backHead; + position++; + } else { + currNode = backHead; + while (currNode.next) { + currNode = currNode.next; + } + currNode.next = new ListNode(backLink.val); + } + } + backLink = backLink.next; + } + return backHead; +} \ No newline at end of file From 7e1ce2391be49a71ddcef2048931cf7fc5e412bd Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 2 May 2019 15:52:37 +0800 Subject: [PATCH 152/274] =?UTF-8?q?=E4=B9=8B=E5=AD=97=E5=BD=A2=E6=89=93?= =?UTF-8?q?=E5=8D=B0=E4=BA=8C=E5=8F=89=E6=A0=91=E4=BD=BF=E7=94=A8=E6=80=9D?= =?UTF-8?q?=E6=83=B3=E6=97=B6=E5=A5=87=E5=81=B6=E8=A1=8C=E5=88=86=E5=88=AB?= =?UTF-8?q?=E5=AD=98=E5=85=A5=E5=90=84=E8=87=AA=E7=9A=84=E5=A0=86=E6=A0=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 165 ++++++++++++++++-------- NowCoder/Leetcode/printTreewithZhizi.js | 71 ++++++++++ 2 files changed, 183 insertions(+), 53 deletions(-) create mode 100644 NowCoder/Leetcode/printTreewithZhizi.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 25ab7fa..f57f562 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -5,9 +5,9 @@ * */ -// const arrayToTreeNode = require('./tools/treeNode'); -const arrayToLinkNode = require('./tools/LinkNode'); -const linkToArray = require('./tools/LinkNodetoArray'); +const arrayToTreeNode = require('./tools/treeNode'); +// const arrayToLinkNode = require('./tools/LinkNode'); +// const linkToArray = require('./tools/LinkNodetoArray'); // function TreeDepth(pRoot) { // // write code here @@ -108,11 +108,11 @@ const linkToArray = require('./tools/LinkNodetoArray'); // return tempState; // } -function TreeNode(x) { - this.val = x; - this.left = null; - this.right = null; -} +// function TreeNode(x) { +// this.val = x; +// this.left = null; +// this.right = null; +// } // 考虑使用层次遍历法 @@ -139,66 +139,125 @@ function TreeNode(x) { // } -function ListNode(x) { - this.val = x; - this.next = null; -} +// function ListNode(x) { +// this.val = x; +// this.next = null; +// } -function deleteDuplication(pHead) { +// function deleteDuplication(pHead) { - if (pHead === null) { - return null; - } - let backLink = pHead; - let sameVal = []; - let current = pHead; - - // 找出链表值重复的节点的值 - while (current.next) { - let currVal = current.val; - current = current.next; - if (currVal == current.val && sameVal.indexOf(currVal) === -1) { - sameVal.push(currVal); - } +// if (pHead === null) { +// return null; +// } +// let backLink = pHead; +// let sameVal = []; +// let current = pHead; + +// // 找出链表值重复的节点的值 +// while (current.next) { +// let currVal = current.val; +// current = current.next; +// if (currVal == current.val && sameVal.indexOf(currVal) === -1) { +// sameVal.push(currVal); +// } +// } + +// // 删除重复数组里的值的链表节点 +// let position = 0; +// let backHead; +// while (backLink) { + +// let currNode; +// if (sameVal.indexOf(backLink.val) === -1) { +// if (position === 0) { +// backHead = new ListNode(backLink.val); +// currNode = backHead; +// position++; +// } else { +// currNode = backHead; +// while (currNode.next) { +// currNode = currNode.next; +// } +// currNode.next = new ListNode(backLink.val); +// } +// } +// backLink = backLink.next; +// } +// return backHead; +// } + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function Print(pRoot) +{ + let output = []; + if (pRoot === null){ + return output; } + let oddArr = []; // 奇数行的结点 + let evenArr = []; // 偶数行的结点 + oddArr.push(pRoot); + let currentlayer = 1; - // 删除重复数组里的值的链表节点 - let position = 0; - let backHead; - while (backLink) { - - let currNode; - if (sameVal.indexOf(backLink.val) === -1) { - if (position === 0) { - backHead = new ListNode(backLink.val); - currNode = backHead; - position++; - } else { - currNode = backHead; - while (currNode.next) { - currNode = currNode.next; + while(oddArr.length !== 0 || evenArr.length !== 0){ + if (currentlayer %2 !== 0){ + let tempArr = []; + while(oddArr.length !== 0){ + let tempNode = oddArr.pop(); + if (tempNode !== null){ + tempArr.push(tempNode.val); + if (tempNode.left !== null){ + evenArr.push(tempNode.left); + } + if (tempNode.right !== null) { + evenArr.push(tempNode.right); + } } - currNode.next = new ListNode(backLink.val); + } + if (tempArr.length !== 0){ + output.push(tempArr); + currentlayer++; + } + } else { + let tempArr = []; + while(evenArr.length !== 0){ + let tempNode = evenArr.pop(); + if (tempNode !== null){ + if (tempNode.right !== null) { + oddArr.push(tempNode.right); + } + tempArr.push(tempNode.val); + if (tempNode.left !== null){ + oddArr.push(tempNode.left); + } + } + } + if (tempArr.length !== 0){ + output.push(tempArr); + currentlayer++; } } - backLink = backLink.next; } - return backHead; -} + return output; +} -let arr1 = [1, 2, 2, 3, 3, 4, 5, 6, 6,7]; +let arr1 = [1, 1, 2, 3, 3, 4, 5]; // let arr2 = [1, 2, 3, 4, 5]; -var tempLink1 = arrayToLinkNode(arr1); +// var tempLink1 = arrayToLinkNode(arr1); // var tempLink2 = arrayToTreeNode(arr2); -console.log(tempLink1); +var tempTree = arrayToTreeNode(arr1); +console.log(tempTree); -tempLink1 = deleteDuplication(tempLink1); -console.log(tempLink1); +tempTreeArr = Print(tempTree); +console.log(tempTreeArr); // console.log(tempLink2); -var list1 = linkToArray(tempLink1); -console.log(list1); +// var list1 = linkToArray(tempLink1); +// console.log(list1); // var list2 = PrintFromTopToBottom(tempLink2); // console.log(list2); diff --git a/NowCoder/Leetcode/printTreewithZhizi.js b/NowCoder/Leetcode/printTreewithZhizi.js new file mode 100644 index 0000000..3566d77 --- /dev/null +++ b/NowCoder/Leetcode/printTreewithZhizi.js @@ -0,0 +1,71 @@ +/******* + * + * 请实现一个函数按照之字形打印二叉树, + * 即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。 + * + * + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function Print(pRoot) +{ + let output = []; + if (pRoot === null){ + return output; + } + let oddArr = []; // 奇数行的结点 + let evenArr = []; // 偶数行的结点 + oddArr.push(pRoot); + let currentlayer = 1; + + while(oddArr.length !== 0 || evenArr.length !== 0){ + if (currentlayer %2 !== 0){ + let tempArr = []; + while(oddArr.length !== 0){ + // 使用栈的思想先进后出,奇数行压入时先压入的是右侧的,弹出时弹出的是先是左侧的 + let tempNode = oddArr.pop(); + if (tempNode !== null){ + tempArr.push(tempNode.val); + // 奇数层的子节点要压入偶数层 + if (tempNode.left !== null){ + evenArr.push(tempNode.left); + } + if (tempNode.right !== null) { + evenArr.push(tempNode.right); + } + } + } + if (tempArr.length !== 0){ + output.push(tempArr); + currentlayer++; + } + } else { + let tempArr = []; + while(evenArr.length !== 0){ + // 偶数行压入时先压入的是左侧的,弹出时弹出的是先是右侧的 + let tempNode = evenArr.pop(); + if (tempNode !== null){ + tempArr.push(tempNode.val); + // 偶数层的子节点要压入奇数层 + if (tempNode.right !== null) { + oddArr.push(tempNode.right); + } + if (tempNode.left !== null){ + oddArr.push(tempNode.left); + } + } + } + if (tempArr.length !== 0){ + output.push(tempArr); + currentlayer++; + } + } + } + return output; + +} \ No newline at end of file From a3d391eb30fe59a131e63bb4eb6a02a2bc852a0c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 2 May 2019 16:09:50 +0800 Subject: [PATCH 153/274] =?UTF-8?q?=E4=BB=8E=E4=B8=8A=E5=88=B0=E4=B8=8B?= =?UTF-8?q?=E6=8C=89=E5=B1=82=E6=89=93=E5=8D=B0=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E6=AF=8F=E4=B8=80=E5=B1=82=E8=BE=93=E5=87=BA=E4=B8=80=E8=A1=8C?= =?UTF-8?q?=E5=A5=87=E5=81=B6=E8=A1=8C=E8=A7=A3=E5=86=B3=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 53 ++++++++++----------- NowCoder/Leetcode/printTreebyLayer.js | 66 +++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 26 deletions(-) create mode 100644 NowCoder/Leetcode/printTreebyLayer.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index f57f562..3531290 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -193,55 +193,56 @@ function TreeNode(x) { } function Print(pRoot) { - let output = []; + let outPrint = []; if (pRoot === null){ - return output; + return outPrint; } - let oddArr = []; // 奇数行的结点 - let evenArr = []; // 偶数行的结点 - oddArr.push(pRoot); - let currentlayer = 1; + let oddLine = []; + let evenLine = []; + oddLine.push(pRoot); + let currentOdd = true; - while(oddArr.length !== 0 || evenArr.length !== 0){ - if (currentlayer %2 !== 0){ + while(oddLine.length !== 0 || evenLine.length !== 0){ + if (currentOdd){ let tempArr = []; - while(oddArr.length !== 0){ - let tempNode = oddArr.pop(); - if (tempNode !== null){ + while(oddLine.length !== 0){ + let tempNode = oddLine[0]; + oddLine = oddLine.slice(1); + if (tempNode !== null) { tempArr.push(tempNode.val); if (tempNode.left !== null){ - evenArr.push(tempNode.left); + evenLine.push(tempNode.left); } - if (tempNode.right !== null) { - evenArr.push(tempNode.right); + if (tempNode.right !== null){ + evenLine.push(tempNode.right); } } } if (tempArr.length !== 0){ - output.push(tempArr); - currentlayer++; + outPrint.push(tempArr); } } else { let tempArr = []; - while(evenArr.length !== 0){ - let tempNode = evenArr.pop(); - if (tempNode !== null){ - if (tempNode.right !== null) { - oddArr.push(tempNode.right); - } + while(evenLine.length !== 0){ + let tempNode = evenLine[0]; + evenLine = evenLine.slice(1); + if (tempNode !== null) { tempArr.push(tempNode.val); if (tempNode.left !== null){ - oddArr.push(tempNode.left); + oddLine.push(tempNode.left); + } + if (tempNode.right !== null){ + oddLine.push(tempNode.right); } } } if (tempArr.length !== 0){ - output.push(tempArr); - currentlayer++; + outPrint.push(tempArr); } } + currentOdd = !currentOdd; } - return output; + return outPrint; } diff --git a/NowCoder/Leetcode/printTreebyLayer.js b/NowCoder/Leetcode/printTreebyLayer.js new file mode 100644 index 0000000..3be740a --- /dev/null +++ b/NowCoder/Leetcode/printTreebyLayer.js @@ -0,0 +1,66 @@ +/**** + * + * + * 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。 + * + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function Print(pRoot) +{ + let outPrint = []; + if (pRoot === null){ + return outPrint; + } + let oddLine = []; + let evenLine = []; + oddLine.push(pRoot); + let currentOdd = true; + + while(oddLine.length !== 0 || evenLine.length !== 0){ + if (currentOdd){ + let tempArr = []; + while(oddLine.length !== 0){ + let tempNode = oddLine[0]; + oddLine = oddLine.slice(1); + if (tempNode !== null) { + tempArr.push(tempNode.val); + if (tempNode.left !== null){ + evenLine.push(tempNode.left); + } + if (tempNode.right !== null){ + evenLine.push(tempNode.right); + } + } + } + if (tempArr.length !== 0){ + outPrint.push(tempArr); + } + } else { + let tempArr = []; + while(evenLine.length !== 0){ + let tempNode = evenLine[0]; + evenLine = evenLine.slice(1); + if (tempNode !== null) { + tempArr.push(tempNode.val); + if (tempNode.left !== null){ + oddLine.push(tempNode.left); + } + if (tempNode.right !== null){ + oddLine.push(tempNode.right); + } + } + } + if (tempArr.length !== 0){ + outPrint.push(tempArr); + } + } + currentOdd = !currentOdd; + } + return outPrint; +} \ No newline at end of file From fc046f05a1324aab1f4fb728f975d138c2dc4225 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 2 May 2019 16:40:03 +0800 Subject: [PATCH 154/274] =?UTF-8?q?=E5=88=A4=E6=96=AD=E4=B8=80=E9=A2=97?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E6=98=AF=E4=B8=8D=E6=98=AF=E5=AF=B9?= =?UTF-8?q?=E7=A7=B0=E7=9A=84=E9=80=92=E5=BD=92=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 132 ++++++++++++++++++----------- NowCoder/Leetcode/isSymmetrical.js | 36 ++++++++ 2 files changed, 117 insertions(+), 51 deletions(-) create mode 100644 NowCoder/Leetcode/isSymmetrical.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 3531290..1cd7ee6 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -186,67 +186,97 @@ const arrayToTreeNode = require('./tools/treeNode'); // return backHead; // } +// function TreeNode(x) { +// this.val = x; +// this.left = null; +// this.right = null; +// } +// function Print(pRoot) +// { +// let outPrint = []; +// if (pRoot === null){ +// return outPrint; +// } +// let oddLine = []; +// let evenLine = []; +// oddLine.push(pRoot); +// let currentOdd = true; + +// while(oddLine.length !== 0 || evenLine.length !== 0){ +// if (currentOdd){ +// let tempArr = []; +// while(oddLine.length !== 0){ +// let tempNode = oddLine[0]; +// oddLine = oddLine.slice(1); +// if (tempNode !== null) { +// tempArr.push(tempNode.val); +// if (tempNode.left !== null){ +// evenLine.push(tempNode.left); +// } +// if (tempNode.right !== null){ +// evenLine.push(tempNode.right); +// } +// } +// } +// if (tempArr.length !== 0){ +// outPrint.push(tempArr); +// } +// } else { +// let tempArr = []; +// while(evenLine.length !== 0){ +// let tempNode = evenLine[0]; +// evenLine = evenLine.slice(1); +// if (tempNode !== null) { +// tempArr.push(tempNode.val); +// if (tempNode.left !== null){ +// oddLine.push(tempNode.left); +// } +// if (tempNode.right !== null){ +// oddLine.push(tempNode.right); +// } +// } +// } +// if (tempArr.length !== 0){ +// outPrint.push(tempArr); +// } +// } +// currentOdd = !currentOdd; +// } +// return outPrint; + +// } + function TreeNode(x) { this.val = x; this.left = null; this.right = null; } -function Print(pRoot) +function isSymmetrical(pRoot) { - let outPrint = []; - if (pRoot === null){ - return outPrint; + let symmetrical = false; + if (pRoot === null) { + return symmetrical; } - let oddLine = []; - let evenLine = []; - oddLine.push(pRoot); - let currentOdd = true; - - while(oddLine.length !== 0 || evenLine.length !== 0){ - if (currentOdd){ - let tempArr = []; - while(oddLine.length !== 0){ - let tempNode = oddLine[0]; - oddLine = oddLine.slice(1); - if (tempNode !== null) { - tempArr.push(tempNode.val); - if (tempNode.left !== null){ - evenLine.push(tempNode.left); - } - if (tempNode.right !== null){ - evenLine.push(tempNode.right); - } - } - } - if (tempArr.length !== 0){ - outPrint.push(tempArr); - } - } else { - let tempArr = []; - while(evenLine.length !== 0){ - let tempNode = evenLine[0]; - evenLine = evenLine.slice(1); - if (tempNode !== null) { - tempArr.push(tempNode.val); - if (tempNode.left !== null){ - oddLine.push(tempNode.left); - } - if (tempNode.right !== null){ - oddLine.push(tempNode.right); - } - } - } - if (tempArr.length !== 0){ - outPrint.push(tempArr); - } + + this.compareNode = function(leftNode, rightNode){ + if (leftNode === null){ + return rightNode === null; + } + if (rightNode === null){ + return false; } - currentOdd = !currentOdd; + if (leftNode.val !== rightNode.val){ + return false; + } + return this.compareNode(leftNode.left, rightNode.right) && this.compareNode(leftNode.right, rightNode.left); } - return outPrint; + return this.compareNode(pRoot.left, pRoot.right); } -let arr1 = [1, 1, 2, 3, 3, 4, 5]; + +// let arr1 = [1, 1, 2, 3, 3, 4, 5]; +let arr1 = [5,6,7,8,7,6,5]; // let arr2 = [1, 2, 3, 4, 5]; // var tempLink1 = arrayToLinkNode(arr1); @@ -254,8 +284,8 @@ let arr1 = [1, 1, 2, 3, 3, 4, 5]; var tempTree = arrayToTreeNode(arr1); console.log(tempTree); -tempTreeArr = Print(tempTree); -console.log(tempTreeArr); +let result = isSymmetrical(tempTree); +console.log(result); // console.log(tempLink2); // var list1 = linkToArray(tempLink1); // console.log(list1); diff --git a/NowCoder/Leetcode/isSymmetrical.js b/NowCoder/Leetcode/isSymmetrical.js new file mode 100644 index 0000000..dcb4a59 --- /dev/null +++ b/NowCoder/Leetcode/isSymmetrical.js @@ -0,0 +1,36 @@ +/***** + * + * 请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。 + * + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function isSymmetrical(pRoot) +{ + if (pRoot === null) { + return true; + } + + this.compareNode = function(leftNode, rightNode){ + if (leftNode === null){ + return rightNode === null; + } + if (rightNode === null){ + return false; + } + if (leftNode.val !== rightNode.val){ + return false; + } + return this.compareNode(leftNode.left, rightNode.right) && this.compareNode(leftNode.right, rightNode.left); + } + + return this.compareNode(pRoot.left, pRoot.right); +} + + +// 非递归写法 \ No newline at end of file From f1dc6d5c3c992b638a6228c5db31c570e9e0fa6c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 3 May 2019 14:56:19 +0800 Subject: [PATCH 155/274] =?UTF-8?q?=E5=88=A4=E6=96=AD=E6=9C=89=E5=A4=A7?= =?UTF-8?q?=E5=B0=8F=E7=8E=8B=E7=9A=84=E6=89=91=E5=85=8B=E7=89=8C=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E6=98=AF=E9=A1=BA=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 各种可能处理 --- NowCoder/Leetcode/isContinuous.js | 74 +++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 NowCoder/Leetcode/isContinuous.js diff --git a/NowCoder/Leetcode/isContinuous.js b/NowCoder/Leetcode/isContinuous.js new file mode 100644 index 0000000..e504be8 --- /dev/null +++ b/NowCoder/Leetcode/isContinuous.js @@ -0,0 +1,74 @@ +/******* + * + * LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)... + * 他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!! + * “红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子..... + * LL不高兴了,他想了想,决定大\小王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。 + * 上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。 + * LL决定去买体育彩票啦。 + * 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, + * 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。 + * + * + * + */ + +function IsContinuous(numbers) +{ + if (numbers === null || numbers.length !== 5) { + return false; + } + + numbers.sort(function(a,b){ + return a-b; + }); + let countArr = []; + let zeroVar = 0; + // 统计每个数值出现的次数 + for (let i = 0; i < numbers.length; i++) { + if (countArr[numbers[i]]) { + countArr[numbers[i]]+=1; + // 如果除0以外的数出现次数大于1 + if (countArr[numbers[i]]>=2 && numbers[i]!==0) { + return false; + } + // 如果 0 出现的次数大于4 + if (numbers[i]===0 && countArr[numbers[i]]>4) { + return false; + } + } else { + countArr[numbers[i]] = 1; + } + } + if (countArr[0]) { + zeroVar = countArr[0]; + } + + // 输入0个个数以及排序好的牌 + this.checkIfContinuous = function(sortArr, zeroNum){ + if (zeroNum === 4) { + return true; + } + let leftArr = sortArr.slice(zeroNum); // 获取非零的牌 + let maxGap = 0; + let countGap = 0; + for (let i = 1; i 1) { + if (tempGap > maxGap) { + maxGap = tempGap; + } + countGap++; + } + } + if (maxGap-1 > zeroNum || countGap > zeroNum) { + return false; + } + return true; + } + // console.log(numbers); + return this.checkIfContinuous(numbers,zeroVar); +} + +let numbers = [0,3,2,6,4]; +console.log(IsContinuous(numbers)); \ No newline at end of file From 1a2b43b64290d17d07c0a4922c1099c6d39b5173 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 3 May 2019 15:23:31 +0800 Subject: [PATCH 156/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9A=84=E5=A4=8D=E5=88=B6=E5=B8=B8=E8=A7=84?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/cloneComplexLinkList.js | 54 +++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 NowCoder/Leetcode/cloneComplexLinkList.js diff --git a/NowCoder/Leetcode/cloneComplexLinkList.js b/NowCoder/Leetcode/cloneComplexLinkList.js new file mode 100644 index 0000000..c5fea4c --- /dev/null +++ b/NowCoder/Leetcode/cloneComplexLinkList.js @@ -0,0 +1,54 @@ +/****** + * + * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点), + * 返回结果为复制后复杂链表的head。 + * + * (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) + * + * + * + */ + +function RandomListNode(x){ + this.label = x; + this.next = null; + this.random = null; +} +function Clone(pHead) +{ + if (pHead === null) { + return null; + } + + let copyList = new RandomListNode(pHead.label); + let randomArr = []; // 使用数组存 random 项 + let current = pHead; + let currentCopy = copyList; + randomArr.push(pHead.random); + + while (current){ + let tempNode = current.next; + let currNode; + if (tempNode !== null) { + currNode = copyList; + while (currNode.next) { + currNode = currNode.next; + } + currNode.next = new RandomListNode(tempNode.label); + randomArr.push(tempNode.random); + } + current = tempNode; + } + + let i = 0; + while (currentCopy){ + if (randomArr[i] !== null) { + currentCopy.random = randomArr[i]; + } + i++; + currentCopy = currentCopy.next; + } + + return copyList; + +} \ No newline at end of file From 18c45427f1aec446a2467fc6e0e7d4a179969061 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 3 May 2019 16:27:43 +0800 Subject: [PATCH 157/274] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E8=BD=AC=E5=8F=8C=E5=90=91=E9=93=BE=E8=A1=A8=E7=9A=84?= =?UTF-8?q?=E9=80=92=E5=BD=92=E4=B8=8E=E9=9D=9E=E9=80=92=E5=BD=92=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../convertBinaryTreetoDoubleLinkList.js | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 NowCoder/Leetcode/convertBinaryTreetoDoubleLinkList.js diff --git a/NowCoder/Leetcode/convertBinaryTreetoDoubleLinkList.js b/NowCoder/Leetcode/convertBinaryTreetoDoubleLinkList.js new file mode 100644 index 0000000..46aab74 --- /dev/null +++ b/NowCoder/Leetcode/convertBinaryTreetoDoubleLinkList.js @@ -0,0 +1,81 @@ +/***** + * + * 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。 + * 要求不能创建任何新的结点,只能调整树中结点指针的指向。 + * + * + */ + + + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +// 中序遍历方法的非递归解法 + +function Convert(pRootOfTree) +{ + if (pRootOfTree === null) { + return null; + } + let stackData = []; + let currentNode = pRootOfTree; + let preNode = null; + let checkFirst = true; + + while (currentNode !== null || stackData.length !== 0) { + while (currentNode !== null){ + stackData.push(currentNode); + currentNode = currentNode.left; + } + currentNode = stackData.pop(); + if (checkFirst) { + pRootOfTree = currentNode; + preNode = pRootOfTree; + checkFirst = false; + } else { + preNode.right = currentNode; + currentNode.left = preNode; + preNode = currentNode; + + } + currentNode = currentNode.right; + } + return pRootOfTree; + +} + + +// 递归解法 +function ConvertRecursion(pRootOfTree) { + if (pRootOfTree === null) { + return null; + } + if (pRootOfTree.left === null && pRootOfTree.right === null) { + return pRootOfTree; + } + + // 将左子树构造成双向链表,并返回链表头 + let leftList = ConvertRecursion(pRootOfTree.left); + let currentNode = leftList; + // 找到左子树链表最后一个数 + while (currentNode !== null && currentNode.right !== null){ + currentNode = currentNode.right; + } + if (leftList !== null) { + currentNode.right = pRootOfTree; + pRootOfTree.left = currentNode; + } + + // 将右子树构造成双向链表并返回链表头 + let rightList = ConvertRecursion(pRootOfTree.right); + if (rightList !== null) { + rightList.left = pRootOfTree; + pRootOfTree.right = rightList; + } + + return leftList !== null ? leftList:pRootOfTree; +} \ No newline at end of file From ad0db615be8cb1063ccdda9416ccb1f282db5514 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 4 May 2019 19:56:37 +0800 Subject: [PATCH 158/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E6=AD=A3=E5=88=99?= =?UTF-8?q?=E8=A1=A8=E8=BE=BE=E5=BC=8F=E7=9A=84=E6=96=B9=E6=B3=95=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E4=B8=80=E4=B8=AA=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E8=A1=A8=E7=A4=BA=E6=95=B0=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/isNumeric.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 NowCoder/Leetcode/isNumeric.js diff --git a/NowCoder/Leetcode/isNumeric.js b/NowCoder/Leetcode/isNumeric.js new file mode 100644 index 0000000..69d5bcf --- /dev/null +++ b/NowCoder/Leetcode/isNumeric.js @@ -0,0 +1,33 @@ +/***** + * + * 判断一个字符串是否表示数值 + * + * + * 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 + * 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 + * 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。 + * + * + * + */ + + +// 考虑可能性的解法 +function isNumeric(s) { + +} + + +// 使用正则表达式简写 + +function isNumeric2(s) { + let numreg = /^[\+\-]?\d*(\.\d+)?([eE][\+\-]?\d+)?$/; + let result = numreg.test(s); + return result; +} + +// 奇怪的测试用例 +// "-.123" 是对的? + +let s = '5e2'; +console.log(isNumeric2(s)); \ No newline at end of file From d30c122aef942923eb9f4e9d7a3cb89a4163b656 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 4 May 2019 19:57:42 +0800 Subject: [PATCH 159/274] =?UTF-8?q?=E5=88=A9=E7=94=A8=E7=9F=A9=E9=98=B5?= =?UTF-8?q?=E6=9C=89=E5=BA=8F=E7=9A=84=E8=BF=99=E4=B8=80=E6=9D=A1=E4=BB=B6?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E4=BA=8C=E7=BB=B4=E6=95=B0=E7=BB=84=E4=B8=AD?= =?UTF-8?q?=E6=9F=A5=E6=89=BE=E5=80=BC=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/checkDatainArray.js | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/NowCoder/Leetcode/checkDatainArray.js b/NowCoder/Leetcode/checkDatainArray.js index de104ac..3e656a8 100644 --- a/NowCoder/Leetcode/checkDatainArray.js +++ b/NowCoder/Leetcode/checkDatainArray.js @@ -18,10 +18,28 @@ function Find(target, array) { return false; } - /* +/* * 涉及理论: 搜索及排序 * 普通解法: 遍历 - * 改进方向: + * 改进方向:利用矩阵有序的这一条件 + * 改进方案:从左下角开始找起,比左下角小的向上移,比左下角大的向右移动 * * - */ \ No newline at end of file + */ + +function Find2(target, array) { + let lenr = array.length; + let lenc = array[0].length; + let i = lenr - 1, + j = 0; + while (i >=0 && j<= lenc-1) { + if (array[i][j] < target) { + j++; + } else if (array[i][j] > target) { + i--; + } else { + return true; + } + } + return false; +} From dafdf948168a5e69da001cf12d8c554dbfa52f10 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 5 May 2019 00:30:15 +0800 Subject: [PATCH 160/274] =?UTF-8?q?=E7=89=B9=E6=AE=8A=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E4=B8=AD=E5=BA=8F=E9=81=8D=E5=8E=86=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E7=BB=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/getNextNode.js | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 NowCoder/Leetcode/getNextNode.js diff --git a/NowCoder/Leetcode/getNextNode.js b/NowCoder/Leetcode/getNextNode.js new file mode 100644 index 0000000..8c3efef --- /dev/null +++ b/NowCoder/Leetcode/getNextNode.js @@ -0,0 +1,40 @@ +/****** + * + * 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。 + * 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 + * + * + * + */ + + +function TreeLinkNode(x){ + this.val = x; + this.left = null; + this.right = null; + this.next = null; // 这是指向父节点的指针,易误解 +} +function GetNext(pNode) +{ + if(pNode === null) { + return null; + } + + if ( pNode.right !== null){ + let tempNode = pNode.right; + while(tempNode.left !== null){ + tempNode = tempNode.left; + } + return tempNode; + } + + while(pNode.next !== null){ + let tempParent = pNode.next; + // 右子树为空时,找到父节点中是左子树的父节点,即为当前结点的下一个结点 + if (tempParent.left === pNode){ + return tempParent; + } + pNode = pNode.next; + } + return null; +} \ No newline at end of file From fcd5240864aa5ebb88fd3745bb1abe0d9ef220d8 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 5 May 2019 14:30:26 +0800 Subject: [PATCH 161/274] =?UTF-8?q?=E5=88=A4=E6=96=AD=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=98=AF=E5=90=A6=E8=A1=A8=E7=A4=BA?= =?UTF-8?q?=E6=95=B0=E5=80=BC=20=E8=80=83=E8=99=91=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E5=A4=9A=E7=A7=8D=E5=8F=AF=E8=83=BD=E6=80=A7=E7=9A=84=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/isNumeric.js | 40 ++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/NowCoder/Leetcode/isNumeric.js b/NowCoder/Leetcode/isNumeric.js index 69d5bcf..c7330cc 100644 --- a/NowCoder/Leetcode/isNumeric.js +++ b/NowCoder/Leetcode/isNumeric.js @@ -14,9 +14,45 @@ // 考虑可能性的解法 function isNumeric(s) { - + if (s.length === 0 || s === null){ + return false; + } + let nDolt =false; // 用于记录小数点 是否出现过 + let nSymbol = false; // 用于 标记 +- 符号是否出现过 + let nTen = false; // 用于标记 e 是否出现过 + + for (let i = 0; i < s.length; i++) { + if (s[i] === 'e' || s[i] === 'E') { + // e 后面没有数字 或者 已经出现过一次 E + if (i === s.length-1 || nTen) { + return false; + } + nTen = true; + }else if (s[i] === '+' || s[i] === '-') { + // 已经出现一次符号,这一次出现的符号前一个字符不是 'e' 或者 'E' + if (nSymbol && s[i-1] !== 'e' && s[i-1] !== 'E') { + return false; + } + if (!nSymbol && i > 0 && s[i - 1] !== 'e' && s[i - 1] !== 'E') { + return false; + } + nSymbol = true; + }else if (s[i] === '.'){ + // 出现了两个小数点或者在E以后出现小数点都不是合法的数字 + if (nDolt || nTen) { + return false; + } + nDolt = true; + } else if(s[i] < '0' || s[i] > '9'){ + return false; + } + } + return true; } +let s = '-1E-16'; +console.log(isNumeric(s)); + // 使用正则表达式简写 @@ -29,5 +65,5 @@ function isNumeric2(s) { // 奇怪的测试用例 // "-.123" 是对的? -let s = '5e2'; + console.log(isNumeric2(s)); \ No newline at end of file From 98ab1c277f86e222e25fa479ad0218c295cbee27 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 6 May 2019 14:54:35 +0800 Subject: [PATCH 162/274] =?UTF-8?q?=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=8F=AA?= =?UTF-8?q?=E5=87=BA=E7=8E=B0=E4=B8=80=E6=AC=A1=E7=9A=84=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=20JavaScript=20=E6=B5=8B=E8=AF=95=E6=A1=88=E4=BE=8B=E4=B8=8D?= =?UTF-8?q?=E9=80=9A=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/firstAppearingOnce.js | 77 +++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 NowCoder/Leetcode/firstAppearingOnce.js diff --git a/NowCoder/Leetcode/firstAppearingOnce.js b/NowCoder/Leetcode/firstAppearingOnce.js new file mode 100644 index 0000000..bc6d9e4 --- /dev/null +++ b/NowCoder/Leetcode/firstAppearingOnce.js @@ -0,0 +1,77 @@ +/******* + * + * + * 请实现一个函数用来找出字符流中第一个只出现一次的字符。 + * 例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。 + * 当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 + * + * + * 如果当前字符流没有存在出现一次的字符, 返回 # 字符。 + * + */ + +// 思想时 HashMap 的 思想 + +//Init module if you need +function Init() { + // write code here + +} +let arrayCounter = []; +let countStr = ''; +//Insert one char from stringstream +function Insert(ch) { + // write code here + countStr += ch; + if (arrayCounter.indexOf(ch) !== -1) { + let tempTable = []; + for (let k = 0; k < arrayCounter.length; k++) { + if (arrayCounter[k] !== ch) { + tempTable.push(arrayCounter[k]); + } + } + arrayCounter = tempTable; + } else { + arrayCounter.push(ch); + } + console.log(arrayCounter); + + // if (arrayCounter[ch]) { + // arrayCounter[ch]++; + // } else { + // arrayCounter[ch] = 1; + // } + +} +//return the first appearence once char in current stringstream +function FirstAppearingOnce() { + // let strLen = countStr.length; + if (arrayCounter.length > 0) { + return arrayCounter[0]; + } + + return '#'; + + +} + +// Insert('h'); +// console.log(FirstAppearingOnce()); +// Insert('e'); +// console.log(FirstAppearingOnce()); +// Insert('l'); +// console.log(FirstAppearingOnce()); +// Insert('l'); +// console.log(FirstAppearingOnce()); +// Insert('o'); +// console.log(FirstAppearingOnce()); +// Insert('w'); +// console.log(FirstAppearingOnce()); +// Insert('o'); +// console.log(FirstAppearingOnce()); +// Insert('r'); +// console.log(FirstAppearingOnce()); +// Insert('l'); +// console.log(FirstAppearingOnce()); +// Insert('d'); +// console.log(FirstAppearingOnce()); \ No newline at end of file From a33b9875113e5d6ff3b03b21a1b3a324bfe88c1a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 6 May 2019 14:55:43 +0800 Subject: [PATCH 163/274] =?UTF-8?q?=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=8E=AF?= =?UTF-8?q?=E7=9A=84=E5=85=A5=E5=8F=A3=E7=BB=93=E7=82=B9=20=E4=B8=89?= =?UTF-8?q?=E7=A7=8D=E4=B8=8D=E5=90=8C=E7=9A=84=E8=A7=A3=E5=86=B3=E6=80=9D?= =?UTF-8?q?=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/entryNodeOfLoop.js | 83 ++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 NowCoder/Leetcode/entryNodeOfLoop.js diff --git a/NowCoder/Leetcode/entryNodeOfLoop.js b/NowCoder/Leetcode/entryNodeOfLoop.js new file mode 100644 index 0000000..9f079cc --- /dev/null +++ b/NowCoder/Leetcode/entryNodeOfLoop.js @@ -0,0 +1,83 @@ +/******** + * + * 链表中环的入口结点 + * + * + * 给一个链表, 若其中包含环, 请找出该链表的环的入口结点, 否则, 输出null。 + * + * + */ + +function ListNode(x){ + this.val = x; + this.next = null; +} + +// 使用存结点的思想解决,当第一次出现相同结点是算作 环的入口结点 +//因为每次都要搜索算法复杂度较高 +function EntryNodeOfLoop(pHead) { + if (pHead === null) { + return null; + } + let currentNode = pHead; + let nodeArr = []; + while (currentNode.next !== null) { + if (nodeArr.indexOf(currentNode) === -1) { + nodeArr.push(currentNode); + } else { + return currentNode; + } + currentNode = currentNode.next; + } + return null; +} + +// 时间复杂度为 O(N) 的算法,使用快慢指针先判断是否有环,如果有环指向 相遇的点 +function EntryNodeOfLoop2(pHead) { + + if (pHead === null || pHead.next === null || pHead.next.next === null) { + return null; + } + + let fastNode = pHead.next.next; + let slowNode = pHead.next; + + // 用于判断有没有环 + while (fastNode !== slowNode) { + if (fastNode.next.next !== null && slowNode.next !== null) { + fastNode = fastNode.next.next; + slowNode = slowNode.next; + } else { + return null; + } + } + // 退出循环的时候 fastNode = slowNode 且是第一次相遇的点 + + fastNode = pHead; + while (fastNode !== slowNode) { + fastNode = fastNode.next; + slowNode = slowNode.next; + } + + return fastNode; +} + +// 使用断链法解决问题 +// 所谓断链法就是把每一个结点的 next 都置空,如果存在环,从环的入口断掉后 +// ! 此方法不能判断链表无环的情况,并且破坏了链表的结构 +function EntryNodeOfLoop3(pHead) { + if (pHead === null || pHead.next === null) { + return null; + } + let firstNode = pHead.next; + let secondNode = pHead; + + while (firstNode !== null) { + secondNode.next = null; + secondNode = firstNode; + firstNode = firstNode.next; + } + + return secondNode; + +} \ No newline at end of file From 3297df1ea622f64fdf711cd5a522d2af3c505568 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 7 May 2019 21:46:42 +0800 Subject: [PATCH 164/274] =?UTF-8?q?=E5=BA=8F=E5=88=97=E5=8C=96=E5=92=8C?= =?UTF-8?q?=E5=8F=8D=E5=BA=8F=E5=88=97=E5=8C=96=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=20=E6=9C=AA=E9=80=9A=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/testAlg.js | 73 ++++++++++++++++------ NowCoder/Leetcode/serializeAndSerialize.js | 51 +++++++++++++++ 2 files changed, 104 insertions(+), 20 deletions(-) create mode 100644 NowCoder/Leetcode/serializeAndSerialize.js diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 1cd7ee6..9be1c58 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -251,41 +251,74 @@ function TreeNode(x) { this.left = null; this.right = null; } -function isSymmetrical(pRoot) -{ - let symmetrical = false; +// function isSymmetrical(pRoot) +// { +// let symmetrical = false; +// if (pRoot === null) { +// return symmetrical; +// } + +// this.compareNode = function(leftNode, rightNode){ +// if (leftNode === null){ +// return rightNode === null; +// } +// if (rightNode === null){ +// return false; +// } +// if (leftNode.val !== rightNode.val){ +// return false; +// } +// return this.compareNode(leftNode.left, rightNode.right) && this.compareNode(leftNode.right, rightNode.left); +// } + +// return this.compareNode(pRoot.left, pRoot.right); +// } + + +function Serialize(pRoot) { + // 使用前序遍历的形式访问整个二叉树 + let nodeStr = ''; if (pRoot === null) { - return symmetrical; + nodeStr += '@,'; + return nodeStr; } + nodeStr += pRoot.val + ','; + nodeStr += Serialize(pRoot.left); + nodeStr += Serialize(pRoot.right); + return nodeStr; +} - this.compareNode = function(leftNode, rightNode){ - if (leftNode === null){ - return rightNode === null; - } - if (rightNode === null){ - return false; - } - if (leftNode.val !== rightNode.val){ - return false; - } - return this.compareNode(leftNode.left, rightNode.right) && this.compareNode(leftNode.right, rightNode.left); - } +let index = -1; - return this.compareNode(pRoot.left, pRoot.right); +function Deserialize(s) { + index++; + if (index >= s.length) { + return null; + } + let nodeArr = s.split(','); + let treeNode = null; + if (nodeArr[index] !== '@') { + treeNode = new TreeNode(nodeArr[index]); + treeNode.left = Deserialize(s); + treeNode.right = Deserialize(s); + } + return treeNode; } // let arr1 = [1, 1, 2, 3, 3, 4, 5]; let arr1 = [5,6,7,8,7,6,5]; -// let arr2 = [1, 2, 3, 4, 5]; +let arr2 = [5, 4, "#", 3, "#", 2]; // var tempLink1 = arrayToLinkNode(arr1); // var tempLink2 = arrayToTreeNode(arr2); -var tempTree = arrayToTreeNode(arr1); +var tempTree = arrayToTreeNode(arr2); console.log(tempTree); -let result = isSymmetrical(tempTree); +let result = Serialize(tempTree); console.log(result); + +console.log(Deserialize(result)); // console.log(tempLink2); // var list1 = linkToArray(tempLink1); // console.log(list1); diff --git a/NowCoder/Leetcode/serializeAndSerialize.js b/NowCoder/Leetcode/serializeAndSerialize.js new file mode 100644 index 0000000..a620b7d --- /dev/null +++ b/NowCoder/Leetcode/serializeAndSerialize.js @@ -0,0 +1,51 @@ +/****** + * + * 将二叉树序列化 和 反序列化 + * + * 请实现两个函数, 分别用来序列化和反序列化二叉树 + * + * + * + */ + + +// 根据前序遍历规则完成序列化与反序列化。 +// 所谓序列化指的是遍历二叉树为字符串; 所谓反序列化指的是依据字符串重新构造成二叉树。 +// 依据前序遍历序列来序列化二叉树, 因为前序遍历序列是从根结点开始的。 当在遍历二叉树时碰到Null指针时, 这些Null指针被序列化为一个特殊的字符“#”。 +// 另外, 结点之间的数值用逗号隔开。 + + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function Serialize(pRoot) { + // 使用前序遍历的形式访问整个二叉树 + let nodeStr = ''; + if (pRoot === null) { + nodeStr+= '#,'; + return nodeStr; + } + nodeStr += pRoot.val + ','; + nodeStr += Serialize(pRoot.left); + nodeStr += Serialize(pRoot.right); + return nodeStr; +} + +let index = -1; + +function Deserialize(s) { + index++; + if (index >= s.length) { + return null; + } + let nodeArr = s.split(','); + let treeNode; + if (nodeArr[index] !== '#') { + treeNode = new TreeNode(parseInt(nodeArr[index])); + treeNode.left = Deserialize(s); + treeNode.right = Deserialize(s); + } + return treeNode; +} From 98c062ad4dd8b23b7aab370dedc6220687806ed7 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 9 May 2019 20:35:22 +0800 Subject: [PATCH 165/274] =?UTF-8?q?=E8=8E=B7=E5=8F=96=E6=89=80=E6=9C=89?= =?UTF-8?q?=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3=E4=B8=AD=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=A4=A7=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/maxInWindows.js | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 NowCoder/Leetcode/maxInWindows.js diff --git a/NowCoder/Leetcode/maxInWindows.js b/NowCoder/Leetcode/maxInWindows.js new file mode 100644 index 0000000..5f870de --- /dev/null +++ b/NowCoder/Leetcode/maxInWindows.js @@ -0,0 +1,41 @@ +/* + * @Author: mikey.zhaopeng + * @Date: 2019-05-09 20:20:53 + * @Last Modified by: mikey.zhaopeng + * @Last Modified time: 2019-05-09 20:34:12 + * + */ + +/**** + * + * 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。 + * 例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口, + * 他们的最大值分别为{4,4,6,6,6,5}; + * + * 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: + * {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, + * {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。 + * + * + */ + +function maxInWindows(num, size) { + let backArray = []; + if (num.length === 0 || num === null || size === 0 || num.length < size) { + return backArray; + } + if (num.length >= size) { + let currentStart = 0; + for (let j = size; j <= num.length; j++) { + let tempArr = num.slice(currentStart++, j); + tempArr.sort((a,b) => a-b); + backArray.push(tempArr[tempArr.length - 1]); + } + } + + return backArray; +} + +let nums = [2, 3, 4, 2, 6, 2, 5, 1]; +let size = 3; +console.log(maxInWindows(nums, size)); \ No newline at end of file From ab9a60273098f56866cd9cc5a5d7c1bde0042110 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 9 May 2019 21:21:40 +0800 Subject: [PATCH 166/274] =?UTF-8?q?=E5=88=A4=E6=96=AD=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E7=9F=A9=E9=98=B5=E4=B8=AD=E7=9A=84=E8=B7=AF=E5=BE=84=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E5=AD=98=E5=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/hasPath.js | 69 +++++++++++++++++++++++++++++++ NowCoder/Leetcode/maxInWindows.js | 6 +-- 2 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 NowCoder/Leetcode/hasPath.js diff --git a/NowCoder/Leetcode/hasPath.js b/NowCoder/Leetcode/hasPath.js new file mode 100644 index 0000000..1585cf7 --- /dev/null +++ b/NowCoder/Leetcode/hasPath.js @@ -0,0 +1,69 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-09 20:36:43 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-09 21:20:49 + */ + +/**** + * + * 请设计一个函数, 用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 + * 路径可以从矩阵中的任意一个格子开始, 每一步可以在矩阵中向左, 向右, 向上, 向下移动一个格子。 + * 如果一条路径经过了矩阵中的某一个格子, 则之后不能再次进入这个格子。 + * 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串 "bcced"的路径, 但是矩阵中不包含 "abcb"路径, + * 因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后, 路径不能再次进入该格子。 + * + * + * + */ + +// matrix 是一个一维数组 + +function hasPath(matrix, rows, cols, path) { + + // 使用回溯法完成矩阵的搜索 + // k 表示path 中的第 k 个字符 staMatrix[currentIndex] === 1 表示该位置已经被访问过 + this.checkIfMeet = function (matrix, rows, cols, i, j, k, pathStr, staMatrix) { + let currentIndex = i * cols + j; + if (i < 0 || i >= rows || j < 0 || j >= cols || staMatrix[currentIndex] === 1 || matrix[currentIndex] !== pathStr[k]) { + return false; + } + if (k === pathStr.length-1) { + return true; + } + // 第一个判断没有返回说明当前字符是属于 path 中的,并且不是最后一个字符(第二个if) + staMatrix[currentIndex] = 1; // 将此状态设置成 1 说明这个点匹配上了并且访问过了这个点 + let nextPathNode = k + 1; + // 对这个点的上下左右四个点进行回溯 + if (this.checkIfMeet(matrix, rows, cols, i + 1, j, nextPathNode, pathStr, staMatrix) || + this.checkIfMeet(matrix, rows, cols, i, j + 1, nextPathNode, pathStr, staMatrix) || + this.checkIfMeet(matrix, rows, cols, i - 1, j, nextPathNode, pathStr, staMatrix) || + this.checkIfMeet(matrix, rows, cols, i, j - 1, nextPathNode, pathStr, staMatrix) + ) { + return true; + } + staMatrix[currentIndex] = 0; + return false; + } + + // 使用状态矩阵来保存访问过的有效值 + let stateMatrix = []; + // 遍历整个矩阵直到找到第一个匹配字符串的字符 然后调用方法进行回溯 + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (this.checkIfMeet(matrix, rows, cols, i, j, 0, path, stateMatrix)) { + return true; + } + } + } + return false; +} + +let matrix = 'abcesfcsadee'; +let rows = 3; +let cols = 4; +let path = 'bcced'; +let path2 = 'abcb'; +console.log(hasPath(matrix, rows, cols, path)); +console.log(hasPath(matrix, rows, cols, path2)); + diff --git a/NowCoder/Leetcode/maxInWindows.js b/NowCoder/Leetcode/maxInWindows.js index 5f870de..1f0c809 100644 --- a/NowCoder/Leetcode/maxInWindows.js +++ b/NowCoder/Leetcode/maxInWindows.js @@ -1,8 +1,8 @@ /* - * @Author: mikey.zhaopeng + * @Author: SkylineBin * @Date: 2019-05-09 20:20:53 - * @Last Modified by: mikey.zhaopeng - * @Last Modified time: 2019-05-09 20:34:12 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-09 20:42:08 * */ From 01b1c120c9ca128f5a3b9e863d24f87a1dcc47b9 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 10 May 2019 10:52:48 +0800 Subject: [PATCH 167/274] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E6=8C=87=E5=8D=97?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E4=B8=89=E4=B8=AA=E5=85=B3=E4=BA=8E=E6=A0=88?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 递归算法解决改进版汉诺塔问题 2. 递归完成一个栈的逆序 3. 用一个辅助栈完成栈的排序 --- .../CodingInterview/hanoiAdvanceProblems.js | 69 +++++++++++++++++++ .../reverseStackByRecursion.js | 49 +++++++++++++ NowCoder/CodingInterview/sortStackByStack.js | 35 ++++++++++ 3 files changed, 153 insertions(+) create mode 100644 NowCoder/CodingInterview/hanoiAdvanceProblems.js create mode 100644 NowCoder/CodingInterview/reverseStackByRecursion.js create mode 100644 NowCoder/CodingInterview/sortStackByStack.js diff --git a/NowCoder/CodingInterview/hanoiAdvanceProblems.js b/NowCoder/CodingInterview/hanoiAdvanceProblems.js new file mode 100644 index 0000000..39a3004 --- /dev/null +++ b/NowCoder/CodingInterview/hanoiAdvanceProblems.js @@ -0,0 +1,69 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-10 10:08:12 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-10 10:50:28 + */ + +/******* + * + * 解决改进版汉诺塔问题 + * + * 有 左中右 三根柱子 + * 将 N 层塔 从左侧柱子 移到 右侧柱子需要走的最小步数 + * 最上面是第一层,最下面是第 N 层 + * 只能将 小的层数放在大的层数之上 + * + * + * + */ + +// 处理移动的过程用于递归 +function processMoving(layerNum, left, middle, right, fromSide, toSide) { + if (layerNum === 1) { + if (fromSide === middle || toSide === middle) { + console.log("Move 1 from " + fromSide + " to " + toSide); + return 1; + } else { + console.log("Move 1 from " + fromSide + " to " + middle); + console.log("Move 1 from " + middle + " to " + toSide); + return 2; + } + } else { + if (fromSide === middle || toSide === middle) { + // 此状况是 从 左移到中 (另一个是 右) + // ! 这是相邻的两个柱子移动需要找到第三个柱子 将 N-1 个从 from 移动到第三个柱子 第 N 层移到 toSide 后 ,再将 N-1 层从第三个柱子移到 toSide + let anotherToSide = (fromSide === left || toSide === left) ? right : left; + let countNum1 = processMoving(layerNum - 1, left, middle, right, fromSide, anotherToSide); + let countNum2 = 1; + console.log("Move " + layerNum +" from " + fromSide + " to " + toSide); + let countNum3 = processMoving(layerNum - 1, left, middle, right, anotherToSide, toSide); + return countNum1 + countNum2 + countNum3; + } else { + // ! 从左 移动到 右 或者 从右移动到 左 + let countNum1 = processMoving(layerNum - 1, left, middle, right, fromSide, toSide); + let countNum2 = 1; + console.log("Move " + layerNum + " from " + fromSide + " to " + middle); + let countNum3 = processMoving(layerNum - 1, left, middle, right, toSide, fromSide); + let countNum4 = 1; + console.log("Move " + layerNum + " from " + middle + " to " + toSide); + let countNum5 = processMoving(layerNum - 1, left, middle, right, fromSide, toSide); + return countNum1 + countNum2 + countNum3 + countNum4 + countNum5; + } + } +} + + +function hanoiAdvanceProblems(layerNum, left, middle, right) { + if (layerNum < 1) { + return 0; + } + + return processMoving(layerNum, left, middle, right, left, right); +} + +let layerNum = 2; +let left = 'left'; +let middle = 'middle'; +let right = 'right'; +console.log(hanoiAdvanceProblems(layerNum, left, middle, right)); \ No newline at end of file diff --git a/NowCoder/CodingInterview/reverseStackByRecursion.js b/NowCoder/CodingInterview/reverseStackByRecursion.js new file mode 100644 index 0000000..89c43a2 --- /dev/null +++ b/NowCoder/CodingInterview/reverseStackByRecursion.js @@ -0,0 +1,49 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-10 09:41:19 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-10 09:52:26 + */ + +/***** + * + * + * 只使用递归而不使用其他数据结构实现一个栈的逆序 + * + * + */ + + +// 第一步构造返回栈底元素的方法 +function getStackBottomElement(stackData){ + let tempData = stackData.pop(); // 栈顶元素 + if (stackData.length ===0) { + return tempData; + } else { + let preData = getStackBottomElement(stackData); + stackData.push(tempData); + return preData; // 栈不为空时返回的是前一个元素 + } +} + +// 对栈进行逆序 +// 到底之后逐层返回,压完就好 +function reverseStackByRecursion(stackData) { + if (stackData.length === 0) { + return; + } + let tempBottomData = getStackBottomElement(stackData); + reverseStackByRecursion(stackData); + stackData.push(tempBottomData); +} + + +let stackData = [5, 2, 4, 6, 8, 1, 4, 9]; + +console.log(stackData); + +reverseStackByRecursion(stackData); + +console.log(stackData); + +// console.log(getStackBottomElement(stackData)); // 5 diff --git a/NowCoder/CodingInterview/sortStackByStack.js b/NowCoder/CodingInterview/sortStackByStack.js new file mode 100644 index 0000000..45cc3e1 --- /dev/null +++ b/NowCoder/CodingInterview/sortStackByStack.js @@ -0,0 +1,35 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-10 09:16:41 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-10 09:31:25 + */ + +/****** + * + * 用一个栈实现另一个栈的排序 + * + * 只允许用一个辅助栈 + * + * + */ + +function sortStackByStack(stackData){ + let helpStack = []; + while (stackData.length !== 0) { + let tempData = stackData.pop(); + while (helpStack.length !== 0 && tempData > helpStack[helpStack.length - 1]) { + stackData.push(helpStack.pop()); + } + helpStack.push(tempData); + // console.log(stackData); + } + while (helpStack.length !== 0) { + stackData.push(helpStack.pop()); + } + return stackData; +} + +let stackData = [5,2,4,6,8,1,4,9]; +console.log(stackData); +console.log(sortStackByStack(stackData)); \ No newline at end of file From 6d15524b814628b7cbf97b946b8ee42022b286c2 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 10 May 2019 12:14:45 +0800 Subject: [PATCH 168/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E9=9D=9E=E9=80=92=E5=BD=92=E6=96=B9=E6=B3=95=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E6=94=B9=E8=BF=9B=E7=89=88=E6=B1=89=E8=AF=BA=E5=A1=94=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CodingInterview/hanoiAdvanceProblems.js | 55 ++++++++++++++++++- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/NowCoder/CodingInterview/hanoiAdvanceProblems.js b/NowCoder/CodingInterview/hanoiAdvanceProblems.js index 39a3004..0610574 100644 --- a/NowCoder/CodingInterview/hanoiAdvanceProblems.js +++ b/NowCoder/CodingInterview/hanoiAdvanceProblems.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-05-10 10:08:12 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-05-10 10:50:28 + * @Last Modified time: 2019-05-10 12:13:11 */ /******* @@ -62,8 +62,57 @@ function hanoiAdvanceProblems(layerNum, left, middle, right) { return processMoving(layerNum, left, middle, right, left, right); } -let layerNum = 2; +let layerNum = 3; let left = 'left'; let middle = 'middle'; let right = 'right'; -console.log(hanoiAdvanceProblems(layerNum, left, middle, right)); \ No newline at end of file +console.log(hanoiAdvanceProblems(layerNum, left, middle, right)); + + +console.log("----------------------------------------"); +console.log("----------------------------------------"); + +// ! 非递归方法解决改进版汉诺塔问题 +// 只有四个动作 +let Action = { + No : 0, + LToM : 1, + MToL : 2, + MToR : 3, + RToM : 4 +} + + +function hanoiAdvanceProblemsWithoutRecursion(layerNum, left, middle, right) { + let leftStack = []; + let middleStack = []; + let rightStack = []; + leftStack.push(Number.MAX_SAFE_INTEGER); + middleStack.push(Number.MAX_SAFE_INTEGER); + rightStack.push(Number.MAX_SAFE_INTEGER); + for (let i = layerNum; i > 0; i--) { + leftStack.push(i); + } + let actionRecord = [Action.No]; + let stepCounter = 0; + while (rightStack.length !== layerNum + 1) { + stepCounter += fromStacktoTostack(actionRecord, Action.MToL, Action.LToM, leftStack, middleStack, left, middle); + stepCounter += fromStacktoTostack(actionRecord, Action.LToM, Action.MToL, middleStack, leftStack, middle, left); + stepCounter += fromStacktoTostack(actionRecord, Action.RToM, Action.MToR, middleStack, rightStack, middle, right); + stepCounter += fromStacktoTostack(actionRecord, Action.MToR, Action.RToM, rightStack, middleStack, right, middle); + } + + return stepCounter; +} + +function fromStacktoTostack(actionRecord, preAction, currentAction, fromStack, toStack, fromSide, toSide) { + if (actionRecord[0] !== preAction && fromStack[fromStack.length - 1] < toStack[toStack.length - 1]) { + toStack.push(fromStack.pop()); + console.log("Move " + toStack[toStack.length - 1] + " from " + fromSide + " to " + toSide); + actionRecord[0] = currentAction; + return 1; + } + return 0; +} + +console.log(hanoiAdvanceProblemsWithoutRecursion(layerNum, left, middle, right)); \ No newline at end of file From 6969dd08954177216f0b82000b274c62271bf062 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 13 May 2019 10:19:08 +0800 Subject: [PATCH 169/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9A=84=E5=B8=B8=E7=94=A8=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../checkIfLinkListPalindrome.js | 70 +++++++++++++++++++ .../commonPartOfTwoLinkList.js | 41 +++++++++++ .../CodingInterview/hanoiAdvanceProblems.js | 4 +- 3 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 NowCoder/CodingInterview/checkIfLinkListPalindrome.js create mode 100644 NowCoder/CodingInterview/commonPartOfTwoLinkList.js diff --git a/NowCoder/CodingInterview/checkIfLinkListPalindrome.js b/NowCoder/CodingInterview/checkIfLinkListPalindrome.js new file mode 100644 index 0000000..a848887 --- /dev/null +++ b/NowCoder/CodingInterview/checkIfLinkListPalindrome.js @@ -0,0 +1,70 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-13 09:35:02 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-13 10:16:25 + */ + + +/****** + * + * + * 判断一个链表是不是回文结构 + * + * + */ + + +// 最简单方法遍历两次 +function checkIfLinkListPalindrome(pHead){ + if (pHead === null) { + return false; + } + let nodeStack = []; + let tempNode = pHead; + while (tempNode !== null) { + nodeStack.push(tempNode.val); + tempNode = tempNode.next; + } + while (tempNode.length !== 0) { + let lastTempVal = tempNode.pop() + if (lastTempVal !== pHead.val) { + return false; + } + pHead = pHead.next; + } + return true; +} + + +// 省去一半存储空间的解法 +// ! 使用快慢指针 省去一半存储空间 +function checkIfLinkListPalindrome2(pHead){ + if (pHead === null) { + return false; + } + let slowPoint = pHead; + let fastPoint = pHead; + while (slowPoint.next !== null && fastPoint.next.next !== null) { + slowPoint = slowPoint.next; + fastPoint = fastPoint.next.next; + } + + fastPoint = slowPoint.next; + let halfNodeStack = []; + while(fastPoint !== null) { + halfNodeStack.push(fastPoint.val); + fastPoint = fastPoint.next; + } + let tempHead = pHead; + while(halfNodeStack.length !==0){ + let tempNodeVal = halfNodeStack.pop(); + if (tempHead.val !== tempNodeVal) { + return false; + } + tempHead = tempHead.next; + } + + return true; + +} \ No newline at end of file diff --git a/NowCoder/CodingInterview/commonPartOfTwoLinkList.js b/NowCoder/CodingInterview/commonPartOfTwoLinkList.js new file mode 100644 index 0000000..b93b1fc --- /dev/null +++ b/NowCoder/CodingInterview/commonPartOfTwoLinkList.js @@ -0,0 +1,41 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-13 09:26:26 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-13 09:32:46 + */ + + +/****** + * + * 打印两个有序链表的公共部分 + * + * + */ + +function ListNode(val) { + this.val = val; + this.next = null; +} + +function commonPartOfTwoLinkList(pHead1, pHead2){ + let commonNodes = []; + if (pHead1 === null || pHead2 === null) { + return commonNodes; + } + + while (pHead1 !== null && pHead2 !== null) { + if (pHead1.val < pHead2.val) { + pHead1 = pHead1.next; + } else if (pHead1.val > pHead2.val) { + pHead2 = pHead2.next; + } else { + commonNodes.push(pHead1.val); + pHead1 = pHead1.next; + pHead2 = pHead2.next; + } + } + + return commonNodes; + +} \ No newline at end of file diff --git a/NowCoder/CodingInterview/hanoiAdvanceProblems.js b/NowCoder/CodingInterview/hanoiAdvanceProblems.js index 0610574..aec38a0 100644 --- a/NowCoder/CodingInterview/hanoiAdvanceProblems.js +++ b/NowCoder/CodingInterview/hanoiAdvanceProblems.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-05-10 10:08:12 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-05-10 12:13:11 + * @Last Modified time: 2019-05-10 12:28:00 */ /******* @@ -105,7 +105,9 @@ function hanoiAdvanceProblemsWithoutRecursion(layerNum, left, middle, right) { return stepCounter; } +// 需要使用数组 actionRecord 来记录上一次的操作是什么,防止相邻 逆序 function fromStacktoTostack(actionRecord, preAction, currentAction, fromStack, toStack, fromSide, toSide) { + // ! 判定四个动作中的哪一个合法(判定条件是 只能从小往大里面压 并且不能压相邻逆序的栈) if (actionRecord[0] !== preAction && fromStack[fromStack.length - 1] < toStack[toStack.length - 1]) { toStack.push(fromStack.pop()); console.log("Move " + toStack[toStack.length - 1] + " from " + fromSide + " to " + toSide); From fb7c967b0ac7a723640c444ec85f076315406f02 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 15 May 2019 19:03:21 +0800 Subject: [PATCH 170/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=AD=A3=E5=88=99?= =?UTF-8?q?=E8=A1=A8=E8=BE=BE=E5=BC=8F=E5=8C=B9=E9=85=8D=E7=9A=84=E6=9C=89?= =?UTF-8?q?=E6=95=88=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/settings.json | 4 ++ NowCoder/Leetcode/lastRemaining_Solution.js | 5 +- NowCoder/Leetcode/matchParren.js | 66 +++++++++++++++++--- TestProjects/ByteDance/20190427AmbashCase.js | 27 ++++++++ 4 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 .vscode/settings.json create mode 100644 TestProjects/ByteDance/20190427AmbashCase.js diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..3590e83 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "fileheader.LastModifiedBy": "SkylineBin", + "fileheader.Author": "SkylineBin" +} \ No newline at end of file diff --git a/NowCoder/Leetcode/lastRemaining_Solution.js b/NowCoder/Leetcode/lastRemaining_Solution.js index 695b608..3fb048d 100644 --- a/NowCoder/Leetcode/lastRemaining_Solution.js +++ b/NowCoder/Leetcode/lastRemaining_Solution.js @@ -59,4 +59,7 @@ function LastRemaining_Solution(n, m) { let n = 5; let m = 2; -console.log(LastRemaining_Solution(n, m)); \ No newline at end of file +console.log(LastRemaining_Solution(n, m)); + +// 约瑟夫环问题 解决方案 + diff --git a/NowCoder/Leetcode/matchParren.js b/NowCoder/Leetcode/matchParren.js index 6414918..35e2e35 100644 --- a/NowCoder/Leetcode/matchParren.js +++ b/NowCoder/Leetcode/matchParren.js @@ -9,7 +9,7 @@ * */ -function match(s, pattern) { +function matchOld(s, pattern) { // write code here s === undefined ? '': s; pattern === undefined ? '' : pattern; @@ -27,7 +27,7 @@ function match(s, pattern) { pattern[i + 1] === undefined ? '' : pattern[i + 1]; if (pattern[i+1] !== '*') { if (s[i] === pattern[i] || ( s[i] !== '' && pattern[i] === '.')) { - return match(s.slice(1), pattern.slice(1)); + return matchOld(s.slice(1), pattern.slice(1)); } else { return false; } @@ -35,12 +35,12 @@ function match(s, pattern) { // 当 pattern 的下一个字符是 * if (s[i] === pattern[i] || (s[i] !== '' && pattern[i] === '.')) { // 都表示当前的这个字符是相同的 if (pattern[i] === '.') { - return match(String(s[s.length - 1]), String(pattern[pattern.length - 1])); + return matchOld(String(s[s.length - 1]), String(pattern[pattern.length - 1])); } - return match(s, pattern.slice(2)) || match(s.slice(1), pattern); + return matchOld(s, pattern.slice(2)) || matchOld(s.slice(1), pattern); } else { // 当前字符不相同,下一个是*,*前面的字符可能出现 0 次 - return match(s, pattern.slice(2)); + return matchOld(s, pattern.slice(2)); } } } @@ -51,6 +51,56 @@ function match(s, pattern) { // "bcbbabab",".*a*a" // var arr1 = 'a'; // var arr2 = '.'; -var arr1 = 'bcbbabab'; -var arr2 = '.*a*a'; -console.log(match(arr1, arr2)); \ No newline at end of file +// var arr1 = 'bcbbabab'; +// var arr2 = '.*a*a'; +// console.log(matchOld(arr1, arr2)); + + +// 重新新的代码 +//s, pattern都是字符串 +function match(s, pattern) { + if (s.length === 0 && pattern.length === 0){ + // s 和 pattern 都为空,可以匹配 + return true; + } else if (s.length !== 0 && pattern.length === 0) { + // s 不为空,pattern 为空,不可以匹配 + return false; + } else if (s.length ===0 && pattern.length !== 0){ + // s为空,pattern 不为空,只有第二个字符是*时可能出现 + if (pattern.length > 1 && pattern[1] === '*') { + return match(s,pattern.slice(2)); + } else { + return false; + } + } else { + + // 第二个字符是 * 时需要考虑 + if (pattern.length > 1 && pattern[1] === '*') { + if (s[0] !== pattern[0] && pattern[0] !== '.') { + // 此时的 * 号可视为前一个字符出现 0 次 + return match(s, pattern.slice(2)); + } else { + // 第一个字符可以匹配就需要考虑: 1.*还是让前一个字符出现0次,吞掉前一字符; + // 2.*让前一个字符出现一次,此时*号省略,匹配下一字符; + // 3.*让前一字符出现2次以上,匹配S的后续字符 + return match(s, pattern.slice(2)) || match(s.slice(1), pattern.slice(2)) || match(s.slice(1), pattern); + } + } else { + // 第二个字符不是 * + if (s[0] ===pattern[0] || pattern[0] === '.') { + // 匹配了当前字符,匹配下一个字符 + return match(s.slice(1), pattern.slice(1)); + } else { + // 当前字符不匹配,返回false + return false; + } + } + } +} + +// 以上代码已通过 + +var arr1 = 'aaa'; +var arr2 = 'ab*a'; +console.log(match(arr1, arr2)); + diff --git a/TestProjects/ByteDance/20190427AmbashCase.js b/TestProjects/ByteDance/20190427AmbashCase.js new file mode 100644 index 0000000..277e776 --- /dev/null +++ b/TestProjects/ByteDance/20190427AmbashCase.js @@ -0,0 +1,27 @@ +/****** + * + * 字节跳动 春招技术类实习生笔试第一题 + * + * 给定 N 个建筑物,3个特工,限定 特工之间潜伏的最大距离 D + * + * 两个特工不能埋伏在同一地点 + * 特工之间无差异,相同的位置算是一种方案 + * + * 输入 N 和 D 以及 建筑物位置数组 (从小到大排列) + * + */ + +function findAmbashCase(position, distance){ + + + this.dfs = function (){ + + } + + + +} + + +let position = [1, 2, 3, 4, 5]; +let distance = 3; From 54b86bd9f691ab637a587b4389a390b4bf26e370 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 15 May 2019 19:40:53 +0800 Subject: [PATCH 171/274] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E7=AC=ACk=E5=B0=8F=E7=9A=84=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 递归与非递归解法 --- NowCoder/Leetcode/kthSmallNode.js | 73 +++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 NowCoder/Leetcode/kthSmallNode.js diff --git a/NowCoder/Leetcode/kthSmallNode.js b/NowCoder/Leetcode/kthSmallNode.js new file mode 100644 index 0000000..63a5226 --- /dev/null +++ b/NowCoder/Leetcode/kthSmallNode.js @@ -0,0 +1,73 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-15 19:03:58 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-15 19:40:17 + */ + + +/***** + * + * 给定一棵二叉搜索树, 请找出其中的第k小的结点。 + * 例如,( 5, 3, 7, 2, 4, 6, 8) 中, 按结点数值大小顺序第三小结点的值为4。 + * + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +// 中序遍历存节点到栈中,取第 K个节点 + +function KthNode(pRoot, k) { + if (pRoot === null || k === 0) { + return null; + } + let nodeStacks = []; + this.inOrderTraverseNode = function (node, nodeArr) { + if (node !== null) { + this.inOrderTraverseNode(node.left, nodeArr); + nodeArr.push(node); + this.inOrderTraverseNode(node.right, nodeArr); + } else { + return; + } + } + + this.inOrderTraverseNode(pRoot, nodeStacks); + if (nodeStacks.length < k) { + return null; + } else { + return nodeStacks[k - 1]; + } + +} + +// 非递归的中序遍历解法 + +function KthNode2(pRoot, k) { + if (pRoot === null || k === 0) { + return null; + } + let counter = 0; + let nodeStacks = []; + let tempNode = pRoot; + do{ + if (tempNode !== null) { + nodeStacks.push(tempNode); + tempNode = tempNode.left; + } else { + tempNode = nodeStacks.pop(); + counter++; + if (counter === k) { + return tempNode; + } + tempNode = tempNode.right; + } + } + while(tempNode!==null || nodeStacks.length !== 0); + return null; +} \ No newline at end of file From 456462942dc1e7a8f36609533f2633bfef27e8d1 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 15 May 2019 20:41:05 +0800 Subject: [PATCH 172/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8dfs=20=E8=A7=A3?= =?UTF-8?q?=E5=86=B3=E6=9C=BA=E5=99=A8=E4=BA=BA=E8=B5=B0=E6=96=B9=E6=A0=BC?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/movingCountRobot.js | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 NowCoder/Leetcode/movingCountRobot.js diff --git a/NowCoder/Leetcode/movingCountRobot.js b/NowCoder/Leetcode/movingCountRobot.js new file mode 100644 index 0000000..c7ab388 --- /dev/null +++ b/NowCoder/Leetcode/movingCountRobot.js @@ -0,0 +1,81 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-15 19:42:12 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-15 20:39:34 + */ + +/***** + * + * 地上有一个m行和n列的方格。 一个机器人从坐标0, 0 的格子开始移动, + * 每一次只能向左, 右, 上, 下四个方向移动一格, 但是不能进入行坐标和列坐标的数位之和大于k的格子。 + * 例如, 当k为18时, 机器人能够进入方格( 35, 37), 因为3 + 5 + 3 + 7 = 18。 + * 但是, 它不能进入方格( 35, 38), 因为3 + 5 + 3 + 8 = 19。 + * + * 请问该机器人能够达到多少个格子? + * + * + */ + +function movingCount(threshold, rows, cols) { + let countNum = 0; + + // 判断值相加是否超出边界 JavaScript 记得取整 + this.checkIfOutside = function(threshold, curRow, curCol){ + let tempCount = 0; + while(curCol > 0 || curRow > 0){ + if (curCol > 0) { + tempCount += curCol%10; + curCol = parseInt(curCol / 10); + } + if (curRow > 0) { + tempCount += curRow%10; + curRow = parseInt(curRow / 10); + } + } + // 超出边界返回 true + if (tempCount > threshold) { + return true; + } else { + return false; + } + } + + if ((rows ===0 && cols === 0) || threshold < 0) { + return countNum; + } + + if (threshold === 0){ + return 1; + } + + // 用于记录是否遍历过该点 + let labelArr = []; + for (let x = 0; x < rows; x++) { + labelArr[x] = []; + for (let y = 0; y < cols; y++) { + labelArr[x][y] = 0; + } + } + + // dfs 搜索上下左右四个方向,使用 labelArr 标记位置是否遍历过 + this.explore = function (i, j, labelArr, rows, cols, threshold){ + if (i < 0 || i >= rows || j < 0 || j >= cols || this.checkIfOutside(threshold, i, j) || labelArr[i][j] === 1) { + return 0; + } + labelArr[i][j] = 1; + // console.log(i+','+j); + return this.explore(i + 1, j, labelArr, rows, cols, threshold) + + this.explore(i - 1, j, labelArr, rows, cols, threshold) + + this.explore(i, j+1, labelArr, rows, cols, threshold) + + this.explore(i, j-1, labelArr, rows, cols, threshold) + + 1; + } + countNum = this.explore(0, 0, labelArr, rows, cols, threshold); + return countNum; +} + +let threshold = 5; +let rows = 10; +let cols = 10; +console.log(movingCount(threshold, rows, cols)); \ No newline at end of file From 1ebc2606c063e3f9ff420b0252ae9d4183968bdb Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 17 May 2019 09:36:42 +0800 Subject: [PATCH 173/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=A4=A7=E5=B0=8F?= =?UTF-8?q?=E6=A0=B9=E5=A0=86=E8=A7=A3=E5=86=B3=E6=95=B0=E6=8D=AE=E6=B5=81?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E4=B8=AD=E4=BD=8D=E6=95=B0=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/getMidim.js | 104 ++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 NowCoder/Leetcode/getMidim.js diff --git a/NowCoder/Leetcode/getMidim.js b/NowCoder/Leetcode/getMidim.js new file mode 100644 index 0000000..e995efd --- /dev/null +++ b/NowCoder/Leetcode/getMidim.js @@ -0,0 +1,104 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-17 08:54:32 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-17 09:35:20 + */ + +/******* + * + * + * 如何得到一个数据流中的中位数? 如果从数据流中读出奇数个数值, 那么中位数就是所有数值排序之后位于中间的数值。 + * 如果从数据流中读出偶数个数值, 那么中位数就是所有数值排序之后中间两个数的平均值。 + * 我们使用Insert() 方法读取数据流, 使用GetMedian() 方法获取当前读取数据的中位数。 + * + * + * + */ + +let littleHeap = []; +let bigHeap = []; + +// 使用完全二叉树的思想实现 +// 大根堆 和 小根堆 + +function Insert(num) { + if (bigHeap.length === 0) { + bigHeap.push(num); + }else { + if (num <= bigHeap[0]) { + bigHeap.push(num); + } else { + littleHeap.push(num); + } + } + + + + // 将堆调整成大根堆 用于存较小那部分数字 + this.heapBigSort = function(arrays) { + + for (let index = 0; index < arrays.length; index++) { + while (arrays[index] > arrays[parseInt((index - 1) / 2)]) { + this.swap(arrays, index, parseInt((index - 1) / 2)); + index = parseInt((index - 1) / 2); + } + } + + } + + // 将堆调整成小根堆 用于存较大那部分数 + this.heapLittleSort = function(arrays) { + for (let index = 0; index < arrays.length; index++) { + while (arrays[index] < arrays[parseInt((index - 1) / 2)]) { + this.swap(arrays, index, parseInt((index - 1) / 2)); + index = parseInt((index - 1) / 2); + } + } + } + + this.swap = function (arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; + } + + if (bigHeap.length - littleHeap.length > 1) { + let tempNode = bigHeap[0]; + bigHeap = bigHeap.slice(1); + littleHeap.push(tempNode); + } else if (littleHeap.length - bigHeap.length > 1) { + let tempNode = littleHeap[0]; + littleHeap = littleHeap.slice(1); + bigHeap.push(tempNode); + } + this.heapBigSort(bigHeap); + this.heapLittleSort(littleHeap); +} + +function GetMedian() { + let midnum = null; + if (bigHeap.length===0 && littleHeap.length === 0) { + return midnum; + } + if (bigHeap.length > littleHeap.length) { + midnum = bigHeap[0]; + } else if(littleHeap.length > bigHeap.length) { + midnum = littleHeap[0]; + } else { + // midnum = parseInt((bigHeap[0] + littleHeap[0])/2); + midnum = (bigHeap[0] + littleHeap[0])/2; + } + return midnum; +} + + +Insert(1); +Insert(2); +console.log(GetMedian()); +Insert(3); +Insert(4); +console.log(GetMedian()); +Insert(5); +console.log(GetMedian()); +Insert(6); From 71b8e8681cbd23bf25d7e99086723de5dc344514 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 17 May 2019 14:02:16 +0800 Subject: [PATCH 174/274] =?UTF-8?q?=E6=89=BE=E5=88=B0=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=BB=93=E7=82=B9=E5=88=B0=E5=8F=B6=E5=AD=90=E7=BB=93?= =?UTF-8?q?=E7=82=B9=E7=9A=84=E8=B7=AF=E5=BE=84=E9=9B=86=E5=90=88=EF=BC=8C?= =?UTF-8?q?=E4=BD=BF=E5=85=B6=E7=AD=89=E4=BA=8E=E4=B8=80=E4=B8=AA=E6=95=B0?= =?UTF-8?q?=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/findPathofBinary.js | 142 ++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 NowCoder/Leetcode/findPathofBinary.js diff --git a/NowCoder/Leetcode/findPathofBinary.js b/NowCoder/Leetcode/findPathofBinary.js new file mode 100644 index 0000000..a323b44 --- /dev/null +++ b/NowCoder/Leetcode/findPathofBinary.js @@ -0,0 +1,142 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-17 10:26:16 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-17 11:32:57 + */ + + +/***** + * + * 输入一颗二叉树的跟节点和一个整数, 打印出二叉树中结点值的和为输入整数的所有路径。 + * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 + * (注意: 在返回值的list中, 数组长度大的数组靠前) + * + * + * + */ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +// 找出所有路径 +function FindAllPath(root, expectNumber) { + let pathArr = []; + if (root === null) { + return pathArr; + } + + // 考虑使用 dfs 完成路径得到搜索 + this.dfs = function (tempRoot, expectNumber, currentNum, currentArr, pathArr) { + if (tempRoot === null) { + currentArr = []; + currentNum = 0; + return; + } + + let tempArr = currentArr.slice(0); + + if (currentNum + tempRoot.val === expectNumber) { + tempArr.push(tempRoot.val); + pathArr.push(tempArr); + return; + } else if (currentNum + tempRoot.val < expectNumber) { + tempArr.push(tempRoot.val); + currentNum += tempRoot.val; + if (tempRoot.left !== null) { + this.dfs(tempRoot.left, expectNumber, currentNum, tempArr, pathArr); + } + if (tempRoot.right !== null) { + this.dfs(tempRoot.right, expectNumber, currentNum, tempArr, pathArr); + } + + } else { + tempArr = []; + currentNum = 0; + return; + } + } + let currentNode = root; + let nodeArrays = []; + nodeArrays.push(currentNode); + while (nodeArrays.length !== 0) { + let tempNode = nodeArrays[0]; + nodeArrays = nodeArrays.slice(1); + if (tempNode.left !== null) { + nodeArrays.push(tempNode.left); + } + if (tempNode.right !== null) { + nodeArrays.push(tempNode.right); + } + this.dfs(tempNode, expectNumber, 0, [], pathArr); + } + + pathArr.sort((a, b) => { + return b.length - a.length; + }) + + return pathArr; +} + + +// 找出根节点到叶子节点的所有路径 +function FindPath(root, expectNumber) { + let pathArr = []; + if (root === null) { + return pathArr; + } + + // 考虑使用 dfs 完成路径得到搜索 + this.dfs = function (tempRoot, expectNumber, currentNum, currentArr, pathArr) { + if (tempRoot === null) { + currentArr = []; + currentNum = 0; + return; + } + + let tempArr = currentArr.slice(0); + + if (currentNum + tempRoot.val === expectNumber && tempRoot.left === null && tempRoot.right === null) { + tempArr.push(tempRoot.val); + pathArr.push(tempArr); + return; + } else if (currentNum + tempRoot.val < expectNumber) { + tempArr.push(tempRoot.val); + currentNum += tempRoot.val; + if (tempRoot.left !== null) { + this.dfs(tempRoot.left, expectNumber, currentNum, tempArr, pathArr); + } + if (tempRoot.right !== null) { + this.dfs(tempRoot.right, expectNumber, currentNum, tempArr, pathArr); + } + + } else { + tempArr = []; + currentNum = 0; + return; + } + } + let currentNode = root; + let nodeArrays = []; + nodeArrays.push(currentNode); + while (nodeArrays.length !== 0) { + let tempNode = nodeArrays[0]; + nodeArrays = nodeArrays.slice(1); + if (tempNode.left !== null) { + nodeArrays.push(tempNode.left); + } + if (tempNode.right !== null) { + nodeArrays.push(tempNode.right); + } + this.dfs(tempNode, expectNumber, 0, [], pathArr); + } + + pathArr.sort((a, b) => { + return b.length - a.length; + }) + + return pathArr; +} From 8ecd0ff47f3e75572427d1f0f90249ffb91f30e5 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 17 May 2019 14:02:50 +0800 Subject: [PATCH 175/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=B0=86=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E8=BD=AC=E6=8D=A2=E6=88=90=E9=A1=BA=E5=BA=8F=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=9F=BA=E7=A1=80=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/binaryTesing.js | 85 +++++++++++++++++++++ Leetcode/testAlg.js | 112 ++++++++++++++++++++-------- Leetcode/tools/arrayToBinaryTree.js | 53 +++++++++++++ 3 files changed, 219 insertions(+), 31 deletions(-) create mode 100644 Leetcode/binaryTesing.js create mode 100644 Leetcode/tools/arrayToBinaryTree.js diff --git a/Leetcode/binaryTesing.js b/Leetcode/binaryTesing.js new file mode 100644 index 0000000..e79f097 --- /dev/null +++ b/Leetcode/binaryTesing.js @@ -0,0 +1,85 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-17 11:05:01 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-17 11:30:03 + */ + + +const arraytoBinaryTree = require('./tools/arrayToBinaryTree'); + + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +function FindPath(root, expectNumber) { + let pathArr = []; + if (root === null) { + return pathArr; + } + + // 考虑使用 dfs 完成路径得到搜索 + this.dfs = function (tempRoot, expectNumber, currentNum, currentArr, pathArr) { + if (tempRoot === null) { + currentArr = []; + currentNum = 0; + return; + } + + let tempArr = currentArr.slice(0); + + if (currentNum + tempRoot.val === expectNumber && tempRoot.left === null && tempRoot.right === null) { + tempArr.push(tempRoot.val); + pathArr.push(tempArr); + return; + } else if (currentNum + tempRoot.val < expectNumber) { + tempArr.push(tempRoot.val); + currentNum += tempRoot.val; + if (tempRoot.left !== null) { + this.dfs(tempRoot.left, expectNumber, currentNum, tempArr, pathArr); + } + if (tempRoot.right !== null) { + this.dfs(tempRoot.right, expectNumber, currentNum, tempArr, pathArr); + } + + } else { + tempArr = []; + currentNum = 0; + return; + } + } + let currentNode = root; + let nodeArrays = []; + nodeArrays.push(currentNode); + while (nodeArrays.length !== 0) { + let tempNode = nodeArrays[0]; + nodeArrays = nodeArrays.slice(1); + if (tempNode.left !== null) { + nodeArrays.push(tempNode.left); + } + if (tempNode.right !== null) { + nodeArrays.push(tempNode.right); + } + this.dfs(tempNode, expectNumber, 0, [], pathArr); + } + + pathArr.sort((a, b) => { + return b.length - a.length; + }) + + return pathArr; +} + + +let arr1 = [1,2,3,4,5,6,7]; + +let result = arraytoBinaryTree(arr1); +console.log(result); + +console.log("------------------------------------------"); + +let paths = FindPath(result, 6); +console.log(paths); diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js index 9be1c58..af00cf4 100644 --- a/Leetcode/testAlg.js +++ b/Leetcode/testAlg.js @@ -246,11 +246,11 @@ const arrayToTreeNode = require('./tools/treeNode'); // } -function TreeNode(x) { - this.val = x; - this.left = null; - this.right = null; -} +// function TreeNode(x) { +// this.val = x; +// this.left = null; +// this.right = null; +// } // function isSymmetrical(pRoot) // { // let symmetrical = false; @@ -275,34 +275,84 @@ function TreeNode(x) { // } -function Serialize(pRoot) { - // 使用前序遍历的形式访问整个二叉树 - let nodeStr = ''; - if (pRoot === null) { - nodeStr += '@,'; - return nodeStr; - } - nodeStr += pRoot.val + ','; - nodeStr += Serialize(pRoot.left); - nodeStr += Serialize(pRoot.right); - return nodeStr; -} +// function Serialize(pRoot) { +// // 使用前序遍历的形式访问整个二叉树 +// let nodeStr = ''; +// if (pRoot === null) { +// nodeStr += '@,'; +// return nodeStr; +// } +// nodeStr += pRoot.val + ','; +// nodeStr += Serialize(pRoot.left); +// nodeStr += Serialize(pRoot.right); +// return nodeStr; +// } -let index = -1; +// let index = -1; -function Deserialize(s) { - index++; - if (index >= s.length) { - return null; +// function Deserialize(s) { +// index++; +// if (index >= s.length) { +// return null; +// } +// let nodeArr = s.split(','); +// let treeNode = null; +// if (nodeArr[index] !== '@') { +// treeNode = new TreeNode(nodeArr[index]); +// treeNode.left = Deserialize(s); +// treeNode.right = Deserialize(s); +// } +// return treeNode; +// } + + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +function FindPath(root, expectNumber) { + let pathArr = []; + + // 考虑使用 dfs 完成路径得到搜索 + this.dfs = function (tempRoot, expectNumber, currentNum, currentArr, pathArr) { + if (tempRoot === null) { + return; + } + if (currentNum + tempRoot.val === expectNumber) { + currentArr.push(tempRoot); + pathArr.push(currentArr); + return; + } else if (currentNum + tempRoot.val < expectNumber) { + currentArr.push(tempRoot); + currentNum += tempRoot.val; + this.dfs(tempRoot.left, expectNumber, currentNum, currentArr, pathArr); + this.dfs(tempRoot.right, expectNumber, currentNum, currentArr, pathArr); + } else { + return; + } } - let nodeArr = s.split(','); - let treeNode = null; - if (nodeArr[index] !== '@') { - treeNode = new TreeNode(nodeArr[index]); - treeNode.left = Deserialize(s); - treeNode.right = Deserialize(s); + let currentNode = root; + let nodeArrays = []; + nodeArrays.push(currentNode); + while (nodeArrays.length !== 0) { + currentNode = nodeArrays[0]; + nodeArrays = nodeArrays.slice(1); + if (currentNode.left !== null) { + nodeArrays.push(currentNode.left); + } + if (currentNode.right !== null) { + nodeArrays.push(currentNode.right); + } + this.dfs(currentNode, expectNumber, 0, [], pathArr); } - return treeNode; + + pathArr.sort((a, b) => { + return b.length - a.length; + }) + + return pathArr; } @@ -312,10 +362,10 @@ let arr2 = [5, 4, "#", 3, "#", 2]; // var tempLink1 = arrayToLinkNode(arr1); // var tempLink2 = arrayToTreeNode(arr2); -var tempTree = arrayToTreeNode(arr2); +var tempTree = arrayToTreeNode(arr1); console.log(tempTree); -let result = Serialize(tempTree); +let result = FindPath(tempTree, ); console.log(result); console.log(Deserialize(result)); diff --git a/Leetcode/tools/arrayToBinaryTree.js b/Leetcode/tools/arrayToBinaryTree.js new file mode 100644 index 0000000..2dc64e6 --- /dev/null +++ b/Leetcode/tools/arrayToBinaryTree.js @@ -0,0 +1,53 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-17 10:52:43 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-17 11:04:23 + */ + + +/******* + * + * 將数组转换成顺序二叉树 + * + * +*/ + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +function arraytoBinaryTree(array) { + if (array.length <= 0) { + return null; + } + if (array.length === 1) { + return new TreeNode(array[0]); + } + + + let node = new TreeNode(array[0]); + let nodeArr = []; + nodeArr.push(node) + let count = 0; + while (2 * count + 1 < array.length) { + if (2 * count + 1 < array.length) { + nodeArr[2 * count + 1] = new TreeNode(array[2 * count + 1]) + nodeArr[count].left = nodeArr[2 * count + 1]; + } + if (2 * count + 2 < array.length) { + nodeArr[2 * count + 2] = new TreeNode(array[2 * count + 2]) + nodeArr[count].right = nodeArr[2 * count + 2]; + } + count++; + } + + return node; +} + +// let arr = [1, 2, 3, 4, 5]; +// console.log(arraytoTreeNode(arr)); + +module.exports = arraytoBinaryTree; \ No newline at end of file From 8a3690789dc31f83fbcb52ed846877f434b1e41f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 17 May 2019 14:39:35 +0800 Subject: [PATCH 176/274] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=BA=8F=E5=88=97=E5=8C=96=E4=B8=8E=E5=8F=8D?= =?UTF-8?q?=E5=BA=8F=E5=88=97=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/binaryTesing.js | 87 ++++++++-------------- NowCoder/Leetcode/serializeAndSerialize.js | 31 ++++---- 2 files changed, 49 insertions(+), 69 deletions(-) diff --git a/Leetcode/binaryTesing.js b/Leetcode/binaryTesing.js index e79f097..65c86ba 100644 --- a/Leetcode/binaryTesing.js +++ b/Leetcode/binaryTesing.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-05-17 11:05:01 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-05-17 11:30:03 + * @Last Modified time: 2019-05-17 14:37:43 */ @@ -15,71 +15,50 @@ function TreeNode(x) { this.right = null; } -function FindPath(root, expectNumber) { - let pathArr = []; - if (root === null) { - return pathArr; +function Serialize(pRoot) { + // 使用前序遍历的形式访问整个二叉树 + let nodeStr = ''; + if (pRoot === null) { + return '#!'; } + nodeStr += pRoot.val + '!'; + nodeStr += Serialize(pRoot.left); + nodeStr += Serialize(pRoot.right); + return nodeStr; +} - // 考虑使用 dfs 完成路径得到搜索 - this.dfs = function (tempRoot, expectNumber, currentNum, currentArr, pathArr) { - if (tempRoot === null) { - currentArr = []; - currentNum = 0; - return; - } - let tempArr = currentArr.slice(0); - - if (currentNum + tempRoot.val === expectNumber && tempRoot.left === null && tempRoot.right === null) { - tempArr.push(tempRoot.val); - pathArr.push(tempArr); - return; - } else if (currentNum + tempRoot.val < expectNumber) { - tempArr.push(tempRoot.val); - currentNum += tempRoot.val; - if (tempRoot.left !== null) { - this.dfs(tempRoot.left, expectNumber, currentNum, tempArr, pathArr); - } - if (tempRoot.right !== null) { - this.dfs(tempRoot.right, expectNumber, currentNum, tempArr, pathArr); - } - - } else { - tempArr = []; - currentNum = 0; - return; - } - } - let currentNode = root; - let nodeArrays = []; - nodeArrays.push(currentNode); - while (nodeArrays.length !== 0) { - let tempNode = nodeArrays[0]; - nodeArrays = nodeArrays.slice(1); - if (tempNode.left !== null) { - nodeArrays.push(tempNode.left); - } - if (tempNode.right !== null) { - nodeArrays.push(tempNode.right); +function Deserialize(s) { + + let nodeArr = s.split('!'); + + this.reConnectTree = function (arrays){ + let tempNode = arrays.shift(); + if (tempNode === '#' || tempNode === '') { + return null; } - this.dfs(tempNode, expectNumber, 0, [], pathArr); + console.log(arrays); + let head = new TreeNode(parseInt(tempNode)); + head.left = this.reConnectTree(arrays); + head.right = this.reConnectTree(arrays); + return head; } - pathArr.sort((a, b) => { - return b.length - a.length; - }) + return this.reConnectTree(nodeArr); - return pathArr; -} +} -let arr1 = [1,2,3,4,5,6,7]; +let arr1 = [8, 6, 10, 5, 7, 9, 11]; let result = arraytoBinaryTree(arr1); console.log(result); console.log("------------------------------------------"); -let paths = FindPath(result, 6); -console.log(paths); +let treeStr = Serialize(result); +console.log(treeStr); + + +let reTree = Deserialize(treeStr); +console.log(reTree); \ No newline at end of file diff --git a/NowCoder/Leetcode/serializeAndSerialize.js b/NowCoder/Leetcode/serializeAndSerialize.js index a620b7d..a48c0a5 100644 --- a/NowCoder/Leetcode/serializeAndSerialize.js +++ b/NowCoder/Leetcode/serializeAndSerialize.js @@ -24,28 +24,29 @@ function Serialize(pRoot) { // 使用前序遍历的形式访问整个二叉树 let nodeStr = ''; if (pRoot === null) { - nodeStr+= '#,'; - return nodeStr; + return '#!'; } - nodeStr += pRoot.val + ','; + nodeStr += pRoot.val + '!'; nodeStr += Serialize(pRoot.left); nodeStr += Serialize(pRoot.right); return nodeStr; } -let index = -1; function Deserialize(s) { - index++; - if (index >= s.length) { - return null; - } - let nodeArr = s.split(','); - let treeNode; - if (nodeArr[index] !== '#') { - treeNode = new TreeNode(parseInt(nodeArr[index])); - treeNode.left = Deserialize(s); - treeNode.right = Deserialize(s); + let nodeArr = s.split('!'); + + this.reConnectTree = function (arrays) { + let tempNode = arrays.shift(); + // ! arrays.shift() 实现队列抛出第一个值的操作 + if (tempNode === '#' || tempNode === '') { + return null; + } + let head = new TreeNode(parseInt(tempNode)); + head.left = this.reConnectTree(arrays); + head.right = this.reConnectTree(arrays); + return head; } - return treeNode; + + return this.reConnectTree(nodeArr); } From 2d8ecd984a81e4c29ae6bfc964ff6a8284c5f70f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 22 May 2019 20:42:33 +0800 Subject: [PATCH 177/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=98=91=E8=8F=87?= =?UTF-8?q?=E8=A1=97=E7=AE=97=E6=B3=95=E6=95=B0=E7=BB=84=E5=8E=BB=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2018Enterprise/arrayUnique-mogujie.js | 49 +++++++++++++++++++ NowCoder/Leetcode/linkTest.js | 12 ----- TestProjects/largeAllone.js | 32 ++++++++++++ 3 files changed, 81 insertions(+), 12 deletions(-) create mode 100644 NowCoder/2018Enterprise/arrayUnique-mogujie.js delete mode 100644 NowCoder/Leetcode/linkTest.js create mode 100644 TestProjects/largeAllone.js diff --git a/NowCoder/2018Enterprise/arrayUnique-mogujie.js b/NowCoder/2018Enterprise/arrayUnique-mogujie.js new file mode 100644 index 0000000..117e78b --- /dev/null +++ b/NowCoder/2018Enterprise/arrayUnique-mogujie.js @@ -0,0 +1,49 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-22 20:26:17 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-22 20:41:10 + */ + + +/****** + * + * 编写一个Javascript函数,传入一个数组,对数组中的元素进行去重并返回一个无重复元素的数组,数组的元素可以是数字、字符串、数组和对象。举例说明: + * 1. 如传入的数组元素为[123, "meili", "123", "mogu", 123],则输出:[123, "meili", "123", "mogu"] + * 2. 如传入的数组元素为[123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"],则输出:[123, [1, 2, 3], [1, "2", 3], "meili"] + * 3. 如传入的数组元素为[123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"],则输出:[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"] + * + * + * + */ + +// 使用 Set 进行构造不重复的数组 +Array.prototype.getUnique = function (){ + // let arr = this; + return [...(new Set(this.map(n => JSON.stringify(n))))].map(m => JSON.parse(m)); +} + + +Array.prototype.unique = function () { + let hash = new Map(); + let result = []; + let tempData; + for (let index = 0; index < this.length; index++) { + if (Object.prototype.toString.call(this[index]) === '[object Object]' || Object.prototype.toString.call(this[index]) === '[object Array]') { + tempData = JSON.stringify(this[index]); + } else { + tempData = this[index]; + } + if (!hash.has(tempData)) { + hash.set(tempData,true); + result.push(this[index]); + } + } + return result; +} + + +let arr = [123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"]; +let arr2 = [123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"]; +console.log(arr2.unique()); +console.log(arr.getUnique()); \ No newline at end of file diff --git a/NowCoder/Leetcode/linkTest.js b/NowCoder/Leetcode/linkTest.js deleted file mode 100644 index b4f05b1..0000000 --- a/NowCoder/Leetcode/linkTest.js +++ /dev/null @@ -1,12 +0,0 @@ -/*** -* -* -* -* -***/ -// ! 本质涉及: - - -// Test Algorithm -// var testNum = 5; -console.log(); \ No newline at end of file diff --git a/TestProjects/largeAllone.js b/TestProjects/largeAllone.js new file mode 100644 index 0000000..c42b4dc --- /dev/null +++ b/TestProjects/largeAllone.js @@ -0,0 +1,32 @@ +/***** + * + * + * + * + */ + +function largeAll(arr,k){ + if (arr.length === 0) { + return 0; + } + + var len = arr.length; + var zeroArr = []; + for (let i = 0; i < arr.length; i++) { + if (arr[i] === 0) { + zeroArr.push(i); + } + } + if (k>= zeroArr.length) { + return len; + } +} + +while (line = readline()) { + var lines = line.split(' '); + var a = parseInt(lines[0]); + var b = parseInt(lines[1]); + // 读取参数完成方法调用 + var m = dictionarySortList(a, b); + print(m); +} \ No newline at end of file From a6459cdd036dec49b4b00b253bd9b4e02f4aa8e6 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 22 May 2019 20:43:11 +0800 Subject: [PATCH 178/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=88=B1=E5=A5=87?= =?UTF-8?q?=E8=89=BA=E7=9A=84=E7=AE=97=E6=B3=95=E7=BB=9F=E8=AE=A1=E5=8C=BA?= =?UTF-8?q?=E9=97=B4=E9=95=BF=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2018Enterprise/countInterval-aqiyi.js | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 NowCoder/2018Enterprise/countInterval-aqiyi.js diff --git a/NowCoder/2018Enterprise/countInterval-aqiyi.js b/NowCoder/2018Enterprise/countInterval-aqiyi.js new file mode 100644 index 0000000..6ff7eff --- /dev/null +++ b/NowCoder/2018Enterprise/countInterval-aqiyi.js @@ -0,0 +1,62 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-17 14:55:41 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-17 14:59:01 + */ + +/**** + * + * 2018 爱奇艺校招一题 + * + * 牛牛的老师给出了一个区间的定义:对于x ≤ y,[x, y]表示x到y之间(包括x和y)的所有连续整数集合。 + * 例如[3,3] = {3}, [4,7] = {4,5,6,7}. + * 牛牛现在有一个长度为n的递增序列,牛牛想知道需要多少个区间并起来等于这个序列。例如: + * {1,2,3,4,5,6,7,8,9,10} + * 最少只需要[1,10]这一个区间 + * {1,3,5,6,7} + * 最少只需要[1,1],[3,3],[5,7]这三个区间 + * + * 输入包括两行, 第一行一个整数n(1≤ n≤ 50), + * 第二行n个整数a[i](1≤ a[i]≤ 50), 表示牛牛的序列, 保证序列是递增的。 + * + * 输入: + * 5 + * 1 3 5 6 7 + * + * 输出: + * 3 + * + * + */ + + +function countNum(arrays) { + let count = 1; + if (arrays.length === 0) { + return 0; + } + if (arrays.length === 1) { + return count; + } + for (let i = 1; i < arrays.length; i++) { + if (arrays[i] - arrays[i - 1] > 1) { + count++; + } + } + return count; +} + +// 注意看读行过程 + +var initPre = readline().split(" "); +var countN = parseInt(initPre[0]); + +var datas = readline().split(" "); +var realdatas = []; + +for (var i = 0; i < countN; i++) { + realdatas.push(parseInt(datas[i])); +} +var result = countNum(realdatas); +print(result); \ No newline at end of file From 1e9bc67942887eb34d84ecade57ddd04cd7d6ad4 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 23 May 2019 16:48:34 +0800 Subject: [PATCH 179/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=80=86=E5=BA=8F?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=95=B4=E6=95=B0=E7=9A=84=E8=A7=A3=E9=A2=98?= =?UTF-8?q?=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/reverseInteger.js | 80 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Leetcode/reverseInteger.js diff --git a/Leetcode/reverseInteger.js b/Leetcode/reverseInteger.js new file mode 100644 index 0000000..37cca64 --- /dev/null +++ b/Leetcode/reverseInteger.js @@ -0,0 +1,80 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-23 16:27:45 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-23 16:47:40 + */ + +/***** + * + * 逆序一个整数 + * Example 1: + * Input: 123 + * Output: 321 + * + * Example 2: + * Input: -123 + * Output: -321 + * Example 3: + * + * Input: 120 + * Output: 21 + * + * + */ + + + +/** + * @param {number} x + * @return {number} + */ +var reverse = function (x) { + if (x === 0) { + return 0; + } + let state = 1; + let MaxNum = 2**31; + if (x < 0) { + state = -1; + x = - x; + } + let num = 0; + while(x > 0){ + num = num*10 + x % 10; + x = parseInt(x/10); + } + num = num * state + if (num >= MaxNum) { + num = 0; + } + if (num < -1*MaxNum) { + num = 0; + } + + return num; +}; + +let x = 123; +console.log(reverse(x)); + + +var reverse2 = function (x) { + let signLabel = true; + let INT_MAX = Math.pow(2, 31); + if (x < 0) { + signLabel = false; + x = Math.abs(x); + } + let backNum = 0; + while (x > 0) { + if (backNum > INT_MAX / 10 || (backNum === INT_MAX / 10 && x % 10 > INT_MAX % 10)) { + return 0; + } + backNum = backNum * 10 + x % 10; + x = parseInt(x / 10); + } + + backNum = signLabel ? backNum : -backNum; + return backNum; +}; \ No newline at end of file From 6354c0e80de959169e0692916238ddf8b5b62949 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 23 May 2019 16:57:14 +0800 Subject: [PATCH 180/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E6=98=AF=E5=90=A6=E6=98=AF=E5=9B=9E=E6=96=87?= =?UTF-8?q?=E6=95=B0=20=E5=B9=B6=E4=BF=AE=E6=94=B9=E9=A2=98=E7=9B=AE?= =?UTF-8?q?=E7=BC=96=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/{twoSum.js => 1.twoSum.js} | 0 Leetcode/{addTwonums.js => 3.addTwonums.js} | 0 ...{reverseInteger.js => 7.reverseInteger.js} | 0 Leetcode/8. stringtoInteger.js | 56 +++++++++++++++++++ Leetcode/9.PalindromeNumber.js | 33 +++++++++++ 5 files changed, 89 insertions(+) rename Leetcode/{twoSum.js => 1.twoSum.js} (100%) rename Leetcode/{addTwonums.js => 3.addTwonums.js} (100%) rename Leetcode/{reverseInteger.js => 7.reverseInteger.js} (100%) create mode 100644 Leetcode/8. stringtoInteger.js create mode 100644 Leetcode/9.PalindromeNumber.js diff --git a/Leetcode/twoSum.js b/Leetcode/1.twoSum.js similarity index 100% rename from Leetcode/twoSum.js rename to Leetcode/1.twoSum.js diff --git a/Leetcode/addTwonums.js b/Leetcode/3.addTwonums.js similarity index 100% rename from Leetcode/addTwonums.js rename to Leetcode/3.addTwonums.js diff --git a/Leetcode/reverseInteger.js b/Leetcode/7.reverseInteger.js similarity index 100% rename from Leetcode/reverseInteger.js rename to Leetcode/7.reverseInteger.js diff --git a/Leetcode/8. stringtoInteger.js b/Leetcode/8. stringtoInteger.js new file mode 100644 index 0000000..eb787db --- /dev/null +++ b/Leetcode/8. stringtoInteger.js @@ -0,0 +1,56 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-23 16:53:39 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-23 16:54:31 + */ + +/**** + * + * String 转 整数 + * + * + */ + +/** + * @param {string} str + * @return {number} + */ +var myAtoi = function (str) { + let i = 0; + let num = 0, + flag = 0, + state = false; + let INT_MAX = Math.pow(2, 31); + while (i < str.length) { + if (str[i] === '-' && num === 0 && flag === 0 && !state) { + state = true; + flag = -1; + } else if (str[i] === '+' && num === 0 && flag === 0 && !state) { + state = true; + flag = 1; + } else if (num === 0 && str[i] === ' ' && !state) { + i++; + continue; + } else if (str[i] >= '0' && str[i] <= '9') { + state = true; + num = num * 10 + parseInt(str[i]); + } else if (str[i] < '0' || str[i] > '9') { + break; + } + + i++; + + } + if (flag === 0) { + flag = 1; + } + if (num > INT_MAX && flag === -1) { + num = INT_MAX; + } else if (num >= INT_MAX && flag === 1) { + num = INT_MAX - 1; + } + + + return num * flag; +}; \ No newline at end of file diff --git a/Leetcode/9.PalindromeNumber.js b/Leetcode/9.PalindromeNumber.js new file mode 100644 index 0000000..82c7251 --- /dev/null +++ b/Leetcode/9.PalindromeNumber.js @@ -0,0 +1,33 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-23 16:55:24 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-23 16:56:19 + */ + +/***** + * + * 判断数字是否是回文数 + * + * + */ + +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function (x) { + let tempArr = []; + x = String(x); + for (let i = 0; i < x.length; i++) { + tempArr.push(x[i]); + } + let j = 0; + while (tempArr.length > 0) { + if (tempArr.pop() !== x[j++]) { + return false; + } + } + + return true; +}; \ No newline at end of file From 90ec78c260c8c5c289a332320fda7e7cee067886 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 23 May 2019 19:24:08 +0800 Subject: [PATCH 181/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=8C=89=E8=A1=8CZ?= =?UTF-8?q?=E5=AD=97=E6=89=93=E5=8D=B0=E8=BE=93=E5=87=BA=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/6.ZigZagConversion.js | 80 ++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Leetcode/6.ZigZagConversion.js diff --git a/Leetcode/6.ZigZagConversion.js b/Leetcode/6.ZigZagConversion.js new file mode 100644 index 0000000..711f051 --- /dev/null +++ b/Leetcode/6.ZigZagConversion.js @@ -0,0 +1,80 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-23 16:58:07 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-23 19:22:59 + */ + + +/**** + * + * Z字打印输出字符串 + * + * Input: s = "PAYPALISHIRING", numRows = 3 + * Output: "PAHNAPLSIIGYIR" + * + * P A H N + * A P L S I I G + * Y I R + * + * + */ + +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function (s, numRows) { + let backStr = ""; + if (s.length <= numRows || numRows === 1) { + return s; + } + let tempArr = []; + for (let i = 0; i < numRows; i++) { + tempArr[i]=[]; + } + let j=0; + let utod = true; + let index = 0; + while(s[j]){ + if (utod) { + tempArr[index++].push(s[j]); + if (index === numRows) { + index = numRows - 1; + utod = false; + } + } else { + if (index === numRows-1 || index === 0) { + tempArr[index].push('#'); + j = j-1; + } else { + tempArr[index].push(s[j]); + } + + if (index === 0) { + index = 0; + utod = true; + } else { + index--; + } + } + // console.log(tempArr); + j++; + } + + tempArr.map(item => { + item.map(tempdata =>{ + if (tempdata !== '#') { + backStr+= tempdata; + } + }) + }) + return backStr; + +}; + +let s = "PAYPALISHIRING", + numRows = 2; + +console.log(convert(s, numRows)); \ No newline at end of file From 9d56add069e05607e97c9ac07f17c2d70fdb26e0 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 24 May 2019 15:09:37 +0800 Subject: [PATCH 182/274] =?UTF-8?q?=E7=90=86=E9=A1=BA=E4=B8=80=E9=81=8D?= =?UTF-8?q?=E6=89=80=E6=9C=89=E7=9A=84=E7=AE=97=E6=B3=95=E7=BC=96=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Leetcode/{checkDatainArray.js => 1.checkDatainArray.js} | 0 NowCoder/Leetcode/{recCover.js => 10.recCover.js} | 0 NowCoder/Leetcode/{numberOf1.js => 11.numberOf1.js} | 0 NowCoder/Leetcode/{doublePower.js => 12.doublePower.js} | 0 NowCoder/Leetcode/{reOrderArray.js => 13.reOrderArray.js} | 0 NowCoder/Leetcode/{findKthToTail.js => 14.findKthToTail.js} | 0 NowCoder/Leetcode/{ReverseList.js => 15.ReverseList.js} | 0 .../{mergeTwosortedLink.js => 16.mergeTwosortedLink.js} | 0 NowCoder/Leetcode/{hasSubtree.js => 17.hasSubtree.js} | 0 NowCoder/Leetcode/{mirrorTree.js => 18.mirrorTree.js} | 0 .../{printMatrixbyClockwise.js => 19.printMatrixbyClockwise.js} | 0 .../{replaceSpaceinString.js => 2.replaceSpaceinString.js} | 0 ...createMinStackStructure.js => 20.createMinStackStructure.js} | 0 NowCoder/Leetcode/{isPopOrder.js => 21.isPopOrder.js} | 0 ...intTreeFromTopToBottom.js => 22.printTreeFromTopToBottom.js} | 0 .../{verifySquenceOfBST.js => 23.verifySquenceOfBST.js} | 0 .../Leetcode/{findPathofBinary.js => 24.findPathofBinary.js} | 0 .../{cloneComplexLinkList.js => 25.cloneComplexLinkList.js} | 0 ...oubleLinkList.js => 26.convertBinaryTreetoDoubleLinkList.js} | 0 .../Leetcode/{permutationString.js => 27.permutationString.js} | 0 ...reThanHalfNum_Solution.js => 28.moreThanHalfNum_Solution.js} | 0 ...tLeastNumbers_Solution.js => 29.getLeastNumbers_Solution.js} | 0 NowCoder/Leetcode/{shiftListNode.js => 3.shiftListNode.js} | 0 ...GreatestSumOfSubArray.js => 30.findGreatestSumOfSubArray.js} | 0 ...en1AndN_Solution.js => 31.numberOf1Between1AndN_Solution.js} | 0 ...ctMinNumberofArray.js => 32.PrintConnectMinNumberofArray.js} | 0 .../{getUglyNumber_Solution.js => 33.getUglyNumber_Solution.js} | 0 .../{firstNotRepeatingChar.js => 34.firstNotRepeatingChar.js} | 0 NowCoder/Leetcode/{inversePairsNum.js => 35.inversePairsNum.js} | 0 ...monNodeofLinkNode.js => 36.findFirstCommonNodeofLinkNode.js} | 0 NowCoder/Leetcode/{getNumberOfK.js => 37.getNumberOfK.js} | 0 NowCoder/Leetcode/{treeDepth.js => 38.treeDepth.js} | 0 NowCoder/Leetcode/{isBalancedTree.js => 39.isBalancedTree.js} | 0 .../{reConstructBinaryTree.js => 4.reConstructBinaryTree.js} | 0 .../{findNumsAppearOnce.js => 40.findNumsAppearOnce.js} | 0 .../{findContinuousSequence.js => 41.findContinuousSequence.js} | 0 .../{findNumbersWithSum.js => 42.findNumbersWithSum.js} | 0 NowCoder/Leetcode/{loopStr.js => 43.loopLeftRotateStr.js} | 0 NowCoder/Leetcode/{reverseWords.js => 44.reverseWords.js} | 0 NowCoder/Leetcode/{isContinuous.js => 45.isContinuous.js} | 0 .../{lastRemaining_Solution.js => 46.lastRemaining_Solution.js} | 0 NowCoder/Leetcode/{sum_Solution.js => 47.sum_Solution.js} | 0 NowCoder/Leetcode/{addTwoNum.js => 48.addTwoNum.js} | 0 NowCoder/Leetcode/{strToInt.js => 49.strToInt.js} | 0 .../{useTwoStackCreatQueue.js => 5.useTwoStackCreatQueue.js} | 0 NowCoder/Leetcode/{duplicate.js => 50.duplicate.js} | 0 NowCoder/Leetcode/{multiply.js => 51.multiply.js} | 0 NowCoder/Leetcode/{matchParren.js => 52.matchParren.js} | 0 NowCoder/Leetcode/{isNumeric.js => 53.isNumeric.js} | 0 .../{firstAppearingOnce.js => 54.firstAppearingOnce.js} | 0 NowCoder/Leetcode/{entryNodeOfLoop.js => 55.entryNodeOfLoop.js} | 0 ...teDuplicationLinkNode.js => 56.deleteDuplicationLinkNode.js} | 0 NowCoder/Leetcode/{getNextNode.js => 57.getNextNode.js} | 0 NowCoder/Leetcode/{isSymmetrical.js => 58.isSymmetrical.js} | 0 .../{printTreewithZhizi.js => 59.printTreewithZhizi.js} | 0 .../{minNumberInRotateArray.js => 6.minNumberInRotateArray.js} | 0 .../Leetcode/{printTreebyLayer.js => 60.printTreebyLayer.js} | 0 .../{serializeAndSerialize.js => 61.serializeAndSerialize.js} | 0 NowCoder/Leetcode/{kthSmallNode.js => 62.kthSmallNode.js} | 0 NowCoder/Leetcode/{getMidim.js => 63.getMidim.js} | 0 NowCoder/Leetcode/{maxInWindows.js => 64.maxInWindows.js} | 0 NowCoder/Leetcode/{hasPath.js => 65.hasPath.js} | 0 .../Leetcode/{movingCountRobot.js => 66.movingCountRobot.js} | 0 NowCoder/Leetcode/{outputFibonacci.js => 7.outputFibonacci.js} | 0 NowCoder/Leetcode/{jumpStep.js => 8.jumpStep.js} | 0 NowCoder/Leetcode/{jumpStepII.js => 9.jumpStepII.js} | 2 +- 66 files changed, 1 insertion(+), 1 deletion(-) rename NowCoder/Leetcode/{checkDatainArray.js => 1.checkDatainArray.js} (100%) rename NowCoder/Leetcode/{recCover.js => 10.recCover.js} (100%) rename NowCoder/Leetcode/{numberOf1.js => 11.numberOf1.js} (100%) rename NowCoder/Leetcode/{doublePower.js => 12.doublePower.js} (100%) rename NowCoder/Leetcode/{reOrderArray.js => 13.reOrderArray.js} (100%) rename NowCoder/Leetcode/{findKthToTail.js => 14.findKthToTail.js} (100%) rename NowCoder/Leetcode/{ReverseList.js => 15.ReverseList.js} (100%) rename NowCoder/Leetcode/{mergeTwosortedLink.js => 16.mergeTwosortedLink.js} (100%) rename NowCoder/Leetcode/{hasSubtree.js => 17.hasSubtree.js} (100%) rename NowCoder/Leetcode/{mirrorTree.js => 18.mirrorTree.js} (100%) rename NowCoder/Leetcode/{printMatrixbyClockwise.js => 19.printMatrixbyClockwise.js} (100%) rename NowCoder/Leetcode/{replaceSpaceinString.js => 2.replaceSpaceinString.js} (100%) rename NowCoder/Leetcode/{createMinStackStructure.js => 20.createMinStackStructure.js} (100%) rename NowCoder/Leetcode/{isPopOrder.js => 21.isPopOrder.js} (100%) rename NowCoder/Leetcode/{printTreeFromTopToBottom.js => 22.printTreeFromTopToBottom.js} (100%) rename NowCoder/Leetcode/{verifySquenceOfBST.js => 23.verifySquenceOfBST.js} (100%) rename NowCoder/Leetcode/{findPathofBinary.js => 24.findPathofBinary.js} (100%) rename NowCoder/Leetcode/{cloneComplexLinkList.js => 25.cloneComplexLinkList.js} (100%) rename NowCoder/Leetcode/{convertBinaryTreetoDoubleLinkList.js => 26.convertBinaryTreetoDoubleLinkList.js} (100%) rename NowCoder/Leetcode/{permutationString.js => 27.permutationString.js} (100%) rename NowCoder/Leetcode/{moreThanHalfNum_Solution.js => 28.moreThanHalfNum_Solution.js} (100%) rename NowCoder/Leetcode/{getLeastNumbers_Solution.js => 29.getLeastNumbers_Solution.js} (100%) rename NowCoder/Leetcode/{shiftListNode.js => 3.shiftListNode.js} (100%) rename NowCoder/Leetcode/{findGreatestSumOfSubArray.js => 30.findGreatestSumOfSubArray.js} (100%) rename NowCoder/Leetcode/{numberOf1Between1AndN_Solution.js => 31.numberOf1Between1AndN_Solution.js} (100%) rename NowCoder/Leetcode/{PrintConnectMinNumberofArray.js => 32.PrintConnectMinNumberofArray.js} (100%) rename NowCoder/Leetcode/{getUglyNumber_Solution.js => 33.getUglyNumber_Solution.js} (100%) rename NowCoder/Leetcode/{firstNotRepeatingChar.js => 34.firstNotRepeatingChar.js} (100%) rename NowCoder/Leetcode/{inversePairsNum.js => 35.inversePairsNum.js} (100%) rename NowCoder/Leetcode/{findFirstCommonNodeofLinkNode.js => 36.findFirstCommonNodeofLinkNode.js} (100%) rename NowCoder/Leetcode/{getNumberOfK.js => 37.getNumberOfK.js} (100%) rename NowCoder/Leetcode/{treeDepth.js => 38.treeDepth.js} (100%) rename NowCoder/Leetcode/{isBalancedTree.js => 39.isBalancedTree.js} (100%) rename NowCoder/Leetcode/{reConstructBinaryTree.js => 4.reConstructBinaryTree.js} (100%) rename NowCoder/Leetcode/{findNumsAppearOnce.js => 40.findNumsAppearOnce.js} (100%) rename NowCoder/Leetcode/{findContinuousSequence.js => 41.findContinuousSequence.js} (100%) rename NowCoder/Leetcode/{findNumbersWithSum.js => 42.findNumbersWithSum.js} (100%) rename NowCoder/Leetcode/{loopStr.js => 43.loopLeftRotateStr.js} (100%) rename NowCoder/Leetcode/{reverseWords.js => 44.reverseWords.js} (100%) rename NowCoder/Leetcode/{isContinuous.js => 45.isContinuous.js} (100%) rename NowCoder/Leetcode/{lastRemaining_Solution.js => 46.lastRemaining_Solution.js} (100%) rename NowCoder/Leetcode/{sum_Solution.js => 47.sum_Solution.js} (100%) rename NowCoder/Leetcode/{addTwoNum.js => 48.addTwoNum.js} (100%) rename NowCoder/Leetcode/{strToInt.js => 49.strToInt.js} (100%) rename NowCoder/Leetcode/{useTwoStackCreatQueue.js => 5.useTwoStackCreatQueue.js} (100%) rename NowCoder/Leetcode/{duplicate.js => 50.duplicate.js} (100%) rename NowCoder/Leetcode/{multiply.js => 51.multiply.js} (100%) rename NowCoder/Leetcode/{matchParren.js => 52.matchParren.js} (100%) rename NowCoder/Leetcode/{isNumeric.js => 53.isNumeric.js} (100%) rename NowCoder/Leetcode/{firstAppearingOnce.js => 54.firstAppearingOnce.js} (100%) rename NowCoder/Leetcode/{entryNodeOfLoop.js => 55.entryNodeOfLoop.js} (100%) rename NowCoder/Leetcode/{deleteDuplicationLinkNode.js => 56.deleteDuplicationLinkNode.js} (100%) rename NowCoder/Leetcode/{getNextNode.js => 57.getNextNode.js} (100%) rename NowCoder/Leetcode/{isSymmetrical.js => 58.isSymmetrical.js} (100%) rename NowCoder/Leetcode/{printTreewithZhizi.js => 59.printTreewithZhizi.js} (100%) rename NowCoder/Leetcode/{minNumberInRotateArray.js => 6.minNumberInRotateArray.js} (100%) rename NowCoder/Leetcode/{printTreebyLayer.js => 60.printTreebyLayer.js} (100%) rename NowCoder/Leetcode/{serializeAndSerialize.js => 61.serializeAndSerialize.js} (100%) rename NowCoder/Leetcode/{kthSmallNode.js => 62.kthSmallNode.js} (100%) rename NowCoder/Leetcode/{getMidim.js => 63.getMidim.js} (100%) rename NowCoder/Leetcode/{maxInWindows.js => 64.maxInWindows.js} (100%) rename NowCoder/Leetcode/{hasPath.js => 65.hasPath.js} (100%) rename NowCoder/Leetcode/{movingCountRobot.js => 66.movingCountRobot.js} (100%) rename NowCoder/Leetcode/{outputFibonacci.js => 7.outputFibonacci.js} (100%) rename NowCoder/Leetcode/{jumpStep.js => 8.jumpStep.js} (100%) rename NowCoder/Leetcode/{jumpStepII.js => 9.jumpStepII.js} (93%) diff --git a/NowCoder/Leetcode/checkDatainArray.js b/NowCoder/Leetcode/1.checkDatainArray.js similarity index 100% rename from NowCoder/Leetcode/checkDatainArray.js rename to NowCoder/Leetcode/1.checkDatainArray.js diff --git a/NowCoder/Leetcode/recCover.js b/NowCoder/Leetcode/10.recCover.js similarity index 100% rename from NowCoder/Leetcode/recCover.js rename to NowCoder/Leetcode/10.recCover.js diff --git a/NowCoder/Leetcode/numberOf1.js b/NowCoder/Leetcode/11.numberOf1.js similarity index 100% rename from NowCoder/Leetcode/numberOf1.js rename to NowCoder/Leetcode/11.numberOf1.js diff --git a/NowCoder/Leetcode/doublePower.js b/NowCoder/Leetcode/12.doublePower.js similarity index 100% rename from NowCoder/Leetcode/doublePower.js rename to NowCoder/Leetcode/12.doublePower.js diff --git a/NowCoder/Leetcode/reOrderArray.js b/NowCoder/Leetcode/13.reOrderArray.js similarity index 100% rename from NowCoder/Leetcode/reOrderArray.js rename to NowCoder/Leetcode/13.reOrderArray.js diff --git a/NowCoder/Leetcode/findKthToTail.js b/NowCoder/Leetcode/14.findKthToTail.js similarity index 100% rename from NowCoder/Leetcode/findKthToTail.js rename to NowCoder/Leetcode/14.findKthToTail.js diff --git a/NowCoder/Leetcode/ReverseList.js b/NowCoder/Leetcode/15.ReverseList.js similarity index 100% rename from NowCoder/Leetcode/ReverseList.js rename to NowCoder/Leetcode/15.ReverseList.js diff --git a/NowCoder/Leetcode/mergeTwosortedLink.js b/NowCoder/Leetcode/16.mergeTwosortedLink.js similarity index 100% rename from NowCoder/Leetcode/mergeTwosortedLink.js rename to NowCoder/Leetcode/16.mergeTwosortedLink.js diff --git a/NowCoder/Leetcode/hasSubtree.js b/NowCoder/Leetcode/17.hasSubtree.js similarity index 100% rename from NowCoder/Leetcode/hasSubtree.js rename to NowCoder/Leetcode/17.hasSubtree.js diff --git a/NowCoder/Leetcode/mirrorTree.js b/NowCoder/Leetcode/18.mirrorTree.js similarity index 100% rename from NowCoder/Leetcode/mirrorTree.js rename to NowCoder/Leetcode/18.mirrorTree.js diff --git a/NowCoder/Leetcode/printMatrixbyClockwise.js b/NowCoder/Leetcode/19.printMatrixbyClockwise.js similarity index 100% rename from NowCoder/Leetcode/printMatrixbyClockwise.js rename to NowCoder/Leetcode/19.printMatrixbyClockwise.js diff --git a/NowCoder/Leetcode/replaceSpaceinString.js b/NowCoder/Leetcode/2.replaceSpaceinString.js similarity index 100% rename from NowCoder/Leetcode/replaceSpaceinString.js rename to NowCoder/Leetcode/2.replaceSpaceinString.js diff --git a/NowCoder/Leetcode/createMinStackStructure.js b/NowCoder/Leetcode/20.createMinStackStructure.js similarity index 100% rename from NowCoder/Leetcode/createMinStackStructure.js rename to NowCoder/Leetcode/20.createMinStackStructure.js diff --git a/NowCoder/Leetcode/isPopOrder.js b/NowCoder/Leetcode/21.isPopOrder.js similarity index 100% rename from NowCoder/Leetcode/isPopOrder.js rename to NowCoder/Leetcode/21.isPopOrder.js diff --git a/NowCoder/Leetcode/printTreeFromTopToBottom.js b/NowCoder/Leetcode/22.printTreeFromTopToBottom.js similarity index 100% rename from NowCoder/Leetcode/printTreeFromTopToBottom.js rename to NowCoder/Leetcode/22.printTreeFromTopToBottom.js diff --git a/NowCoder/Leetcode/verifySquenceOfBST.js b/NowCoder/Leetcode/23.verifySquenceOfBST.js similarity index 100% rename from NowCoder/Leetcode/verifySquenceOfBST.js rename to NowCoder/Leetcode/23.verifySquenceOfBST.js diff --git a/NowCoder/Leetcode/findPathofBinary.js b/NowCoder/Leetcode/24.findPathofBinary.js similarity index 100% rename from NowCoder/Leetcode/findPathofBinary.js rename to NowCoder/Leetcode/24.findPathofBinary.js diff --git a/NowCoder/Leetcode/cloneComplexLinkList.js b/NowCoder/Leetcode/25.cloneComplexLinkList.js similarity index 100% rename from NowCoder/Leetcode/cloneComplexLinkList.js rename to NowCoder/Leetcode/25.cloneComplexLinkList.js diff --git a/NowCoder/Leetcode/convertBinaryTreetoDoubleLinkList.js b/NowCoder/Leetcode/26.convertBinaryTreetoDoubleLinkList.js similarity index 100% rename from NowCoder/Leetcode/convertBinaryTreetoDoubleLinkList.js rename to NowCoder/Leetcode/26.convertBinaryTreetoDoubleLinkList.js diff --git a/NowCoder/Leetcode/permutationString.js b/NowCoder/Leetcode/27.permutationString.js similarity index 100% rename from NowCoder/Leetcode/permutationString.js rename to NowCoder/Leetcode/27.permutationString.js diff --git a/NowCoder/Leetcode/moreThanHalfNum_Solution.js b/NowCoder/Leetcode/28.moreThanHalfNum_Solution.js similarity index 100% rename from NowCoder/Leetcode/moreThanHalfNum_Solution.js rename to NowCoder/Leetcode/28.moreThanHalfNum_Solution.js diff --git a/NowCoder/Leetcode/getLeastNumbers_Solution.js b/NowCoder/Leetcode/29.getLeastNumbers_Solution.js similarity index 100% rename from NowCoder/Leetcode/getLeastNumbers_Solution.js rename to NowCoder/Leetcode/29.getLeastNumbers_Solution.js diff --git a/NowCoder/Leetcode/shiftListNode.js b/NowCoder/Leetcode/3.shiftListNode.js similarity index 100% rename from NowCoder/Leetcode/shiftListNode.js rename to NowCoder/Leetcode/3.shiftListNode.js diff --git a/NowCoder/Leetcode/findGreatestSumOfSubArray.js b/NowCoder/Leetcode/30.findGreatestSumOfSubArray.js similarity index 100% rename from NowCoder/Leetcode/findGreatestSumOfSubArray.js rename to NowCoder/Leetcode/30.findGreatestSumOfSubArray.js diff --git a/NowCoder/Leetcode/numberOf1Between1AndN_Solution.js b/NowCoder/Leetcode/31.numberOf1Between1AndN_Solution.js similarity index 100% rename from NowCoder/Leetcode/numberOf1Between1AndN_Solution.js rename to NowCoder/Leetcode/31.numberOf1Between1AndN_Solution.js diff --git a/NowCoder/Leetcode/PrintConnectMinNumberofArray.js b/NowCoder/Leetcode/32.PrintConnectMinNumberofArray.js similarity index 100% rename from NowCoder/Leetcode/PrintConnectMinNumberofArray.js rename to NowCoder/Leetcode/32.PrintConnectMinNumberofArray.js diff --git a/NowCoder/Leetcode/getUglyNumber_Solution.js b/NowCoder/Leetcode/33.getUglyNumber_Solution.js similarity index 100% rename from NowCoder/Leetcode/getUglyNumber_Solution.js rename to NowCoder/Leetcode/33.getUglyNumber_Solution.js diff --git a/NowCoder/Leetcode/firstNotRepeatingChar.js b/NowCoder/Leetcode/34.firstNotRepeatingChar.js similarity index 100% rename from NowCoder/Leetcode/firstNotRepeatingChar.js rename to NowCoder/Leetcode/34.firstNotRepeatingChar.js diff --git a/NowCoder/Leetcode/inversePairsNum.js b/NowCoder/Leetcode/35.inversePairsNum.js similarity index 100% rename from NowCoder/Leetcode/inversePairsNum.js rename to NowCoder/Leetcode/35.inversePairsNum.js diff --git a/NowCoder/Leetcode/findFirstCommonNodeofLinkNode.js b/NowCoder/Leetcode/36.findFirstCommonNodeofLinkNode.js similarity index 100% rename from NowCoder/Leetcode/findFirstCommonNodeofLinkNode.js rename to NowCoder/Leetcode/36.findFirstCommonNodeofLinkNode.js diff --git a/NowCoder/Leetcode/getNumberOfK.js b/NowCoder/Leetcode/37.getNumberOfK.js similarity index 100% rename from NowCoder/Leetcode/getNumberOfK.js rename to NowCoder/Leetcode/37.getNumberOfK.js diff --git a/NowCoder/Leetcode/treeDepth.js b/NowCoder/Leetcode/38.treeDepth.js similarity index 100% rename from NowCoder/Leetcode/treeDepth.js rename to NowCoder/Leetcode/38.treeDepth.js diff --git a/NowCoder/Leetcode/isBalancedTree.js b/NowCoder/Leetcode/39.isBalancedTree.js similarity index 100% rename from NowCoder/Leetcode/isBalancedTree.js rename to NowCoder/Leetcode/39.isBalancedTree.js diff --git a/NowCoder/Leetcode/reConstructBinaryTree.js b/NowCoder/Leetcode/4.reConstructBinaryTree.js similarity index 100% rename from NowCoder/Leetcode/reConstructBinaryTree.js rename to NowCoder/Leetcode/4.reConstructBinaryTree.js diff --git a/NowCoder/Leetcode/findNumsAppearOnce.js b/NowCoder/Leetcode/40.findNumsAppearOnce.js similarity index 100% rename from NowCoder/Leetcode/findNumsAppearOnce.js rename to NowCoder/Leetcode/40.findNumsAppearOnce.js diff --git a/NowCoder/Leetcode/findContinuousSequence.js b/NowCoder/Leetcode/41.findContinuousSequence.js similarity index 100% rename from NowCoder/Leetcode/findContinuousSequence.js rename to NowCoder/Leetcode/41.findContinuousSequence.js diff --git a/NowCoder/Leetcode/findNumbersWithSum.js b/NowCoder/Leetcode/42.findNumbersWithSum.js similarity index 100% rename from NowCoder/Leetcode/findNumbersWithSum.js rename to NowCoder/Leetcode/42.findNumbersWithSum.js diff --git a/NowCoder/Leetcode/loopStr.js b/NowCoder/Leetcode/43.loopLeftRotateStr.js similarity index 100% rename from NowCoder/Leetcode/loopStr.js rename to NowCoder/Leetcode/43.loopLeftRotateStr.js diff --git a/NowCoder/Leetcode/reverseWords.js b/NowCoder/Leetcode/44.reverseWords.js similarity index 100% rename from NowCoder/Leetcode/reverseWords.js rename to NowCoder/Leetcode/44.reverseWords.js diff --git a/NowCoder/Leetcode/isContinuous.js b/NowCoder/Leetcode/45.isContinuous.js similarity index 100% rename from NowCoder/Leetcode/isContinuous.js rename to NowCoder/Leetcode/45.isContinuous.js diff --git a/NowCoder/Leetcode/lastRemaining_Solution.js b/NowCoder/Leetcode/46.lastRemaining_Solution.js similarity index 100% rename from NowCoder/Leetcode/lastRemaining_Solution.js rename to NowCoder/Leetcode/46.lastRemaining_Solution.js diff --git a/NowCoder/Leetcode/sum_Solution.js b/NowCoder/Leetcode/47.sum_Solution.js similarity index 100% rename from NowCoder/Leetcode/sum_Solution.js rename to NowCoder/Leetcode/47.sum_Solution.js diff --git a/NowCoder/Leetcode/addTwoNum.js b/NowCoder/Leetcode/48.addTwoNum.js similarity index 100% rename from NowCoder/Leetcode/addTwoNum.js rename to NowCoder/Leetcode/48.addTwoNum.js diff --git a/NowCoder/Leetcode/strToInt.js b/NowCoder/Leetcode/49.strToInt.js similarity index 100% rename from NowCoder/Leetcode/strToInt.js rename to NowCoder/Leetcode/49.strToInt.js diff --git a/NowCoder/Leetcode/useTwoStackCreatQueue.js b/NowCoder/Leetcode/5.useTwoStackCreatQueue.js similarity index 100% rename from NowCoder/Leetcode/useTwoStackCreatQueue.js rename to NowCoder/Leetcode/5.useTwoStackCreatQueue.js diff --git a/NowCoder/Leetcode/duplicate.js b/NowCoder/Leetcode/50.duplicate.js similarity index 100% rename from NowCoder/Leetcode/duplicate.js rename to NowCoder/Leetcode/50.duplicate.js diff --git a/NowCoder/Leetcode/multiply.js b/NowCoder/Leetcode/51.multiply.js similarity index 100% rename from NowCoder/Leetcode/multiply.js rename to NowCoder/Leetcode/51.multiply.js diff --git a/NowCoder/Leetcode/matchParren.js b/NowCoder/Leetcode/52.matchParren.js similarity index 100% rename from NowCoder/Leetcode/matchParren.js rename to NowCoder/Leetcode/52.matchParren.js diff --git a/NowCoder/Leetcode/isNumeric.js b/NowCoder/Leetcode/53.isNumeric.js similarity index 100% rename from NowCoder/Leetcode/isNumeric.js rename to NowCoder/Leetcode/53.isNumeric.js diff --git a/NowCoder/Leetcode/firstAppearingOnce.js b/NowCoder/Leetcode/54.firstAppearingOnce.js similarity index 100% rename from NowCoder/Leetcode/firstAppearingOnce.js rename to NowCoder/Leetcode/54.firstAppearingOnce.js diff --git a/NowCoder/Leetcode/entryNodeOfLoop.js b/NowCoder/Leetcode/55.entryNodeOfLoop.js similarity index 100% rename from NowCoder/Leetcode/entryNodeOfLoop.js rename to NowCoder/Leetcode/55.entryNodeOfLoop.js diff --git a/NowCoder/Leetcode/deleteDuplicationLinkNode.js b/NowCoder/Leetcode/56.deleteDuplicationLinkNode.js similarity index 100% rename from NowCoder/Leetcode/deleteDuplicationLinkNode.js rename to NowCoder/Leetcode/56.deleteDuplicationLinkNode.js diff --git a/NowCoder/Leetcode/getNextNode.js b/NowCoder/Leetcode/57.getNextNode.js similarity index 100% rename from NowCoder/Leetcode/getNextNode.js rename to NowCoder/Leetcode/57.getNextNode.js diff --git a/NowCoder/Leetcode/isSymmetrical.js b/NowCoder/Leetcode/58.isSymmetrical.js similarity index 100% rename from NowCoder/Leetcode/isSymmetrical.js rename to NowCoder/Leetcode/58.isSymmetrical.js diff --git a/NowCoder/Leetcode/printTreewithZhizi.js b/NowCoder/Leetcode/59.printTreewithZhizi.js similarity index 100% rename from NowCoder/Leetcode/printTreewithZhizi.js rename to NowCoder/Leetcode/59.printTreewithZhizi.js diff --git a/NowCoder/Leetcode/minNumberInRotateArray.js b/NowCoder/Leetcode/6.minNumberInRotateArray.js similarity index 100% rename from NowCoder/Leetcode/minNumberInRotateArray.js rename to NowCoder/Leetcode/6.minNumberInRotateArray.js diff --git a/NowCoder/Leetcode/printTreebyLayer.js b/NowCoder/Leetcode/60.printTreebyLayer.js similarity index 100% rename from NowCoder/Leetcode/printTreebyLayer.js rename to NowCoder/Leetcode/60.printTreebyLayer.js diff --git a/NowCoder/Leetcode/serializeAndSerialize.js b/NowCoder/Leetcode/61.serializeAndSerialize.js similarity index 100% rename from NowCoder/Leetcode/serializeAndSerialize.js rename to NowCoder/Leetcode/61.serializeAndSerialize.js diff --git a/NowCoder/Leetcode/kthSmallNode.js b/NowCoder/Leetcode/62.kthSmallNode.js similarity index 100% rename from NowCoder/Leetcode/kthSmallNode.js rename to NowCoder/Leetcode/62.kthSmallNode.js diff --git a/NowCoder/Leetcode/getMidim.js b/NowCoder/Leetcode/63.getMidim.js similarity index 100% rename from NowCoder/Leetcode/getMidim.js rename to NowCoder/Leetcode/63.getMidim.js diff --git a/NowCoder/Leetcode/maxInWindows.js b/NowCoder/Leetcode/64.maxInWindows.js similarity index 100% rename from NowCoder/Leetcode/maxInWindows.js rename to NowCoder/Leetcode/64.maxInWindows.js diff --git a/NowCoder/Leetcode/hasPath.js b/NowCoder/Leetcode/65.hasPath.js similarity index 100% rename from NowCoder/Leetcode/hasPath.js rename to NowCoder/Leetcode/65.hasPath.js diff --git a/NowCoder/Leetcode/movingCountRobot.js b/NowCoder/Leetcode/66.movingCountRobot.js similarity index 100% rename from NowCoder/Leetcode/movingCountRobot.js rename to NowCoder/Leetcode/66.movingCountRobot.js diff --git a/NowCoder/Leetcode/outputFibonacci.js b/NowCoder/Leetcode/7.outputFibonacci.js similarity index 100% rename from NowCoder/Leetcode/outputFibonacci.js rename to NowCoder/Leetcode/7.outputFibonacci.js diff --git a/NowCoder/Leetcode/jumpStep.js b/NowCoder/Leetcode/8.jumpStep.js similarity index 100% rename from NowCoder/Leetcode/jumpStep.js rename to NowCoder/Leetcode/8.jumpStep.js diff --git a/NowCoder/Leetcode/jumpStepII.js b/NowCoder/Leetcode/9.jumpStepII.js similarity index 93% rename from NowCoder/Leetcode/jumpStepII.js rename to NowCoder/Leetcode/9.jumpStepII.js index bed1e2d..2981908 100644 --- a/NowCoder/Leetcode/jumpStepII.js +++ b/NowCoder/Leetcode/9.jumpStepII.js @@ -16,7 +16,7 @@ function jumpFloorII(number) { } else if (number == 1) { return 1; } else { - return jumpFloorII(number - 1); + return 2*jumpFloorII(number - 1); } } From f444d0954e39806367486458241c804b6d2f297e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 25 May 2019 16:25:47 +0800 Subject: [PATCH 183/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A015=E5=92=8C20?= =?UTF-8?q?=E9=A2=98=E7=9A=84=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/15.3sum.js | 72 +++++++++++++++++++++++++++++++ Leetcode/20.validSymbelList.js | 78 ++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 Leetcode/15.3sum.js create mode 100644 Leetcode/20.validSymbelList.js diff --git a/Leetcode/15.3sum.js b/Leetcode/15.3sum.js new file mode 100644 index 0000000..f784322 --- /dev/null +++ b/Leetcode/15.3sum.js @@ -0,0 +1,72 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-25 15:53:51 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-25 16:20:12 + */ + + +/***** + * + * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0 ? + * Find all unique triplets in the array which gives the sum of zero. + * + * + * Given array nums = [-1, 0, 1, 2, -1, -4], + * + * A solution set is: + * [ + * [-1, 0, 1], + * [-1, -1, 2] + * ] + * + * + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +let threeSum = function (nums) { + let backArrs = []; + if (nums.length < 3) { + return backArrs; + } + + let target = 0; + nums = nums.sort((a, b) => a - b); // 对数组进行排序,由小到大 + for (let i = 0; i < nums.length -2; i++) { + if (nums[i] > target) { + break; + } + if (i>0 && nums[i] === nums[i-1]) { + continue; + } + let j = i+1; // 第二个数从大于 i 开始 + let k = nums.length - 1; // 第三个数从最大开始 + + while(j < k){ + let tempSum = nums[i] + nums[j] + nums[k]; // 暂存当前状态 + if (tempSum === target) { + backArrs.push([nums[i], nums[j], nums[k]]); + while (nums[j] == nums[j+1]){ + j++; + } + while(nums[k] === nums[k-1]){ + k--; + } + j++; + k--; + } else if (tempSum < target) { + j++; + } else if (tempSum > target) { + k--; + } + } + } + + return backArrs; +}; + +let nums = [-1, 0, 1, 2, -1, -4]; +console.log(threeSum(nums)); \ No newline at end of file diff --git a/Leetcode/20.validSymbelList.js b/Leetcode/20.validSymbelList.js new file mode 100644 index 0000000..91695f3 --- /dev/null +++ b/Leetcode/20.validSymbelList.js @@ -0,0 +1,78 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-25 15:35:02 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-25 15:51:37 + */ + + +/******* + * + * + * 检查字符串是否是成对闭合的 + * + * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + * + * + * + * ()[]{} + * true + * + * ([)] + * false + * + * {[]} + * true + * + */ + +/** + * @param {string} s + * @return {boolean} + * + * by SkylineBin + */ +var isValid = function (s) { + if (s.length === 0) { + return true; + } + let openArr = ['(','{','[']; + let closeArr = [')','}',']']; + let tempStack = []; + for (let i = 0; i < s.length; i++) { + if (openArr.indexOf(s[i]) !== -1 || closeArr.indexOf(s[i]) !== -1) { + if (openArr.indexOf(s[i]) !== -1) { + tempStack.push(s[i]); + } else if (closeArr.indexOf(s[i]) !== -1) { + if (tempStack.length === 0 || closeArr.indexOf(s[i]) !== openArr.indexOf(tempStack.pop())) { + return false; + } + } + }else { + return false; + } + } + if (tempStack.length !== 0) { + return false; + } + return true; +}; + +let str = '([)]'; +console.log(isValid(str)); + + +// 优秀解答参考 +let isValid2 = function (s) { + let map = { + '[': ']', + '{': '}', + '(': ')' + } + let stack = []; + for (let letter of s) { + if (map[letter] != undefined) stack.push(letter); + else if (map[stack.pop()] != letter) return false; + } + return stack.length === 0 ? true : false; +}; \ No newline at end of file From 42a3334cc4ae421d283d078b207b64c31eaabb6c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 26 May 2019 11:30:17 +0800 Subject: [PATCH 184/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20leetcode=20?= =?UTF-8?q?=E7=9A=84=E7=AC=AC21=E9=A2=98=E9=A2=98=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/21.MergeTwoSortedLists.js | 51 ++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Leetcode/21.MergeTwoSortedLists.js diff --git a/Leetcode/21.MergeTwoSortedLists.js b/Leetcode/21.MergeTwoSortedLists.js new file mode 100644 index 0000000..66cfe15 --- /dev/null +++ b/Leetcode/21.MergeTwoSortedLists.js @@ -0,0 +1,51 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-26 11:20:02 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-26 11:28:37 + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + if(l1 === null || l2 === null){ + return (l1 === null)? l2:l1; + } + let listHead; + if(l1.val < l2.val){ + listHead = new ListNode(l1.val); + l1 = l1.next; + } else { + listHead = new ListNode(l2.val); + l2 = l2.next; + } + let currentNode = listHead; + while(l1 && l2){ + if(l1.val < l2.val){ + currentNode.next = new ListNode(l1.val); + l1 = l1.next; + } else { + currentNode.next = new ListNode(l2.val); + l2 = l2.next; + } + currentNode = currentNode.next; + } + + if(l1!==null){ + currentNode.next = l1; + } + if(l2!==null){ + currentNode.next = l2; + } + return listHead; +}; \ No newline at end of file From 508cedf7841bbf89fbd10ded4be5702cb328c059 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 31 May 2019 10:23:22 +0800 Subject: [PATCH 185/274] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9B=B8=E5=8A=A0=E7=9A=84=E9=A2=98=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/{3.addTwonums.js => 2.addTwonums.js} | 70 +++++++++++++++---- 1 file changed, 55 insertions(+), 15 deletions(-) rename Leetcode/{3.addTwonums.js => 2.addTwonums.js} (52%) diff --git a/Leetcode/3.addTwonums.js b/Leetcode/2.addTwonums.js similarity index 52% rename from Leetcode/3.addTwonums.js rename to Leetcode/2.addTwonums.js index cb985d8..ae9b861 100644 --- a/Leetcode/3.addTwonums.js +++ b/Leetcode/2.addTwonums.js @@ -1,9 +1,18 @@ -/*** -* -* -* -* -***/ +/****** + * + * You are given two non-empty linked lists representing two non-negative integers. + * The digits are stored in reverse order and each of their nodes contain a single digit. + * Add the two numbers and return it as a linked list. + * + * + * + * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) + * Output: 7 -> 0 -> 8 + * Explanation: 342 + 465 = 807. + * + * + * + */ // ! 本质涉及: /** @@ -26,7 +35,7 @@ function ListNode(val) { this.next = null; } -// 思路错误,不是先算完求和再转换成链表 +// ! 思路错误,不是先算完求和再转换成链表 var addTwoNumbersold = function (l1, l2) { var num1 =0; var num2 =0; @@ -70,21 +79,52 @@ var addTwoNumbersold = function (l1, l2) { // Test Algorithm // var testNum = 5; -console.log(); +// console.log(); // var nodeone = arrayToLinkNode([2,4,3]); // var nodetwo = arrayToLinkNode([5,6,4]); var nodeone = arrayToLinkNode([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); var nodetwo = arrayToLinkNode([5,6,4]); -console.log(addTwoNumbersold(nodeone, nodetwo)); - -var addTwoNumbers = function (l1, l2) { +let addTwoNumbers = function (l1, l2) { // 定义进位 - var carry = 0; - var p = l1,q=l2; - while (p.next != null || q.next != null) { + let carry = 0; + let p = l1,q=l2; + let numStack = []; + let backdata = 0; + while (p != null || q != null) { + let currentNum = 0; + if (p != null && q != null) { + currentNum = p.val + q.val; + } else if (p != null || q != null) { + currentNum = p === null ? q.val : p.val; + } + currentNum = carry === 1 ? currentNum + 1 : currentNum; + if (currentNum > 9) { + currentNum = currentNum % 10; + carry = 1; + } else { + carry = 0; + } + numStack.push(currentNum); + p = p?p.next:p; + q = q?q.next:q; + } + if (carry) { + numStack.push(1); + carry = 0; + } + let backLink = new ListNode(numStack.shift()); + let tempNode = backLink; + while (numStack.length) { + tempNode.next = new ListNode(numStack.shift()); + tempNode = tempNode.next; } + return backLink; +} + +var node1 = arrayToLinkNode([5]); +var node2 = arrayToLinkNode([5, 6, 4]); -} \ No newline at end of file +console.log(addTwoNumbers(node1, node2)); \ No newline at end of file From aac63ef30b7b1f6f363d53a6c0e4b0d4042a4eec Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 3 Jun 2019 22:01:59 +0800 Subject: [PATCH 186/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E5=AD=90=E4=B8=B2=E7=9A=84=E6=9A=B4=E5=8A=9B?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJavaScript/sortTesting.js | 20 +++++++ Leetcode/2.addTwonums.js | 1 - .../2018Enterprise/maxCommonSubString-vivo.js | 58 +++++++++++++++++++ 3 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js create mode 100644 NowCoder/2018Enterprise/maxCommonSubString-vivo.js diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js new file mode 100644 index 0000000..4a84eec --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js @@ -0,0 +1,20 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-03 20:33:20 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-03 20:34:31 + */ + + +const BubbleSort = require('./BubbleSort'); +const SelectionSort = require('./SelectionSort'); +const InsertionSort = require('./InsertionSort'); +const MergeSort = require('./MergeSort'); +const DutchFlagArray = require('./DultFlagArray'); +const QuickSort = require('./QuickSort'); +const HeapSort = require('./HeapSort'); + + +let arrOne = [38,65,97,76,13,27,10]; + +BubbleSort(arrOne); \ No newline at end of file diff --git a/Leetcode/2.addTwonums.js b/Leetcode/2.addTwonums.js index ae9b861..0f7abeb 100644 --- a/Leetcode/2.addTwonums.js +++ b/Leetcode/2.addTwonums.js @@ -91,7 +91,6 @@ let addTwoNumbers = function (l1, l2) { let carry = 0; let p = l1,q=l2; let numStack = []; - let backdata = 0; while (p != null || q != null) { let currentNum = 0; if (p != null && q != null) { diff --git a/NowCoder/2018Enterprise/maxCommonSubString-vivo.js b/NowCoder/2018Enterprise/maxCommonSubString-vivo.js new file mode 100644 index 0000000..3f56ee7 --- /dev/null +++ b/NowCoder/2018Enterprise/maxCommonSubString-vivo.js @@ -0,0 +1,58 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-03 21:26:42 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-03 21:59:37 + */ + +/***** + * + * 编程找出两个字符串中最大公共子字符串, + * + * 如 "abccade", "dgcadde"的最大子串为 "cad" + * + * + */ + +// 枚举方法实现搜索 +function maxCommonSubString(str1, str2){ + + let backstr = ""; + if (str1 === '' || str2 === '') { + return backstr; + } + let startPosition = 0; + let maxLength =0; + + for (let i = 0; i < str1.length; i++) { + for (let j = 0; j < str2.length; j++) { + if (str1[i] === str2[j]) { + let k = 1; + while (str1[i + k] === str2[j + k] && str1[i + k] != '' && str2[j + k] != '') { + k++; + } + if (k > maxLength) { + maxLength = k; + startPosition = i; + } + } + } + } + if (maxLength > 0) { + console.log('????'); + backstr = str1.slice(startPosition, startPosition+maxLength); + + } + return backstr; + +} + +let str1 = "abccade"; +let str2 = "dgcadde"; + +console.log(maxCommonSubString(str1, str2)); + + + // for (let index = startPosition; index <= maxLength; index++) { + // backstr += str1[index]; + // } \ No newline at end of file From 09fb7d4da8895b346551995857a3330f29c66051 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 4 Jun 2019 14:16:50 +0800 Subject: [PATCH 187/274] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BA=86=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E9=81=8D=E5=8E=86=E8=A7=A3=E5=86=B3=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E5=AD=90=E4=B8=B2=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2018Enterprise/maxCommonSubString-vivo.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/NowCoder/2018Enterprise/maxCommonSubString-vivo.js b/NowCoder/2018Enterprise/maxCommonSubString-vivo.js index 3f56ee7..5a73664 100644 --- a/NowCoder/2018Enterprise/maxCommonSubString-vivo.js +++ b/NowCoder/2018Enterprise/maxCommonSubString-vivo.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-06-03 21:26:42 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-06-03 21:59:37 + * @Last Modified time: 2019-06-04 14:13:37 */ /***** @@ -28,7 +28,7 @@ function maxCommonSubString(str1, str2){ for (let j = 0; j < str2.length; j++) { if (str1[i] === str2[j]) { let k = 1; - while (str1[i + k] === str2[j + k] && str1[i + k] != '' && str2[j + k] != '') { + while (str1[i + k] === str2[j + k] && typeof str1[i + k] === 'string' && typeof str2[j + k] === 'string') { k++; } if (k > maxLength) { @@ -39,12 +39,9 @@ function maxCommonSubString(str1, str2){ } } if (maxLength > 0) { - console.log('????'); backstr = str1.slice(startPosition, startPosition+maxLength); - } return backstr; - } let str1 = "abccade"; From 7b2757d0fb79d60e4dd3eab73cfba6633dcb7409 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 4 Jun 2019 21:28:01 +0800 Subject: [PATCH 188/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=8F=90=E5=89=8D?= =?UTF-8?q?=E6=89=B9=E7=AC=94=E8=AF=95=E7=9A=84=E8=A7=A3=E9=A2=98=E6=80=9D?= =?UTF-8?q?=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2018Enterprise/maxCommonSubString-vivo.js | 10 ++-- NowCoder/2019/vivo1.js | 39 +++++++++++++ NowCoder/2019/vivo2.js | 1 + NowCoder/2019/vivo3.js | 56 +++++++++++++++++++ 4 files changed, 102 insertions(+), 4 deletions(-) create mode 100644 NowCoder/2019/vivo1.js create mode 100644 NowCoder/2019/vivo2.js create mode 100644 NowCoder/2019/vivo3.js diff --git a/NowCoder/2018Enterprise/maxCommonSubString-vivo.js b/NowCoder/2018Enterprise/maxCommonSubString-vivo.js index 5a73664..08c431e 100644 --- a/NowCoder/2018Enterprise/maxCommonSubString-vivo.js +++ b/NowCoder/2018Enterprise/maxCommonSubString-vivo.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-06-03 21:26:42 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-06-04 14:13:37 + * @Last Modified time: 2019-06-04 18:34:21 */ /***** @@ -50,6 +50,8 @@ let str2 = "dgcadde"; console.log(maxCommonSubString(str1, str2)); - // for (let index = startPosition; index <= maxLength; index++) { - // backstr += str1[index]; - // } \ No newline at end of file +// for (let index = startPosition; index <= maxLength; index++) { +// backstr += str1[index]; +// } + +// 使用动态规划解决 \ No newline at end of file diff --git a/NowCoder/2019/vivo1.js b/NowCoder/2019/vivo1.js new file mode 100644 index 0000000..f75830b --- /dev/null +++ b/NowCoder/2019/vivo1.js @@ -0,0 +1,39 @@ +/****** + * + * + * 从数组A中找数组B中不存在的数 + * + * + */ + + +function solution(arr1, arr2) { + var outputArr = []; //用于输出的结果数组 + if (arr1.length === 0 && arr2.length !== 0) { + outputArr = arr1; + } else if (arr1.length !== 0 && arr2.length === 0) { + outputArr = arr2; + } else if (arr1.length === 0 && arr2.length === 0) { + outputArr = []; + } else { + arr2.sort((a, b) => { + return a - b; + }) + for (let i = 0; i < arr1.length; i++) { + let state = false; + for (let j = 0; j < arr2.length; j++) { + if (arr2[j] === arr1[i]) { + state = true; + } + } + if (!state) { + outputArr.push(arr1[i]); + } + } + + } + + +} + + diff --git a/NowCoder/2019/vivo2.js b/NowCoder/2019/vivo2.js new file mode 100644 index 0000000..a9ee5bf --- /dev/null +++ b/NowCoder/2019/vivo2.js @@ -0,0 +1 @@ +// 链表指定位置逆序 \ No newline at end of file diff --git a/NowCoder/2019/vivo3.js b/NowCoder/2019/vivo3.js new file mode 100644 index 0000000..113a120 --- /dev/null +++ b/NowCoder/2019/vivo3.js @@ -0,0 +1,56 @@ +/**** + * + * 使用 动态规划的思想 实现 背包问题 + * 背包问题实质是 组合优化问题 + * + * + */ + + + + +//请把代码实现写在solution方程里面 +function solution(arr1, arr2, arr3) { + + var sum = arr1[0]; //总金额 + + var maxValue; //用于输出能买到的最大热度 + + //TODO write your code here + + maxValue = 0; + var i, w, a, b, kS = []; + + let maxLength = arr2.length; + + for (let i = 0; i <= arr2.length; i++) { + kS[i] = []; + } + + for (let j = 0; j <= maxLength; j++) { + for (let w = 0; w <= sum; w++) { + if (j == 0 || w == 0) { + kS[j][w] = 0; + } else if (arr2[j - 1] <= w) { + a = arr3[j - 1] + kS[j - 1][w - arr2[j - 1]]; + b = kS[j - 1][w]; + kS[j][w] = (a > b) ? a : b; + } else { + kS[j][w] = kS[j - 1][w]; + } + } + } + + maxValue = kS[maxLength][sum]; + + return maxValue; + +} + + +let arr1 = [1000]; +let arr2 = [200,600,100,180,300,450]; +let arr3 = [6,10,3,4,5,8]; + + +console.log(solution(arr1, arr2, arr3)); \ No newline at end of file From e31b1dc3cb07564f32ac84a2b3094f7727a8751e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 12 Jun 2019 21:12:42 +0800 Subject: [PATCH 189/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=94=9F=E6=88=90=20?= =?UTF-8?q?n=20=E7=BB=84=20=E6=8B=AC=E5=8F=B7=E7=BB=84=E6=88=90=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=9B=86=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LeetCode 22 --- Leetcode/22.GenerateParentheses.js | 37 ++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Leetcode/22.GenerateParentheses.js diff --git a/Leetcode/22.GenerateParentheses.js b/Leetcode/22.GenerateParentheses.js new file mode 100644 index 0000000..30ce241 --- /dev/null +++ b/Leetcode/22.GenerateParentheses.js @@ -0,0 +1,37 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-12 21:05:07 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-12 21:11:45 + */ + +/**** + * + * 生成 n 组 括号组成的字符串集合 + * + * + */ + +/** + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = function(n) { + let backArr = []; + function compose(left, right, str) { + if (!left && !right && str.length) { + backArr.push(str); + } + if(left) { + compose(left - 1, right, str+'('); + } + if(left < right) { + compose(left, right - 1, str+')'); + } + } + + compose(n,n,''); + return backArr; +}; + +console.log(generateParenthesis(0)); \ No newline at end of file From 917e9a9bfaa1bcd9656f82cb156c9a54dc3993c3 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 13 Jun 2019 22:34:48 +0800 Subject: [PATCH 190/274] Create crazyList-neteasy.js --- NowCoder/2018Enterprise/crazyList-neteasy.js | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 NowCoder/2018Enterprise/crazyList-neteasy.js diff --git a/NowCoder/2018Enterprise/crazyList-neteasy.js b/NowCoder/2018Enterprise/crazyList-neteasy.js new file mode 100644 index 0000000..94cc3b9 --- /dev/null +++ b/NowCoder/2018Enterprise/crazyList-neteasy.js @@ -0,0 +1,42 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-13 22:01:11 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-13 22:22:19 + */ + + +function crazyList(n, listN){ + let maxNum = 0; + if (n !== listN.length){ + return 0; + } + let sortArr = listN.sort((a,b) => { + return a - b; + }); + let i =0; + let j = n - 1; + let tempArr = []; + while(j>i){ + tempArr.push(sortArr[i++]); + tempArr.push(sortArr[j--]); + } + tempArr.pop(); + + this.dsp = function(){ + + } + + this.maxList = function(arr){ + let num = 0; + for(let k=1;k Date: Mon, 17 Jun 2019 20:15:32 +0800 Subject: [PATCH 191/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=85=BE=E8=AE=AF201?= =?UTF-8?q?8=E9=9F=B3=E4=B9=90=E5=88=97=E8=A1=A8=E7=BB=84=E6=88=90?= =?UTF-8?q?=E6=96=B9=E6=A1=88=E7=A7=8D=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2018Enterprise/musicList-tencent.js | 39 ++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 NowCoder/2018Enterprise/musicList-tencent.js diff --git a/NowCoder/2018Enterprise/musicList-tencent.js b/NowCoder/2018Enterprise/musicList-tencent.js new file mode 100644 index 0000000..490bd48 --- /dev/null +++ b/NowCoder/2018Enterprise/musicList-tencent.js @@ -0,0 +1,39 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-17 19:46:16 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-17 20:03:30 + */ + + +function findMaxKindsofMusicList(allLength, lengthA, numX, lengthB, numY){ + let countNum = 0; + let c = []; + let mod = 1000000007; + for (let i = 0; i <= 100; i++) { + c[i] = []; + c[i][0] = 1; + } + for (let j = 1; j <=100; j++) { + for (let k = 1; k <=100; k++) { + c[0][k] = 0; + c[j][k] = (c[j-1][k-1] + c[j-1][k]) % mod; + } + } + + for (let i = 0; i <= numX; i++) { + if (i*lengthA <= allLength && (allLength - lengthA*i)%lengthB === 0 && (allLength - lengthA*i)/lengthB <= numY) { + countNum = (countNum + (c[numX][i] * c[numY][(allLength - lengthA*i)/lengthB]) % mod) % mod; + } + } + + return countNum; +} + +let allLength = 5; +let lengthA = 2; +let numX = 3; +let lengthB = 3; +let numY = 3; + +console.log(findMaxKindsofMusicList(allLength, lengthA, numX, lengthB, numY)); \ No newline at end of file From 82a3d6f592e8875a794b347622e6b4cc731523e6 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 17 Jun 2019 21:22:58 +0800 Subject: [PATCH 192/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=85=BE=E8=AE=AF?= =?UTF-8?q?=E7=94=BB=E6=9D=BF=E6=9C=80=E5=B0=8F=E6=AC=A1=E6=95=B0=E5=AE=9E?= =?UTF-8?q?=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用DFS解决此问题的方法 --- NowCoder/2018Enterprise/paintNum-tencent.js | 73 +++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 NowCoder/2018Enterprise/paintNum-tencent.js diff --git a/NowCoder/2018Enterprise/paintNum-tencent.js b/NowCoder/2018Enterprise/paintNum-tencent.js new file mode 100644 index 0000000..32a290a --- /dev/null +++ b/NowCoder/2018Enterprise/paintNum-tencent.js @@ -0,0 +1,73 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-17 20:24:14 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-17 21:21:38 + */ + + +function countPaintNum(numN, numM, str){ + let count = 0; + let strC = []; + for (let index = 0; index < numN; index++) { + strC[index] = []; + let tempData = str[index]; + for (let j = 0; j < numM; j++) { + strC[index][j] = tempData[j]; + } + } + // console.log(strC); + + this.dfs_B = function (x, y, strC){ + x = parseInt(x); + y = parseInt(y); + if(x >= 0 && x < numN && y >= 0 && y < numM && (strC[x][y] === 'B' || strC[x][y] === 'G')){ + if (strC[x][y] === 'G') { + strC[x][y] = 'Y'; + } else { + strC[x][y] = 'X'; + } + this.dfs_B(x + 1, y - 1, strC); + this.dfs_B(x - 1, y + 1, strC); + } + return; + } + this.dfs_Y = function (x, y, strC){ + x = parseInt(x); + y = parseInt(y); + if(x >= 0 && x < numN && y >= 0 && y < numM && (strC[x][y] === 'Y' || strC[x][y] === 'G')){ + if (strC[x][y] === 'G') { + strC[x][y] = 'B'; + } else { + strC[x][y] = 'X'; + } + this.dfs_Y(x - 1, y - 1, strC); + this.dfs_Y(x + 1, y + 1, strC); + } + return; + } + + for (let i = 0; i < numN; i++) { + for (let j = 0; j < numM; j++) { + if (strC[i][j] === 'Y') { + this.dfs_Y(i,j, strC); + count++; + } else if(strC[i][j] === 'B'){ + this.dfs_B(i, j, strC); + count++; + }else if (strC[i][j] === 'G'){ + this.dfs_Y(i, j, strC); + // strC[i][j] = 'B'; + this.dfs_B(i, j, strC); + count += 2; + } + } + } + + return count; +} + +let numM = 4; +let numN = 4; +let str = ['YXXB','XYGX','XBYY','BXXY']; +console.log(countPaintNum(numN, numM, str)); \ No newline at end of file From 7938943cbfd64e893c0192514ebb056adb96fda4 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 19 Jun 2019 20:48:30 +0800 Subject: [PATCH 193/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=89=E9=81=93?= =?UTF-8?q?=E7=89=9B=E5=AE=A2=E7=BD=91=E6=A8=A1=E6=8B=9F=E5=B0=B8=E4=BD=93?= =?UTF-8?q?=E7=9A=84=E8=A7=A3=E7=AD=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CodingInterview/MinimumReturnSubstring.js | 27 +++++++++++++ .../CodingInterview/findMaxEvenStrLength.js | 34 ++++++++++++++++ NowCoder/CodingInterview/findMaxLengthDNA.js | 39 +++++++++++++++++++ 3 files changed, 100 insertions(+) create mode 100644 NowCoder/CodingInterview/MinimumReturnSubstring.js create mode 100644 NowCoder/CodingInterview/findMaxEvenStrLength.js create mode 100644 NowCoder/CodingInterview/findMaxLengthDNA.js diff --git a/NowCoder/CodingInterview/MinimumReturnSubstring.js b/NowCoder/CodingInterview/MinimumReturnSubstring.js new file mode 100644 index 0000000..f508807 --- /dev/null +++ b/NowCoder/CodingInterview/MinimumReturnSubstring.js @@ -0,0 +1,27 @@ +/***** + * + * 用字符串拼最少的回文数 + * + * 2019.06.19 + * + */ + + +function findminNumofStr(str){ + let minNum = 0; + let arr = str.split(''); + // 转换成数组后,进行归并迭代 + minNum = arr.reduce((tempSet,ele)=> { + return tempSet.delete(ele)? tempSet:tempSet.add(ele); + },new Set()).size; + if(minNum === 0){ + minNum = 1; + } + return minNum; +} + + + +var initPre = readline().split(" "); +var linstr = initPre[0]; +print(findminNumofStr(linstr)) \ No newline at end of file diff --git a/NowCoder/CodingInterview/findMaxEvenStrLength.js b/NowCoder/CodingInterview/findMaxEvenStrLength.js new file mode 100644 index 0000000..8376359 --- /dev/null +++ b/NowCoder/CodingInterview/findMaxEvenStrLength.js @@ -0,0 +1,34 @@ +/***** + * + * 计算删除多少后还是偶串的最大长度 + * + * + */ + + +function findMaxLengthEvenStr(str){ + let backEvenLen = 0; + this.checkIfEven = function(tempStr){ + if(tempStr.length % 2 !== 0){ + return false; + } + if (tempStr.substring(0,tempStr.length/2) === tempStr.substring(tempStr.length/2,tempStr.length)){ + return true; + } + return false; + } + for(let i=1;i backLen){ + backLen = num; + } + if (tempStr.length > 0 && state){ + this.dfs(tempStr,num); + } + return; + } + for(let i=0;i Date: Thu, 20 Jun 2019 21:23:31 +0800 Subject: [PATCH 194/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=B0=8F=E6=98=93?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E7=94=9F=E6=B4=BB=E7=9A=84=E5=A4=A9=E6=95=B0?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2018Enterprise/maxDay-neteasy.js | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 NowCoder/2018Enterprise/maxDay-neteasy.js diff --git a/NowCoder/2018Enterprise/maxDay-neteasy.js b/NowCoder/2018Enterprise/maxDay-neteasy.js new file mode 100644 index 0000000..3f08ce1 --- /dev/null +++ b/NowCoder/2018Enterprise/maxDay-neteasy.js @@ -0,0 +1,49 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-20 21:15:56 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-20 21:23:17 + */ + +/**** + * + * 小易独立生活的天数 + * + * + */ + + +function getMaxDays(x, f, d, p){ + let maxDate = 0; + x = parseInt(x); + f = parseInt(f); + d = parseInt(d); + p = parseInt(p); + if (parseInt(f) >= parseInt(d/x)){ + maxDate = parseInt(d/x); + } else { + maxDate = parseInt(f); + maxDate += parseInt((d - f*x)/(x + p)); + } + return maxDate; +} + + + + +var initPre = readline().split(" "); +var x = initPre[0]; +var f = initPre[1]; +var d = initPre[2]; +var p = initPre[3]; + +print(getMaxDays(x, f, d, p)) + +// let initPre = [3,5,100,10] + +// let x = initPre[0]; +// let f = initPre[1]; +// let d = initPre[2]; +// let p = initPre[3]; + +// console.log(getMaxDays(x, f, d, p)); \ No newline at end of file From 5177d0c7a4b118ff3865369a8db29cf3c1cdf452 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 20 Jun 2019 21:42:57 +0800 Subject: [PATCH 195/274] =?UTF-8?q?=E6=9F=A5=E6=89=BE=E6=9C=80=E9=95=BF01?= =?UTF-8?q?=E4=BA=A4=E5=8F=89=E5=AD=90=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2018Enterprise/maxLengthSubString.js | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 NowCoder/2018Enterprise/maxLengthSubString.js diff --git a/NowCoder/2018Enterprise/maxLengthSubString.js b/NowCoder/2018Enterprise/maxLengthSubString.js new file mode 100644 index 0000000..f24ce72 --- /dev/null +++ b/NowCoder/2018Enterprise/maxLengthSubString.js @@ -0,0 +1,43 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-20 21:27:03 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-20 21:42:16 + */ + + +function findMaxLengthSubString(str){ + let maxNum = 1; + + this.dfs = function(tempStr,num){ + if(tempStr[1] && tempStr[0] !== tempStr[1]){ + num++; + } else if(!tempStr[1] || tempStr[0] === tempStr[1]){ + return; + } + if(num > maxNum){ + maxNum = num; + } + tempStr = tempStr.substring(1, tempStr.length); + if(tempStr.length > 1){ + this.dfs(tempStr, num) + } + return; + } + for(let i=0;i< str.length;i++){ + let tempStr = str.substring(i,str.length); + this.dfs(tempStr,1); + } + return maxNum; +} + + + +// let initdata = readline().split(" "); +// let str = initdata[0]; + +// print(findMaxLengthSubString(str)); + +// let str = "111101111"; +let str = "000011110000"; +console.log(findMaxLengthSubString(str)); \ No newline at end of file From 1e4e05dc656a1791f3b505ec7e593a3c9240a32f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 22 Jun 2019 14:35:59 +0800 Subject: [PATCH 196/274] =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=9B=9E=E6=96=87?= =?UTF-8?q?=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/5.LongestPalindromicSubstring.js | 69 +++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Leetcode/5.LongestPalindromicSubstring.js diff --git a/Leetcode/5.LongestPalindromicSubstring.js b/Leetcode/5.LongestPalindromicSubstring.js new file mode 100644 index 0000000..10d806d --- /dev/null +++ b/Leetcode/5.LongestPalindromicSubstring.js @@ -0,0 +1,69 @@ +/**** + * + * get Longest Palindromic Substring of one string + * + * + * + */ + +// dfs solution +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function(s) { + let maxLen = 0; + let maxPaStr = ''; + if(s.length === 1){ + maxLen=1; + maxPaStr=s; + } + this.dfs = function(tempStr,i,j){ + let temp = tempStr.substring(i,j); + if(temp === temp.split('').reverse().join('')){ + if(j-i+1 > maxLen){ + maxLen = j-i+1; + maxPaStr = temp; + } + } + + if(j<= tempStr.length -1){ + this.dfs(tempStr,i,j+1); + } + return; + } + for(let i=0;i< s.length-1;i++){ + this.dfs(s,i,i+1); + } + return maxPaStr; +}; + +let testString= "jglknendplocymmvwtoxvebkekzfdhykknufqdkntnqvgfbahsljkobhbxkvyictzkqjqydczuxjkgecdyhixdttxfqmgksrkyvopwprsgoszftuhawflzjyuyrujrxluhzjvbflxgcovilthvuihzttzithnsqbdxtafxrfrblulsakrahulwthhbjcslceewxfxtavljpimaqqlcbrdgtgjryjytgxljxtravwdlnrrauxplempnbfeusgtqzjtzshwieutxdytlrrqvyemlyzolhbkzhyfyttevqnfvmpqjngcnazmaagwihxrhmcibyfkccyrqwnzlzqeuenhwlzhbxqxerfifzncimwqsfatudjihtumrtjtggzleovihifxufvwqeimbxvzlxwcsknksogsbwwdlwulnetdysvsfkonggeedtshxqkgbhoscjgpiel"; + +// 对于长字符串,以上方法超时 + +var longestPalindrome2 = function(s) { + let maxLen = 0; + let maxPaStr = ''; + if(s.length === 1){ + maxLen=1; + maxPaStr=s; + } + let reverseS = s.split('').reverse().join(''); + let lens = s.length; + for(let i=0;i< s.length;i++){ + for (let j = i+1; j <=s.length; j++) { + let temp = s.substring(i,j); + if(j-i+1 > maxLen && temp === reverseS.substring(lens-j, lens-i)){ + maxLen = j-i+1; + maxPaStr =temp; + } + } + } + return maxPaStr; +}; + +// 以上代码可通过 + +let s = "abacda"; +console.log(longestPalindrome2(s)); \ No newline at end of file From 61e6d4ace98cdd6f20526ea0bf6dfc493a8e9c3e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 22 Jun 2019 16:18:31 +0800 Subject: [PATCH 197/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E6=97=A0=E9=87=8D=E5=A4=8D=E5=AD=90=E4=B8=B2=E7=9A=84=E8=A7=A3?= =?UTF-8?q?=E9=A2=98=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...gestSubstringWithoutRepeatingCharacters.js | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Leetcode/3.LongestSubstringWithoutRepeatingCharacters.js diff --git a/Leetcode/3.LongestSubstringWithoutRepeatingCharacters.js b/Leetcode/3.LongestSubstringWithoutRepeatingCharacters.js new file mode 100644 index 0000000..58e53a4 --- /dev/null +++ b/Leetcode/3.LongestSubstringWithoutRepeatingCharacters.js @@ -0,0 +1,93 @@ +/****** + * + * 最长无重复子字符串 + * + * + * + */ + +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + let maxLen = 0; + if(s.length === 1){ + maxLen = 1; + } + function checkIfHasRepeat(str){ + if(Array.from(new Set(str.split(''))).join('') === str){ + return true; + }else { + return false; + } + } + + for (let i = 0; i < s.length; i++) { + for (let j = i+1; j <= s.length; j++) { + let temp = s.substring(i,j); + if(j-i > maxLen && checkIfHasRepeat(temp)){ + maxLen = j-i; + } + } + } + return maxLen; + +}; + +// 以上方案超时 + +// let s = 'abcabcbb'; +// console.log(lengthOfLongestSubstring(s)); + +var lengthOfLongestSubstring2 = function(s) { + let maxLen = 0; + if(s.length === 1){ + maxLen = 1; + } + + this.dfs = function(tempstr,i,j){ + let temp = tempstr.substring(i,j); + if(temp.indexOf(tempstr[j-1]) === temp.length-1){ + if(temp.length > maxLen){ + maxLen = temp.length; + } + }else { + return; + } + if(j < s.length){ + this.dfs(tempstr,i,j+1); + } + return; + } + for(let i=0;i< s.length-1;i++){ + this.dfs(s,i,i+1); + } + return maxLen; + +}; + +// 此方案可通过 + +// let s = 'pwwkew'; +// console.log(lengthOfLongestSubstring2(s)); + +// 以下是官方给的解题方案 解题思路滑动窗口 +var lengthOfLongestSubstring3 = function(s) { + let maxLen = 0; + let tset = new Set(); + let i=0,j=0; + let len = s.length; + while(i< len && j < len){ + if(!tset.has(s[j])){ + tset.add(s[j++]); + maxLen = Math.max(maxLen, j-i); + } else { + tset.delete(s[i++]); + } + } + return maxLen; +}; + +let s = 'pwwkew'; +console.log(lengthOfLongestSubstring3(s)); \ No newline at end of file From b7a3d325b42186df0943fa16f99fbbe88c4dd60f Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 23 Jun 2019 15:03:12 +0800 Subject: [PATCH 198/274] =?UTF-8?q?=E8=BF=94=E5=9B=9E=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E4=B8=AD=E4=B8=8D=E9=87=8D=E5=A4=8D=E9=83=A8=E5=88=86=E7=9A=84?= =?UTF-8?q?=E9=95=BF=E5=BA=A6=EF=BC=8C=E5=B9=B6=E4=BF=AE=E6=94=B9=E5=8E=9F?= =?UTF-8?q?=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../26.RemoveDuplicatesfromSortedArray.js | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Leetcode/26.RemoveDuplicatesfromSortedArray.js diff --git a/Leetcode/26.RemoveDuplicatesfromSortedArray.js b/Leetcode/26.RemoveDuplicatesfromSortedArray.js new file mode 100644 index 0000000..a6ac666 --- /dev/null +++ b/Leetcode/26.RemoveDuplicatesfromSortedArray.js @@ -0,0 +1,55 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-23 14:31:25 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-23 15:01:23 + */ + + +/**** + * + * 返回数组中不重复的部分 + * 返回的是长度 + * 原数组中的数对应位置也需要改变 + * + * + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function(nums) { + if(nums.length > 1){ + for(let i=1;i Date: Sun, 23 Jun 2019 15:30:58 +0800 Subject: [PATCH 199/274] =?UTF-8?q?LeetCode19=E9=A2=98=E4=BB=8E=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E6=9C=AB=E7=AB=AF=E7=A7=BB=E9=99=A4=E7=AC=ACN?= =?UTF-8?q?=E4=B8=AA=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/19.RemoveNthNodeFromEndofList.js | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Leetcode/19.RemoveNthNodeFromEndofList.js diff --git a/Leetcode/19.RemoveNthNodeFromEndofList.js b/Leetcode/19.RemoveNthNodeFromEndofList.js new file mode 100644 index 0000000..e99f3a5 --- /dev/null +++ b/Leetcode/19.RemoveNthNodeFromEndofList.js @@ -0,0 +1,52 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-23 15:29:17 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-23 15:30:22 + */ + + +/***** + * + * 从链表末端移除第N个节点 + * + * + * + */ + + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + * 快慢结点法 + */ +var removeNthFromEnd = function(head, n) { + let fastNode,slowNode,tempNode, i=1; + fastNode = head; + while(i Date: Sun, 23 Jun 2019 16:58:39 +0800 Subject: [PATCH 200/274] =?UTF-8?q?=E6=B1=82=E4=B8=80=E4=B8=AA=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E9=A1=BA=E5=BA=8F=E5=92=8C=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/53.MaximumSubarray.js | 93 ++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Leetcode/53.MaximumSubarray.js diff --git a/Leetcode/53.MaximumSubarray.js b/Leetcode/53.MaximumSubarray.js new file mode 100644 index 0000000..a2eb558 --- /dev/null +++ b/Leetcode/53.MaximumSubarray.js @@ -0,0 +1,93 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-23 15:34:16 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-23 16:58:20 + */ + + +/**** + * + * 求一个数组的顺序和最大的子数组 + * + * + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function(nums) { + let maxSum = -1*Number.MAX_VALUE; + if(nums.length === 1){ + return nums[0]; + } + for (let i = 0; i < nums.length; i++) { + for (let j = i+1; j <=nums.length; j++) { + let sum = nums[i]; + for (let m = i+1; m maxSum){ + maxSum = sum; + } + } + } + return maxSum; +}; + +// 以上方案超时 + +let nums = [-2,1,-3,4,-1,2,1,-5,4]; +// console.log(maxSubArray(nums)); + +var maxSubArray2 = function(nums) { + let maxSum = -1*Number.MAX_VALUE; + if(nums.length === 1){ + return nums[0]; + } + for (let i = 0; i < nums.length; i++) { + let sum = nums[i]; + for (let j = i+1; j < nums.length; j++) { + sum += nums[j]; + maxSum = Math.max(maxSum,sum,nums[i],nums[j]); + } + } + return maxSum; +}; +console.log(maxSubArray2(nums)); + +var maxSubArray3 = function(nums) { + let maxSum = -1*Number.MAX_VALUE; + if(nums.length === 1){ + return nums[0]; + } + for (let i = 0; i < nums.length; i++) { + let sum = nums[i]; + for (let j = i+1; j < nums.length; j++) { + sum += nums[j]; + if(maxSum < sum){ + maxSum = dum; + } + if(maxSum < nums[i]){ + maxSum = nums[i]; + } + if(maxSum < nums[j]){ + maxSum = nums[j]; + } + } + } + return maxSum; +}; + + +// 以下方案是时间复杂度最低,空间复杂度较高 +var maxSubArray4 = function(nums) { + let globalMax = nums[0], + localMax = nums[0]; + for (let i = 1; i < nums.length; i++) { + localMax = Math.max(nums[i], nums[i] + localMax); + globalMax = Math.max(globalMax, localMax); + } + return globalMax; +}; \ No newline at end of file From 9400f4e9458ce73ca8785d3fc7c9e6774242ea4c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 23 Jun 2019 22:29:16 +0800 Subject: [PATCH 201/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=88=B1=E5=A5=87?= =?UTF-8?q?=E8=89=BA=E6=95=B0=E7=BB=84=E6=8E=92=E5=BA=8F=E6=94=B9=E5=8A=A8?= =?UTF-8?q?=E6=AC=A1=E6=95=B0=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2018Enterprise/countChangeTimes-aiqiyi.js | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 NowCoder/2018Enterprise/countChangeTimes-aiqiyi.js diff --git a/NowCoder/2018Enterprise/countChangeTimes-aiqiyi.js b/NowCoder/2018Enterprise/countChangeTimes-aiqiyi.js new file mode 100644 index 0000000..f9d0514 --- /dev/null +++ b/NowCoder/2018Enterprise/countChangeTimes-aiqiyi.js @@ -0,0 +1,36 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-23 22:26:24 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-23 22:28:12 + */ + + +function countChange(arr,n){ + if(arr.length !== n || n===0 || n===1){ + return 0; + } + let arrC = arr.slice(0); + arrC = arrC.sort((a,b)=> a-b); + let count = 0; + for(let i=0;i Date: Mon, 24 Jun 2019 21:28:14 +0800 Subject: [PATCH 202/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=A7=84=E5=88=92=E7=9A=84=E5=B0=9D=E8=AF=95=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E6=80=9D=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1.找到状态的定义 2.找到状态转移方程的定义 --- DataStructures/AlgorithmMode/LISbyDP.js | 43 +++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 DataStructures/AlgorithmMode/LISbyDP.js diff --git a/DataStructures/AlgorithmMode/LISbyDP.js b/DataStructures/AlgorithmMode/LISbyDP.js new file mode 100644 index 0000000..b86a8a3 --- /dev/null +++ b/DataStructures/AlgorithmMode/LISbyDP.js @@ -0,0 +1,43 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-24 21:13:08 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-24 21:25:26 + */ + +/**** + * + * 最长上升子序列问题 + * + * 经典动态规划的思想 + * + * 状态是什么? fs[i] + * 状态转移方程是什么? + * fs[i] = fs[j] + 1 (if fs[j] < fs[i] && j Date: Tue, 25 Jun 2019 21:58:43 +0800 Subject: [PATCH 203/274] =?UTF-8?q?=E7=94=A8=E5=8F=8B=E7=9A=84=E4=B8=80?= =?UTF-8?q?=E5=A5=97=E9=A2=98=E7=9B=AE=E4=B8=AD=E7=9A=84=E4=B8=A4=E9=81=93?= =?UTF-8?q?=E7=AE=80=E5=8D=95=E7=BC=96=E7=A8=8B=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2018Enterprise/changeCSSWebkit-yongyou.js | 42 +++++++++++++++++++ .../2018Enterprise/eventExample.-yongyou.js | 27 ++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 NowCoder/2018Enterprise/changeCSSWebkit-yongyou.js create mode 100644 NowCoder/2018Enterprise/eventExample.-yongyou.js diff --git a/NowCoder/2018Enterprise/changeCSSWebkit-yongyou.js b/NowCoder/2018Enterprise/changeCSSWebkit-yongyou.js new file mode 100644 index 0000000..36b5f2e --- /dev/null +++ b/NowCoder/2018Enterprise/changeCSSWebkit-yongyou.js @@ -0,0 +1,42 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-25 21:16:37 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-25 21:58:05 + */ + + +/***** + * + * + * + * + */ + +function changeItem(arr){ + let newArr = arr.toLowerCase(); + let backStr = ""; + let state =true; + for (let i = 0; i < newArr.length; i++) { + if(i!==0 && newArr[i]==='-'){ + state = false; + }else if(newArr[i] !=='-'){ + if(!state){ + backStr += newArr[i].toUpperCase(); + state = !state; + }else{ + backStr += newArr[i]; + } + } + } + return backStr; +} +let arr = "-webkit-background-image"; +console.log(changeItem(arr)); + +// 官方答案 +const camel_hump = str => { + return str.replace(/(?:\-|\_)([a-z])/g, (input, match) => { + return match.toUpperCase(); + }); +} \ No newline at end of file diff --git a/NowCoder/2018Enterprise/eventExample.-yongyou.js b/NowCoder/2018Enterprise/eventExample.-yongyou.js new file mode 100644 index 0000000..5946793 --- /dev/null +++ b/NowCoder/2018Enterprise/eventExample.-yongyou.js @@ -0,0 +1,27 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-25 21:31:59 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-25 21:45:21 + */ + + +/***** + * + * 事件的监听和触发 + * + * + */ + +let btn = document.getElementById('buttom'); +btn.onclick = function (){ + +} + +let EventEmitter = { + + on(){ + let btn = document.getElementById('buttom'); + + } +} \ No newline at end of file From b91768f6278fed048ad2fcebcc252783c5e06bf2 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 26 Jun 2019 22:10:17 +0800 Subject: [PATCH 204/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0JavaScript=20?= =?UTF-8?q?=E5=9F=BA=E7=A1=80=E8=83=BD=E5=8A=9B=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/JavaScriptAbility/1.indexOf.js | 22 +++++++++ NowCoder/JavaScriptAbility/3.removeItem.js | 12 +++++ .../JavaScriptAbility/4.removeWithoutCopy.js | 47 +++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 NowCoder/JavaScriptAbility/1.indexOf.js create mode 100644 NowCoder/JavaScriptAbility/3.removeItem.js create mode 100644 NowCoder/JavaScriptAbility/4.removeWithoutCopy.js diff --git a/NowCoder/JavaScriptAbility/1.indexOf.js b/NowCoder/JavaScriptAbility/1.indexOf.js new file mode 100644 index 0000000..58e66ae --- /dev/null +++ b/NowCoder/JavaScriptAbility/1.indexOf.js @@ -0,0 +1,22 @@ + +function indexOf(arr, item) { + if(Array.prototype.indexOf){ + return arr.indexOf(item); + }else{ + for(var i=0;i=0; index--) { + if(arr[index]===item){ + arr.splice(index,1) + } + } +} + +// 自己与自己作战 +// 将 arr 看作队列,不重复的再放一遍到队列最后, +// 循环一次会把原有的数组都清除掉,剩下的就是copy的不重复的数据,顺序也能保持一致 +function removeWithoutCopy3(arr, item){ + if (!arr || arr.length === 0) { + return arr; + } + for (var index = 0; index Date: Thu, 27 Jun 2019 21:07:19 +0800 Subject: [PATCH 205/274] =?UTF-8?q?=E5=BF=AB=E6=89=8B2019=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E6=8C=89=E5=AD=97=E5=85=B8=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/stringNormalization-kuaishou.js | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 NowCoder/2019/stringNormalization-kuaishou.js diff --git a/NowCoder/2019/stringNormalization-kuaishou.js b/NowCoder/2019/stringNormalization-kuaishou.js new file mode 100644 index 0000000..eb1f839 --- /dev/null +++ b/NowCoder/2019/stringNormalization-kuaishou.js @@ -0,0 +1,44 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-27 20:22:36 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-27 20:41:09 + */ + +/***** + * + * 字符串按照字典序归一化 + * + * + */ + + +function strDic(arr){ + if(!arr || arr.length === 0){ + return ''; + } + let countArr=[]; + arr = arr.split('').sort().join(''); + for(let i=0;ia-b) + for(let temp in countArr){ + backStr+= String(temp)+String(countArr[temp]); + } + return backStr; +} + +let arr = 'abadbsedfrt'; +// let arr = 'dabcab'; +console.log(strDic(arr)); + +// 自测程序 +// let datas = readline().split(' '); +// let arr = datas[0]; +// print(strDic(arr)); \ No newline at end of file From 84f4a374bdc458082db8efb25901d877724b4861 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 27 Jun 2019 21:08:14 +0800 Subject: [PATCH 206/274] =?UTF-8?q?=E5=AE=9A=E6=97=B6=E5=99=A8=E6=89=93?= =?UTF-8?q?=E5=8D=B0=E8=BF=9E=E7=BB=AD=E6=95=B0=E5=AD=97=EF=BC=8C=E5=8F=AF?= =?UTF-8?q?=E5=8F=96=E6=B6=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/JavaScriptAbility/counter.js | 57 +++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 NowCoder/JavaScriptAbility/counter.js diff --git a/NowCoder/JavaScriptAbility/counter.js b/NowCoder/JavaScriptAbility/counter.js new file mode 100644 index 0000000..a13d03f --- /dev/null +++ b/NowCoder/JavaScriptAbility/counter.js @@ -0,0 +1,57 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-27 20:52:17 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-27 21:06:45 + */ + +function count(start, end) { + console.log(start); + function timeInterval(){ + // 执行定时调用的方法 + if(start < end){ + console.log(++start); + setTimeout(timeInterval, 100); + } + } + timeInterval(); + let backObj={}; + backObj.cancel = function(){ + timeInterval=null; + } + return backObj; +} + +function count2(start, end) { + if(start<=end){ + console.log(start++); + var timer = setTimeout(function(){count(start,end)},100); + } + return { + cancel:function(){ + clearTimeout(timer); + } + }; +} + + +// 只有第三个通过了 + +function count3(start, end) { + console.log(start++); + var timer = setInterval(function(){ + if(start<=end){ + console.log(start++); + }else { + clearInterval(timer); + } + },100); + + return { + cancel:function(){ + clearInterval(timer); + } + }; +} + +count3(1,10); \ No newline at end of file From 1899c17dadebc85b0a95164092323a200cee86b7 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 27 Jun 2019 21:16:03 +0800 Subject: [PATCH 207/274] =?UTF-8?q?=E6=B5=81=E7=A8=8B=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E4=B8=8E=E5=87=BD=E6=95=B0=E4=BC=A0=E5=8F=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../JavaScriptAbility/functionParametor.js | 25 +++++++++++++++++++ NowCoder/JavaScriptAbility/processControl.js | 23 +++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 NowCoder/JavaScriptAbility/functionParametor.js create mode 100644 NowCoder/JavaScriptAbility/processControl.js diff --git a/NowCoder/JavaScriptAbility/functionParametor.js b/NowCoder/JavaScriptAbility/functionParametor.js new file mode 100644 index 0000000..cf38a0b --- /dev/null +++ b/NowCoder/JavaScriptAbility/functionParametor.js @@ -0,0 +1,25 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-27 21:14:50 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-27 21:15:47 + */ + + +/***** + * + * 将 arr 作为 fn 的参数 + * + * + */ + +// input: +// function (greeting, name, punctuation) {return greeting + ', ' + name + (punctuation || '!');}, ['Hello', 'Ellie', '!'] + +// output: +// Hello, Ellie! + + +function argsAsArray(fn, arr) { + return fn.apply(this,arr); +} \ No newline at end of file diff --git a/NowCoder/JavaScriptAbility/processControl.js b/NowCoder/JavaScriptAbility/processControl.js new file mode 100644 index 0000000..8a9f876 --- /dev/null +++ b/NowCoder/JavaScriptAbility/processControl.js @@ -0,0 +1,23 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-27 21:12:14 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-27 21:12:14 + */ + + +function fizzBuzz(num) { + if(!num || typeof num !== 'number'){ + return false; + }else { + if(num%3 === 0 && num%5===0){ + return 'fizzbuzz'; + }else if(num%3 === 0){ + return 'fizz'; + }else if(num%5===0){ + return 'buzz'; + }else { + return num; + } + } +} \ No newline at end of file From 7d4ad6e56dbe0db231afc1f495f017af14028dab Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 28 Jun 2019 16:50:49 +0800 Subject: [PATCH 208/274] =?UTF-8?q?=E5=A3=B9=E9=92=B1=E5=8C=85=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E5=88=B7=E6=96=B0=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/11.ContainerWithMostWater.js | 47 +++++++++++++++++++++++++++ NowCoder/2019/htmltime-oneWallet.html | 21 ++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 Leetcode/11.ContainerWithMostWater.js create mode 100644 NowCoder/2019/htmltime-oneWallet.html diff --git a/Leetcode/11.ContainerWithMostWater.js b/Leetcode/11.ContainerWithMostWater.js new file mode 100644 index 0000000..d2a363f --- /dev/null +++ b/Leetcode/11.ContainerWithMostWater.js @@ -0,0 +1,47 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-28 16:37:57 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-28 16:50:26 + */ + + +/***** + * + * + * 柱状值数组能够装水的最大容量 + * + * + */ + +/** + * @param {number[]} height + * @return {number} + */ +// 以下算法时间复杂度为 O(n^2) +var maxArea = function(height) { + let backout=0; + if(height.length <2){ + return backout; + } + for(let i=0;i + + + + time + + +

+ Current Time: +
+

+ + + \ No newline at end of file From 32ba0e3d42f09fdd5d19f99460730989e28e94f9 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 29 Jun 2019 09:54:23 +0800 Subject: [PATCH 209/274] =?UTF-8?q?=E6=95=B4=E6=95=B0=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E6=88=90=E7=BD=97=E9=A9=AC=E6=95=B0=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/12.IntegertoRoman.js | 66 +++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Leetcode/12.IntegertoRoman.js diff --git a/Leetcode/12.IntegertoRoman.js b/Leetcode/12.IntegertoRoman.js new file mode 100644 index 0000000..94c15b5 --- /dev/null +++ b/Leetcode/12.IntegertoRoman.js @@ -0,0 +1,66 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-29 09:14:26 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-29 09:43:00 + */ + + + +/***** + * + * + * 将整数转换成罗马数字 + * + */ + + +/** + * @param {number} num + * @return {string} + */ +var intToRoman = function(num) { + let symbolArr = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']; + let valueArr = [1000,900,500,400,100,90,50,40,10,9,5,4,1]; + let curNum = num,i=0,outStr=''; + while(curNum > 0){ + if(curNum - valueArr[i]>=0){ + outStr+=symbolArr[i]; + curNum = curNum - valueArr[i] + }else { + i++; + } + } + return outStr; +}; + + +// 好的思路 +// 千,百,十,个 +// class Solution { +// public String intToRoman(int n) { +// String M[] = {"", "M", "MM", "MMM"}; +// String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; +// String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; +// String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; +// return M[n / 1000] + C[(n / 100) % 10] + X[(n / 10) % 10] + I[n % 10]; +// } +// } + +var intToRoman2 = function(num) { + num = parseInt(num); + let M = ["", "M", "MM", "MMM"]; + let C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; + let X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; + let I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; + let i = parseInt((num / 1000)? (num / 1000):0), + j = parseInt(((num / 100) % 10)? (num / 100) % 10:0), + k = parseInt(((num / 10) % 10)? (num / 10)%10:0), + m = parseInt(num % 10); + return M[i] + C[j] + X[k] + I[m]; +} + + +let num = 1994; +console.log(intToRoman(num)); +console.log(intToRoman2(num)); \ No newline at end of file From b808186c359eea16c60b911c65d31095870f9342 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 30 Jun 2019 16:08:24 +0800 Subject: [PATCH 210/274] =?UTF-8?q?=E6=95=B4=E6=95=B0=E8=BD=AC=E7=BD=97?= =?UTF-8?q?=E9=A9=AC=E5=AD=97=E6=AF=8D=E4=BB=A5=E5=8F=8A=E7=BD=97=E9=A9=AC?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E8=BD=AC=E6=95=B4=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/12.IntegertoRoman.js | 3 ++- Leetcode/13.RomantoInteger.js | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 Leetcode/13.RomantoInteger.js diff --git a/Leetcode/12.IntegertoRoman.js b/Leetcode/12.IntegertoRoman.js index 94c15b5..9e61f37 100644 --- a/Leetcode/12.IntegertoRoman.js +++ b/Leetcode/12.IntegertoRoman.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-06-29 09:14:26 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-06-29 09:43:00 + * @Last Modified time: 2019-06-29 10:06:21 */ @@ -47,6 +47,7 @@ var intToRoman = function(num) { // } // } +// 需要注意的是 JavaScript 中可能需要取整操作 var intToRoman2 = function(num) { num = parseInt(num); let M = ["", "M", "MM", "MMM"]; diff --git a/Leetcode/13.RomantoInteger.js b/Leetcode/13.RomantoInteger.js new file mode 100644 index 0000000..8c27a5c --- /dev/null +++ b/Leetcode/13.RomantoInteger.js @@ -0,0 +1,40 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-29 10:07:10 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-29 10:07:42 + */ + + +/***** + * + * + * 罗马字符串转数字 + * + */ + +/** + * @param {string} s + * @return {number} + */ +var romanToInt = function(s) { + let symbolArr = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']; + let valueArr = [1000,900,500,400,100,90,50,40,10,9,5,4,1]; + if(s.length === 1){ + return valueArr[symbolArr.indexOf(s)]; + } + let backNum = 0; + for(let i =0;isymbolArr.indexOf(s[i+1])){ + backNum += parseInt(valueArr[symbolArr.indexOf(s.slice(i,i+2))]); + i++; + }else{ + backNum += parseInt(valueArr[symbolArr.indexOf(s[i])]); + } + }else{ + backNum += parseInt(valueArr[symbolArr.indexOf(s[i])]); + } + } + return backNum; +}; \ No newline at end of file From 577ac91866280d6a971f8ee166e789fb55838c01 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 30 Jun 2019 22:19:23 +0800 Subject: [PATCH 211/274] =?UTF-8?q?=E5=AD=97=E8=8A=82=E8=B7=B3=E5=8A=A8?= =?UTF-8?q?=E4=B8=89=E9=81=93=E7=BC=96=E7=A8=8B=E9=A2=98=EF=BC=8C=E8=B7=B3?= =?UTF-8?q?=E6=9D=BF=E9=97=AE=E9=A2=98=E5=BE=85=E8=A7=A3=E5=86=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/crazyCowProblem-byteDance.js | 57 ++++++++++++++++++++++ NowCoder/2019/findPrime-byteDance.js | 43 ++++++++++++++++ NowCoder/2019/jumpGameX-byteDance.js | 35 +++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 NowCoder/2019/crazyCowProblem-byteDance.js create mode 100644 NowCoder/2019/findPrime-byteDance.js create mode 100644 NowCoder/2019/jumpGameX-byteDance.js diff --git a/NowCoder/2019/crazyCowProblem-byteDance.js b/NowCoder/2019/crazyCowProblem-byteDance.js new file mode 100644 index 0000000..e5f4edb --- /dev/null +++ b/NowCoder/2019/crazyCowProblem-byteDance.js @@ -0,0 +1,57 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-30 21:31:56 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-30 21:55:41 + */ + + +/***** + * + * 疯牛问题 + * + * 思路:将问题转换成 能分配C头牛的最大间隔是多少 + * + * + */ + +function crazyCow(numN,numC,locations){ + let maxLen = 0; + if(numC===1){ + return maxLen; + } + let copyL = locations.slice(0); + copyL.sort(); + let left = 0; + let right = copyL[copyL.length-1]-copyL[0]; + + this.check = function(midNum,numC,copyL){ + let tempData = copyL[0]; + let count = 1; + for (let i = 0; i < copyL.length; i++) { + if(copyL[i]-tempData >= midNum){ + tempData= copyL[i]; + count++; + if(count>=numC){ + return true; + } + } + } + return false; + } + + while(right >= left){ + let mid = left + parseInt((right - left)/2); + if(this.check(mid,numC,copyL)){ + left = mid + 1; + }else { + right = mid - 1; + } + } + return left - 1; +} + +let numN = 5; +let numC = 3; +let locations = [1,2,8,4,9]; +console.log(crazyCow(numN,numC,locations)); \ No newline at end of file diff --git a/NowCoder/2019/findPrime-byteDance.js b/NowCoder/2019/findPrime-byteDance.js new file mode 100644 index 0000000..8b4b813 --- /dev/null +++ b/NowCoder/2019/findPrime-byteDance.js @@ -0,0 +1,43 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-30 21:53:06 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-30 22:18:58 + */ + + + +/** + * + * + * 找出小于N的所有质数 + * + * + * @param {*} N + * @returns + */ +function findPrime(N) { + let list = []; + if(N<=2){ + return list.join(' '); + } + var i = 2, j = 2; + let state; + while(i farthest) { + farthest = nums[i] + i; + } + } + start = end + 1; + end = farthest; + } + return jump; + } + return 0; +} \ No newline at end of file From f483b2468dc070e2682185b13f3d5493a513b663 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 1 Jul 2019 21:40:51 +0800 Subject: [PATCH 212/274] Create 121.BestTimetoBuyandSellStock.js --- Leetcode/121.BestTimetoBuyandSellStock.js | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Leetcode/121.BestTimetoBuyandSellStock.js diff --git a/Leetcode/121.BestTimetoBuyandSellStock.js b/Leetcode/121.BestTimetoBuyandSellStock.js new file mode 100644 index 0000000..359e3f3 --- /dev/null +++ b/Leetcode/121.BestTimetoBuyandSellStock.js @@ -0,0 +1,30 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-01 21:37:48 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-01 21:40:41 + */ + +/**** + * + * 买卖股票的最佳时机 + * + * + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let maxPro=0,min=Number.MAX_VALUE; + for(let i=0;i maxPro){ + maxPro = prices[i]-min; + } + } + return maxPro; +}; \ No newline at end of file From 63485241a9cf968295c60271dd448c85c8015556 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 2 Jul 2019 19:27:46 +0800 Subject: [PATCH 213/274] =?UTF-8?q?=E7=BD=91=E6=98=932019=E6=A0=A1?= =?UTF-8?q?=E6=8B=9B=E6=97=8B=E8=BD=AC=E6=96=B9=E5=90=91=E7=89=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2018Enterprise/findDirection-neteasy.js | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 NowCoder/2018Enterprise/findDirection-neteasy.js diff --git a/NowCoder/2018Enterprise/findDirection-neteasy.js b/NowCoder/2018Enterprise/findDirection-neteasy.js new file mode 100644 index 0000000..6c08553 --- /dev/null +++ b/NowCoder/2018Enterprise/findDirection-neteasy.js @@ -0,0 +1,56 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-02 19:20:33 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-02 19:27:10 + */ + + +/**** + * + * + * 面朝北 N + * + * 输入第一行 旋转几次 N + * 输入第二行 旋转左右的字符串 + * + * 输出最终的旋转方向 + * + * 北 N + * 东 E + * 南 S + * 西 W + * + * + */ + +function lastDirection(numN,str){ + if(!str || str.length === 0){ + return ''; + } + let dirs = ['N','E','S','W']; + let start = 0; + // let outDir = dirs[0]; + for(let i=0;i Date: Tue, 2 Jul 2019 20:57:46 +0800 Subject: [PATCH 214/274] =?UTF-8?q?=E5=AF=BB=E6=89=BE=E7=AC=A6=E5=90=88?= =?UTF-8?q?=E6=9D=A1=E4=BB=B6=E7=9A=84=E6=95=B0=E5=80=BC=E5=AF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../findNumofDataList-neteasy.js | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 NowCoder/2018Enterprise/findNumofDataList-neteasy.js diff --git a/NowCoder/2018Enterprise/findNumofDataList-neteasy.js b/NowCoder/2018Enterprise/findNumofDataList-neteasy.js new file mode 100644 index 0000000..55eb7d4 --- /dev/null +++ b/NowCoder/2018Enterprise/findNumofDataList-neteasy.js @@ -0,0 +1,63 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-02 19:37:30 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-02 20:33:22 + */ + + +/**** + * + * find data list of Num N and Num K + * + * + */ + +function findNumofData(numN, numK){ + if(numN<1 || numK<0){ + return 0; + } + let count = 0; + for(let x=1;x<=numN;x++){ + for(let y=1;y<=numN;y++){ + if(parseInt(x % y) >= numK){ + count++; + } + } + } + return count; +} + +// 以上算法时间复杂度过高 + +let numN = 5; +let numK = 2; + +// console.log(findNumofData(numN, numK)); +// let datas = readline().split(' '); +// let numN = parseInt(datas[0]); +// let numK = parseInt(datas[1]); +// print(findNumofData(numN, numK)); + + + +function findNumofData2(numN, numK){ + if(numN<1 || numK<0){ + return 0; + } + let count = 0; + let x=1,y=1; + if(numK === 0){ + count = numN*numN; + }else { + for(let y=numK+1;y<=numN;y++){ + // 在 1~ n*y 中,共有 [(numN/y)*(y-numK)]组 (此时 n*y+y>numN) + // 在 n*y+1 ~ numN 中 有 (numN % y)-numK+1 个数满足 + count+= parseInt(numN/y)*parseInt(y-numK)+ Math.max(parseInt(numN%y-numK+1),0); + } + } + + return count; +} + +console.log(findNumofData2(numN, numK)); \ No newline at end of file From 9d47e42f2263614f3e56dcea5af7698a16ad3d61 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 5 Jul 2019 21:24:42 +0800 Subject: [PATCH 215/274] =?UTF-8?q?=E9=A1=BA=E5=BA=8F=E6=8E=A5=E7=BA=B8?= =?UTF-8?q?=E7=89=8C-byteDance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/byteDance/0705-1.js | 67 +++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 NowCoder/2019/byteDance/0705-1.js diff --git a/NowCoder/2019/byteDance/0705-1.js b/NowCoder/2019/byteDance/0705-1.js new file mode 100644 index 0000000..f04ecad --- /dev/null +++ b/NowCoder/2019/byteDance/0705-1.js @@ -0,0 +1,67 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-05 20:45:34 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-05 21:23:58 + */ + + +/****** + * + * 两人随机平分 52 张扑克,每人 26张 + * byte 先开始 + * dance 后开始 + * + * 相同的收回两张相同的牌及中间所有的牌 + * + * + * + */ + +function judgeWhoWin(arrB,arrD){ + let lenB=0,lenD=0; + let datas = []; + let i=0,j=0; + let stateB=-1,stateD=-1; + let outside; + while(i<26){ + stateB = datas.indexOf(arrB[i]); + if(stateB > -1){ + lenB += parseInt(datas.length + 1 - stateB); + if(stateB === 0){ + datas = []; + }else{ + datas = datas.slice(0, stateB); + } + + }else{ + datas.push(arrB[i]); + } + stateD = datas.indexOf(arrD[i]); + if(stateD > -1){ + lenD += parseInt(datas.length + 1 - stateD); + if(stateD === 0){ + datas = []; + }else{ + datas = datas.slice(0, stateD); + } + }else{ + datas.push(arrD[i]); + } + i++; + // console.log(datas); + } + if(lenB === lenD){ + outside = "Draw"; + }else if(lenB > lenD){ + outside = "Byte"; + }else { + outside = "Dance"; + } + return outside; +} + +let arrB = [10,2,5,6,13,11,11,4,10,8,12,5,4,1,8,1,7,12,4,13,6,9,9,9,5,7]; +let arrD = [6,3,13,8,2,3,7,3,2,2,12,11,10,6,10,1,1,12,3,5,7,11,13,4,8,9]; + +console.log(judgeWhoWin(arrB,arrD)); \ No newline at end of file From a231f49f43f40c38cae3777d15b095fccbe274ec Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 5 Jul 2019 21:41:20 +0800 Subject: [PATCH 216/274] =?UTF-8?q?=E8=AE=A1=E7=AE=97=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E6=97=A5=E6=9C=9F=E5=88=B0=202012.03.12?= =?UTF-8?q?=E7=9A=84=E5=A4=A9=E6=95=B0=EF=BC=8C=E5=BE=97=E5=88=B0=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/byteDance/0705-2.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 NowCoder/2019/byteDance/0705-2.js diff --git a/NowCoder/2019/byteDance/0705-2.js b/NowCoder/2019/byteDance/0705-2.js new file mode 100644 index 0000000..9d34871 --- /dev/null +++ b/NowCoder/2019/byteDance/0705-2.js @@ -0,0 +1,31 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-05 21:26:33 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-05 21:40:46 + */ + + +/***** + * + * 计算日期到 2012.03.12的天数 + * + * + * + */ + +function findDays(arrs){ + let outCount = []; + let startDate = new Date('2012-3-12'); + this.calDay = function(tempDate){ + let newDate = new Date(String(tempDate.join('-'))); + return parseInt((newDate-startDate)/24/60/60/1000); + } + for (let i = 0; i < arrs.length; i++) { + outCount.push(this.calDay(arrs[i])); + } + return outCount; +} + +let arrs = [[2012,3,14],[2013,3,12],[2014,5,15],[2019,3,12],[2019,7,5]]; +console.log(findDays(arrs)); \ No newline at end of file From 3dd2a5072c7ff0e3316158a0ef9cbbd26d9f6bc5 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 5 Jul 2019 22:07:49 +0800 Subject: [PATCH 217/274] =?UTF-8?q?=E6=89=BE=E6=9C=80=E5=B0=8F=E7=8F=AD?= =?UTF-8?q?=E7=BA=A7=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/byteDance/0705-2.js | 2 +- NowCoder/2019/byteDance/0705-3.js | 47 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 NowCoder/2019/byteDance/0705-3.js diff --git a/NowCoder/2019/byteDance/0705-2.js b/NowCoder/2019/byteDance/0705-2.js index 9d34871..c57db27 100644 --- a/NowCoder/2019/byteDance/0705-2.js +++ b/NowCoder/2019/byteDance/0705-2.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-07-05 21:26:33 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-07-05 21:40:46 + * @Last Modified time: 2019-07-05 21:41:54 */ diff --git a/NowCoder/2019/byteDance/0705-3.js b/NowCoder/2019/byteDance/0705-3.js new file mode 100644 index 0000000..1531e09 --- /dev/null +++ b/NowCoder/2019/byteDance/0705-3.js @@ -0,0 +1,47 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-05 21:42:07 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-05 22:06:19 + */ + +/**** + * + * 最少班级问题 + * + * n 门课,每门课 ai 个人选 + * + * 求最少班级数 + * + */ + +function findMinClass(numArr){ + let n = numArr.length; + let minClass = 0; + let minNum = numArr[0]; + for (let i = 0; i < n; i++) { + if(numArr[i] < minNum){ + minNum = numArr[i]; + } + } + let minCommon = 1; + for (let j = 1; j <=minNum; j++) { + let state = true; + for (let m = 0; m < n; m++) { + if(numArr[m]%j !== 0){ + state = false; + } + } + if(state){ + minCommon = j; + } + } + for (let k = 0; k < n; k++) { + minClass += parseInt(numArr[k]/minCommon); + } + + return minClass; +} + +let numArr = [4,6,8,12,10,6]; +console.log(findMinClass(numArr)); \ No newline at end of file From 72ff756a8c8c498fdaa62366be2ef405a952dbee Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Jul 2019 15:38:53 +0800 Subject: [PATCH 218/274] =?UTF-8?q?=E9=81=93=E8=B7=AF=E8=A7=84=E5=88=92?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E7=9A=84=E9=83=A8=E5=88=86=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/byteDance/0705-4.js | 66 +++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 NowCoder/2019/byteDance/0705-4.js diff --git a/NowCoder/2019/byteDance/0705-4.js b/NowCoder/2019/byteDance/0705-4.js new file mode 100644 index 0000000..f574fbb --- /dev/null +++ b/NowCoder/2019/byteDance/0705-4.js @@ -0,0 +1,66 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-06 12:58:14 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 15:38:36 + */ + + +/***** + * + * + * 道路规划问题 + * + * + * + */ + +function roadPlaning(numN,numM,strC,arrR){ + let outSide = []; + let rightArr = []; + let recordArr = []; + let roadNum = 0; + for (let i = 0; i < arrR.length; i++) { + let tempA = arrR[i]; + // 剔除那些不满足 A->B, B->A 的道路 + if(strC[parseInt(tempA[0])-1] !== strC[parseInt(tempA[1])-1]){ + rightArr.push(tempA); + recordArr.push(i); + } + } + if(rightArr.length === 0){ + return outSide; + } + + function check(arr){ + for(let m=1;m<=numN;m++){ + if(arr.indexOf(m)===-1){ + return false; + } + } + if(arr.length === numN){ + return false; + } + return true; + } + + let tempArr = []; + for (let j = 0; j <=rightArr.length; j++) { + tempArr = tempArr.concat(rightArr[j]); + outSide.push(recordArr[j]+1); + if(check(tempArr)){ + return outSide; + } + } + + +} + +let numN = 4; +let numM = 6; +let strC = "AABB"; +let arrR = [[3,4],[2,1],[4,2],[3,1],[1,4],[2,3]]; +let b = roadPlaning(numN,numM,strC,arrR); +console.log(b.length,b); + +// 部分解决方案 \ No newline at end of file From 6826053ebc007deaf2f6ac7b5d8b151ab0b768cf Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Jul 2019 16:33:44 +0800 Subject: [PATCH 219/274] =?UTF-8?q?=E7=BD=91=E7=BB=9C=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E4=B9=8B=E9=97=B4=E7=9A=84=E6=9C=80=E5=A4=A7=E6=97=B6=E5=BB=B6?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/byteDance/0705-5.js | 75 +++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 NowCoder/2019/byteDance/0705-5.js diff --git a/NowCoder/2019/byteDance/0705-5.js b/NowCoder/2019/byteDance/0705-5.js new file mode 100644 index 0000000..e4cb21c --- /dev/null +++ b/NowCoder/2019/byteDance/0705-5.js @@ -0,0 +1,75 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-06 15:47:41 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 16:33:24 + */ + + +/**** + * + * 网络节点之间的最大时延问题 + * + * + * + */ + + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +function findMaxTime(numN,arrA, nodeB){ + let tempArr = []; + for (let i = 0; i < numN; i++) { + tempArr[i]=[]; + for (let j = 0; j < numN; j++) { + tempArr[i].push(0); + } + } + let tempRoad; + // 构建 n*n 的矩阵 + for (let i = 0; i < arrA.length; i++) { + tempRoad = arrA[i]; + tempArr[parseInt(tempRoad[0]-1)][parseInt(tempRoad[1]-1)] = parseInt(tempRoad[2]); + tempArr[parseInt(tempRoad[1]-1)][parseInt(tempRoad[0]-1)] = parseInt(tempRoad[2]); + } + function checkMandN(m,n,tempArr){ + for (let i = 0; i < tempArr.length; i++) { + if(tempArr[i][m]!==0 && tempArr[i][n]!==0){ + if(!tempArr[m][n]){ + tempArr[m][n] = tempArr[i][m] + tempArr[i][n]; + }else { + tempArr[m][n] = Math.min(tempArr[i][m] + tempArr[i][n],tempArr[m][n]); + } + tempArr[n][m] = tempArr[m][n]; + } + } + } + for (let m = 0; m < tempArr.length; m++) { + for (let n = 0; n < tempArr[0].length; n++) { + if(m !==n && tempArr[m][n] === 0 && tempArr[n][m]===0){ + checkMandN(m,n,tempArr); + } + } + } + // console.log(tempArr); + let outside = []; + let node; + for (let j = 0; j < nodeB.length; j++) { + node = tempArr[parseInt(nodeB[j]-1)]; + node = node.sort(function(a,b){return a-b}); + outside.push(node[node.length-1]); + } + return outside; +} + +let numN = 4; +let arrA = [[1,2,10],[1,3,5],[4,1,3]]; +let nodeB = [2,4]; +console.log(findMaxTime(numN,arrA, nodeB)); + +// 部分案例可通过 +// 且效率应该不高 \ No newline at end of file From 25841f32b81a082769571a1327d4ca3f325b7b14 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Jul 2019 16:44:13 +0800 Subject: [PATCH 220/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=A7=A3=E9=A2=98?= =?UTF-8?q?=E6=80=9D=E8=B7=AF=E7=9A=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/byteDance/0705-1.js | 8 ++++++-- NowCoder/2019/byteDance/0705-2.js | 3 ++- NowCoder/2019/byteDance/0705-3.js | 6 +++++- NowCoder/2019/byteDance/0705-4.js | 8 +++++--- NowCoder/2019/byteDance/0705-5.js | 5 ++++- 5 files changed, 22 insertions(+), 8 deletions(-) diff --git a/NowCoder/2019/byteDance/0705-1.js b/NowCoder/2019/byteDance/0705-1.js index f04ecad..cebcad0 100644 --- a/NowCoder/2019/byteDance/0705-1.js +++ b/NowCoder/2019/byteDance/0705-1.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-07-05 20:45:34 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-07-05 21:23:58 + * @Last Modified time: 2019-07-06 16:43:38 */ @@ -25,18 +25,22 @@ function judgeWhoWin(arrB,arrD){ let stateB=-1,stateD=-1; let outside; while(i<26){ + // 在场面的牌中找先手的牌 stateB = datas.indexOf(arrB[i]); if(stateB > -1){ + // 找到先手的牌就对场面的牌进行处理 lenB += parseInt(datas.length + 1 - stateB); if(stateB === 0){ + // 如果位置是第一张牌,牌面清空 datas = []; }else{ datas = datas.slice(0, stateB); } - }else{ + // 没找到则先手的牌置入场中 datas.push(arrB[i]); } + // 要在这里对后手搜索,因为先手可能影响牌面 stateD = datas.indexOf(arrD[i]); if(stateD > -1){ lenD += parseInt(datas.length + 1 - stateD); diff --git a/NowCoder/2019/byteDance/0705-2.js b/NowCoder/2019/byteDance/0705-2.js index c57db27..f4e5882 100644 --- a/NowCoder/2019/byteDance/0705-2.js +++ b/NowCoder/2019/byteDance/0705-2.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-07-05 21:26:33 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-07-05 21:41:54 + * @Last Modified time: 2019-07-06 16:40:27 */ @@ -19,6 +19,7 @@ function findDays(arrs){ let startDate = new Date('2012-3-12'); this.calDay = function(tempDate){ let newDate = new Date(String(tempDate.join('-'))); + // 以毫秒计数,要除以1000来计算间隔的天数 return parseInt((newDate-startDate)/24/60/60/1000); } for (let i = 0; i < arrs.length; i++) { diff --git a/NowCoder/2019/byteDance/0705-3.js b/NowCoder/2019/byteDance/0705-3.js index 1531e09..5c20f77 100644 --- a/NowCoder/2019/byteDance/0705-3.js +++ b/NowCoder/2019/byteDance/0705-3.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-07-05 21:42:07 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-07-05 22:06:19 + * @Last Modified time: 2019-07-06 16:39:42 */ /**** @@ -13,6 +13,8 @@ * * 求最少班级数 * + * 求最大公约数 + * */ function findMinClass(numArr){ @@ -25,6 +27,7 @@ function findMinClass(numArr){ } } let minCommon = 1; + // 求n个数的最大公约数 for (let j = 1; j <=minNum; j++) { let state = true; for (let m = 0; m < n; m++) { @@ -36,6 +39,7 @@ function findMinClass(numArr){ minCommon = j; } } + // 根据最大公约数计算需要开班的个数 for (let k = 0; k < n; k++) { minClass += parseInt(numArr[k]/minCommon); } diff --git a/NowCoder/2019/byteDance/0705-4.js b/NowCoder/2019/byteDance/0705-4.js index f574fbb..76f7649 100644 --- a/NowCoder/2019/byteDance/0705-4.js +++ b/NowCoder/2019/byteDance/0705-4.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-07-06 12:58:14 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-07-06 15:38:36 + * @Last Modified time: 2019-07-06 16:38:19 */ @@ -28,10 +28,12 @@ function roadPlaning(numN,numM,strC,arrR){ recordArr.push(i); } } + // 如果没有符合同类型不互通的道路,则返回空 if(rightArr.length === 0){ return outSide; } + // 检查当前收集的道路对能否满足所有互联需求 function check(arr){ for(let m=1;m<=numN;m++){ if(arr.indexOf(m)===-1){ @@ -45,6 +47,7 @@ function roadPlaning(numN,numM,strC,arrR){ } let tempArr = []; + // 按照顺序进行填入检查,此处需要更改和升级 for (let j = 0; j <=rightArr.length; j++) { tempArr = tempArr.concat(rightArr[j]); outSide.push(recordArr[j]+1); @@ -52,8 +55,7 @@ function roadPlaning(numN,numM,strC,arrR){ return outSide; } } - - + return outSide; } let numN = 4; diff --git a/NowCoder/2019/byteDance/0705-5.js b/NowCoder/2019/byteDance/0705-5.js index e4cb21c..f1ae8d8 100644 --- a/NowCoder/2019/byteDance/0705-5.js +++ b/NowCoder/2019/byteDance/0705-5.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-07-06 15:47:41 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-07-06 16:33:24 + * @Last Modified time: 2019-07-06 16:35:47 */ @@ -36,6 +36,7 @@ function findMaxTime(numN,arrA, nodeB){ tempArr[parseInt(tempRoad[0]-1)][parseInt(tempRoad[1]-1)] = parseInt(tempRoad[2]); tempArr[parseInt(tempRoad[1]-1)][parseInt(tempRoad[0]-1)] = parseInt(tempRoad[2]); } + // 将m,n位置填满 function checkMandN(m,n,tempArr){ for (let i = 0; i < tempArr.length; i++) { if(tempArr[i][m]!==0 && tempArr[i][n]!==0){ @@ -50,6 +51,7 @@ function findMaxTime(numN,arrA, nodeB){ } for (let m = 0; m < tempArr.length; m++) { for (let n = 0; n < tempArr[0].length; n++) { + // 针对那些空位置,填满 if(m !==n && tempArr[m][n] === 0 && tempArr[n][m]===0){ checkMandN(m,n,tempArr); } @@ -60,6 +62,7 @@ function findMaxTime(numN,arrA, nodeB){ let node; for (let j = 0; j < nodeB.length; j++) { node = tempArr[parseInt(nodeB[j]-1)]; + // 要求最大时延的,直接查表 node = node.sort(function(a,b){return a-b}); outside.push(node[node.length-1]); } From 912b3766b2e21e9da2de67e146b8ebc6c3a6c021 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Jul 2019 17:03:19 +0800 Subject: [PATCH 221/274] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=8E=92=E5=BA=8F?= =?UTF-8?q?=E7=9A=84=E5=87=A0=E4=B8=AA=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js | 2 +- .../basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js | 2 +- .../basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js index 7c832e9..ccdb212 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js @@ -2,7 +2,7 @@ * @author SkylineBin * @time 2018-10-6 * @function create InsertionSort by JavaScript - * + * 实现插入排序 * @Algorithm_bigO * best_bigO = O(N) * worst_bigO = O(N^2) diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js index 6d58beb..8856a0f 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js @@ -2,7 +2,7 @@ * @author SkylineBin * @time 2018-10-6 * @function create MergeSort by JavaScript - * + * 归并排序 * @Algorithm_bigO * O(N * log(N)) * diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js index 52a7cc7..8870b39 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js @@ -2,7 +2,7 @@ * @author SkylineBin * @time 2018-10-6 * @function use javascript to create SelectionSort - * + * 选择排序 * @Algorithm_bigO O(N ^ 2) * N is the length of arrays * From 4abb51836524ad92b4741b3604aa499847843035 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 6 Jul 2019 22:10:39 +0800 Subject: [PATCH 222/274] =?UTF-8?q?=E5=A4=84=E7=90=86=20arguments=20?= =?UTF-8?q?=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/JavaScriptAbility/argumentsAdd.js | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 NowCoder/JavaScriptAbility/argumentsAdd.js diff --git a/NowCoder/JavaScriptAbility/argumentsAdd.js b/NowCoder/JavaScriptAbility/argumentsAdd.js new file mode 100644 index 0000000..6d28dd3 --- /dev/null +++ b/NowCoder/JavaScriptAbility/argumentsAdd.js @@ -0,0 +1,41 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-06 22:04:00 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 22:09:47 + */ + + +/**** + * + * Arguments 求和的解法 + * + * + * + */ + + +// 普通版本 +function useArguments() { + var outside = 0; + for(var i=0;i args.reduce((a,b)=>a+b); +console.log(useArgumentsES6(1,2,3,4,5,6)); \ No newline at end of file From eaf6179ee6f8e30cc715be0aa43e6fe46ac25e65 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 7 Jul 2019 21:50:31 +0800 Subject: [PATCH 223/274] =?UTF-8?q?=E5=AD=97=E8=8A=82=E8=B7=B3=E5=8A=A8?= =?UTF-8?q?=E7=9A=84=E4=B8=89=E9=81=93=E9=A2=98=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019/byteDance/0707-1.js | 54 ++++++++++ NowCoder/2019/byteDance/0707-3.js | 165 ++++++++++++++++++++++++++++++ NowCoder/2019/byteDance/0707-4.js | 59 +++++++++++ 3 files changed, 278 insertions(+) create mode 100644 NowCoder/2019/byteDance/0707-1.js create mode 100644 NowCoder/2019/byteDance/0707-3.js create mode 100644 NowCoder/2019/byteDance/0707-4.js diff --git a/NowCoder/2019/byteDance/0707-1.js b/NowCoder/2019/byteDance/0707-1.js new file mode 100644 index 0000000..7c788f8 --- /dev/null +++ b/NowCoder/2019/byteDance/0707-1.js @@ -0,0 +1,54 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-07 16:29:51 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-07 17:21:23 + */ + + +/****** + * + * 比赛问题 + * + * 田忌赛马问题 + * + * 思路总结:先比较最大的是否大,再比较最小的是否大, + * 如果都不满足就用最小的和对方最大的比较输一场,后续继续按照此思路继续比较 + * + * + * + */ + +function findMaxCount(arrA, arrB){ + let count = 0; + arrA.sort((a,b)=>a-b); // my team + arrB.sort((a,b)=>a-b); // other team + let i=0,j=0; + let m= arrA.length-1,n=arrA.length-1; + let state = true; + while(state){ + if(i===m){ + state= !state; + } + if(arrA[m]>arrB[n]){ + count++; + m--; + n--; + }else if(arrA[i]>arrB[j]){ + i++; + j++; + count++; + }else { + if(arrA[i] maxValue){ + // return count; + // } + // } + + + this.dfs = function(num){ + if(num === len-1){ + for (let j = 1; j < len; j++) { + if(!vis[j] && Math.abs(nums[f[0]]-nums[j])<=maxValue && Math.abs(nums[j]-nums[f[num-1]])<=maxValue){ + count++; + f[num]=j; + console.log(f); + } + } + return; + }else{ + for (let i = 1; i < len; i++) { + if(!vis[i] && Math.abs(nums[f[num-1]]-nums[i]) <= maxValue){ + f[num] = i; + vis[i]=true; + this.dfs(num+1); + vis[i]=false; + } + } + } + } + vis[0] = true; + this.dfs(1); + return count; +} + +// let maxValue = 8; +// let nums = [5,16,8,10]; +// console.log(heightMaxMiddle(maxValue, nums)); + + + +// 记录上一次的选取的位置 +function heightMaxMiddle2(maxValue, nums){ + let count = 0; + let len = nums.length; + let vis=[]; + // let f = []; + // f[0]=0; + if(len === 1){ + return 1; + } + // let sortNums = nums.sort(function(a,b){ + // return a-b; + // }) + // // 排序后判断是否存在相差大于 maxValue 的情况 + // for (let i = 0; i < sortNums.length-1; i++) { + // vis[i]=false; + // // f[i+1]=0; + // if(sortNums[i+1]-sortNums[i] > maxValue){ + // return count; + // } + // } + + this.dfs = function(total,num,nums){ + if(total === len){ + if(Math.abs(nums[num]-nums[0])<=maxValue){ + count++; + } + return; + }else{ + for (let i = 0; i < len; i++) { + if(!vis[i] && Math.abs(nums[num]-nums[i])<=maxValue){ + vis[i]=true; + this.dfs(total+1,i,nums); + vis[i]=false; + } + } + } + } + vis[0]=true; + this.dfs(1,0,nums); + return count; +} + +// let maxValue = 8; +// let nums = [5,16,8,10]; +// console.log(heightMaxMiddle2(maxValue, nums)); + + + +// 对矩阵直接转换操作 +function heightMaxMiddle3(maxValue, nums){ + let m = maxValue; + let res = []; + let count = 0; + this.sort = function(nums,start,res){ + if(start == nums.length-1 && Math.abs(nums[start]-nums[start-1])<=m && Math.abs(nums[start]-nums[0])<=m){ + count++; + res.push(nums.slice(0)); + }else{ + for(let i = start; i < nums.length; i++){ + this.swap(nums, start, i); + if(Math.abs(nums[start]-nums[start-1])<=m){ + this.sort(nums, start+1, res); + } + this.swap(nums, start, i); + } + } + } + this.swap = function(arr,a,b){ + let temp = arr[a]; + arr[a] = arr[b]; + arr[b]= temp; + } + + this.sort(nums,1,res); + console.log(res); + return count; +} + +let maxValue = 8; +let nums = [5,16,8,10]; +console.log(heightMaxMiddle3(maxValue, nums)); \ No newline at end of file diff --git a/NowCoder/2019/byteDance/0707-4.js b/NowCoder/2019/byteDance/0707-4.js new file mode 100644 index 0000000..c8bb8e2 --- /dev/null +++ b/NowCoder/2019/byteDance/0707-4.js @@ -0,0 +1,59 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-07 13:53:10 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-07 16:23:35 + */ + +/**** + * + * 字节跳动第四题 + * + * + * 积分与喜爱值的背包问题 + * + * + */ + + +function knapSack (n, weights, values, m) { + let a, b, kS = []; + for (let i = 0; i <= m; i++) { + kS[i] = []; + } + + for (let j = 0; j <= m; j++) { + for (let w = 0; w <= n; w++) { + if (j == 0 || w == 0) { + kS[j][w] = 0; + } else if (weights[j-1] <= w) { + a = values[j-1] + kS[j-1][w-weights[j-1]]; + b = kS[j-1][w]; + kS[j][w] = (a > b) ? a : b; + } else { + kS[j][w] = kS[j-1][w]; + } + } + } + return kS[m][n]; +} + +let weights = [69,60,8]; +let values = [10,1,2]; +let n = 68; +let m = 3; +console.log(knapSack(n, weights, values, m)); + + +let datasOne = readline().split(' '); +let n = parseInt(datasOne[0]); +let m = parseInt(datasOne[1]); +let weights = []; +let values = []; +let temp; +for (let i = 0; i < m; i++) { + temp = readline().split(' '); + weights.push(parseInt(temp[0])); + values.push(parseInt(temp[1])); +} +print(knapSack(n, weights, values, m)); From b194f5c13ba34100400f98854aa8d55621d75838 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 12 Jul 2019 15:17:23 +0800 Subject: [PATCH 224/274] =?UTF-8?q?=E9=80=92=E5=BD=92=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=E5=90=88=E5=B9=B6=E4=B8=A4=E6=9C=89=E5=BA=8F=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E4=BB=A5=E5=8F=8A=E5=B0=BE=E9=80=92=E5=BD=92=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E4=BC=98=E5=8C=96=E8=B4=B9=E5=B8=83=E6=8B=89=E5=A5=87?= =?UTF-8?q?=E6=95=B0=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/Leetcode/16.mergeTwosortedLink.js | 18 ++++++++++ NowCoder/Leetcode/7.outputFibonacci.js | 41 ++++++++++++++++++++-- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/NowCoder/Leetcode/16.mergeTwosortedLink.js b/NowCoder/Leetcode/16.mergeTwosortedLink.js index a1d8478..d4f6a40 100644 --- a/NowCoder/Leetcode/16.mergeTwosortedLink.js +++ b/NowCoder/Leetcode/16.mergeTwosortedLink.js @@ -56,4 +56,22 @@ function Merge(pHead1, pHead2) } return outputLink; +} + + +// 递归版本的做法 +function Merge2(pHead1, pHead2){ + if(pHead1 === null){ + return pHead2; + } + if(pHead2 === null){ + return pHead1; + } + if(pHead1.val <= pHead2.val){ + pHead1.next = Merge2(pHead1.next,pHead2); + return pHead1; + }else { + pHead2.next = Merge2(pHead1,pHead2.next); + return pHead2; + } } \ No newline at end of file diff --git a/NowCoder/Leetcode/7.outputFibonacci.js b/NowCoder/Leetcode/7.outputFibonacci.js index d0fc8aa..3f9f972 100644 --- a/NowCoder/Leetcode/7.outputFibonacci.js +++ b/NowCoder/Leetcode/7.outputFibonacci.js @@ -23,10 +23,47 @@ function Fibonacci(n) { } } +let n = 39; +console.log(Fibonacci(n)); + /* * 涉及理论: 循环 * 普通解法: 遍历 - * 改进方向: + * 改进方向:尾递归 * * - */ \ No newline at end of file + */ + +function tailFibonacci(n,ac1=0,ac2=1){ + if(n<=1) {return ac2} + return tailFibonacci(n-1, ac2, ac1+ac2); +} + +function Fibonacci2(n){ + if(n===0){ + return 0; + } + return tailFibonacci(n,ac1=0,ac2=1); +} + +console.log(Fibonacci2(n)); + + +/***** + * + * 使用动态规划思维思想解决 + * + * + */ + +function Fibonacci3(n){ + let f=0,s=1; + if(n===0){return 0;} + while(n--){ + s+=f; + f=s-f; + } + return f; +} + +console.log(Fibonacci3(n)); \ No newline at end of file From 4da825b5a7c80304cdf58bd6134b21fcf86552d5 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 12 Jul 2019 15:30:06 +0800 Subject: [PATCH 225/274] =?UTF-8?q?=E6=94=B9=E5=8F=98=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=A4=B9=E7=9A=84=E5=90=8D=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 剑指Offer->CodingInterviews CodingInterview -> RealInterviewExamination --- NowCoder/{Leetcode => CodingInterviews}/1.checkDatainArray.js | 0 NowCoder/{Leetcode => CodingInterviews}/10.recCover.js | 0 NowCoder/{Leetcode => CodingInterviews}/11.numberOf1.js | 0 NowCoder/{Leetcode => CodingInterviews}/12.doublePower.js | 0 NowCoder/{Leetcode => CodingInterviews}/13.reOrderArray.js | 0 NowCoder/{Leetcode => CodingInterviews}/14.findKthToTail.js | 0 NowCoder/{Leetcode => CodingInterviews}/15.ReverseList.js | 0 .../{Leetcode => CodingInterviews}/16.mergeTwosortedLink.js | 0 NowCoder/{Leetcode => CodingInterviews}/17.hasSubtree.js | 0 NowCoder/{Leetcode => CodingInterviews}/18.mirrorTree.js | 0 .../{Leetcode => CodingInterviews}/19.printMatrixbyClockwise.js | 0 .../{Leetcode => CodingInterviews}/2.replaceSpaceinString.js | 0 .../20.createMinStackStructure.js | 0 NowCoder/{Leetcode => CodingInterviews}/21.isPopOrder.js | 0 .../22.printTreeFromTopToBottom.js | 0 .../{Leetcode => CodingInterviews}/23.verifySquenceOfBST.js | 0 NowCoder/{Leetcode => CodingInterviews}/24.findPathofBinary.js | 0 .../{Leetcode => CodingInterviews}/25.cloneComplexLinkList.js | 0 .../26.convertBinaryTreetoDoubleLinkList.js | 0 NowCoder/{Leetcode => CodingInterviews}/27.permutationString.js | 0 .../28.moreThanHalfNum_Solution.js | 0 .../29.getLeastNumbers_Solution.js | 0 NowCoder/{Leetcode => CodingInterviews}/3.shiftListNode.js | 0 .../30.findGreatestSumOfSubArray.js | 0 .../31.numberOf1Between1AndN_Solution.js | 0 .../32.PrintConnectMinNumberofArray.js | 0 .../{Leetcode => CodingInterviews}/33.getUglyNumber_Solution.js | 0 .../{Leetcode => CodingInterviews}/34.firstNotRepeatingChar.js | 0 NowCoder/{Leetcode => CodingInterviews}/35.inversePairsNum.js | 0 .../36.findFirstCommonNodeofLinkNode.js | 0 NowCoder/{Leetcode => CodingInterviews}/37.getNumberOfK.js | 0 NowCoder/{Leetcode => CodingInterviews}/38.treeDepth.js | 0 NowCoder/{Leetcode => CodingInterviews}/39.isBalancedTree.js | 0 .../{Leetcode => CodingInterviews}/4.reConstructBinaryTree.js | 0 .../{Leetcode => CodingInterviews}/40.findNumsAppearOnce.js | 0 .../{Leetcode => CodingInterviews}/41.findContinuousSequence.js | 0 .../{Leetcode => CodingInterviews}/42.findNumbersWithSum.js | 0 NowCoder/{Leetcode => CodingInterviews}/43.loopLeftRotateStr.js | 0 NowCoder/{Leetcode => CodingInterviews}/44.reverseWords.js | 0 NowCoder/{Leetcode => CodingInterviews}/45.isContinuous.js | 0 .../{Leetcode => CodingInterviews}/46.lastRemaining_Solution.js | 0 NowCoder/{Leetcode => CodingInterviews}/47.sum_Solution.js | 0 NowCoder/{Leetcode => CodingInterviews}/48.addTwoNum.js | 0 NowCoder/{Leetcode => CodingInterviews}/49.strToInt.js | 0 .../{Leetcode => CodingInterviews}/5.useTwoStackCreatQueue.js | 0 NowCoder/{Leetcode => CodingInterviews}/50.duplicate.js | 0 NowCoder/{Leetcode => CodingInterviews}/51.multiply.js | 0 NowCoder/{Leetcode => CodingInterviews}/52.matchParren.js | 0 NowCoder/{Leetcode => CodingInterviews}/53.isNumeric.js | 0 .../{Leetcode => CodingInterviews}/54.firstAppearingOnce.js | 0 NowCoder/{Leetcode => CodingInterviews}/55.entryNodeOfLoop.js | 0 .../56.deleteDuplicationLinkNode.js | 0 NowCoder/{Leetcode => CodingInterviews}/57.getNextNode.js | 0 NowCoder/{Leetcode => CodingInterviews}/58.isSymmetrical.js | 0 .../{Leetcode => CodingInterviews}/59.printTreewithZhizi.js | 0 .../{Leetcode => CodingInterviews}/6.minNumberInRotateArray.js | 0 NowCoder/{Leetcode => CodingInterviews}/60.printTreebyLayer.js | 0 .../{Leetcode => CodingInterviews}/61.serializeAndSerialize.js | 0 NowCoder/{Leetcode => CodingInterviews}/62.kthSmallNode.js | 0 NowCoder/{Leetcode => CodingInterviews}/63.getMidim.js | 0 NowCoder/{Leetcode => CodingInterviews}/64.maxInWindows.js | 0 NowCoder/{Leetcode => CodingInterviews}/65.hasPath.js | 0 NowCoder/{Leetcode => CodingInterviews}/66.movingCountRobot.js | 0 NowCoder/{Leetcode => CodingInterviews}/7.outputFibonacci.js | 0 NowCoder/{Leetcode => CodingInterviews}/8.jumpStep.js | 0 NowCoder/{Leetcode => CodingInterviews}/9.jumpStepII.js | 0 NowCoder/{Leetcode => CodingInterviews}/findSumfromArray.js | 0 .../MinimumReturnSubstring.js | 0 .../checkIfLinkListPalindrome.js | 0 .../commonPartOfTwoLinkList.js | 2 +- .../findMaxEvenStrLength.js | 0 .../findMaxLengthDNA.js | 0 .../hanoiAdvanceProblems.js | 0 .../reverseStackByRecursion.js | 0 .../sortStackByStack.js | 0 75 files changed, 1 insertion(+), 1 deletion(-) rename NowCoder/{Leetcode => CodingInterviews}/1.checkDatainArray.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/10.recCover.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/11.numberOf1.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/12.doublePower.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/13.reOrderArray.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/14.findKthToTail.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/15.ReverseList.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/16.mergeTwosortedLink.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/17.hasSubtree.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/18.mirrorTree.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/19.printMatrixbyClockwise.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/2.replaceSpaceinString.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/20.createMinStackStructure.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/21.isPopOrder.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/22.printTreeFromTopToBottom.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/23.verifySquenceOfBST.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/24.findPathofBinary.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/25.cloneComplexLinkList.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/26.convertBinaryTreetoDoubleLinkList.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/27.permutationString.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/28.moreThanHalfNum_Solution.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/29.getLeastNumbers_Solution.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/3.shiftListNode.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/30.findGreatestSumOfSubArray.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/31.numberOf1Between1AndN_Solution.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/32.PrintConnectMinNumberofArray.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/33.getUglyNumber_Solution.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/34.firstNotRepeatingChar.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/35.inversePairsNum.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/36.findFirstCommonNodeofLinkNode.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/37.getNumberOfK.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/38.treeDepth.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/39.isBalancedTree.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/4.reConstructBinaryTree.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/40.findNumsAppearOnce.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/41.findContinuousSequence.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/42.findNumbersWithSum.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/43.loopLeftRotateStr.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/44.reverseWords.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/45.isContinuous.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/46.lastRemaining_Solution.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/47.sum_Solution.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/48.addTwoNum.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/49.strToInt.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/5.useTwoStackCreatQueue.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/50.duplicate.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/51.multiply.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/52.matchParren.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/53.isNumeric.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/54.firstAppearingOnce.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/55.entryNodeOfLoop.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/56.deleteDuplicationLinkNode.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/57.getNextNode.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/58.isSymmetrical.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/59.printTreewithZhizi.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/6.minNumberInRotateArray.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/60.printTreebyLayer.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/61.serializeAndSerialize.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/62.kthSmallNode.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/63.getMidim.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/64.maxInWindows.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/65.hasPath.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/66.movingCountRobot.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/7.outputFibonacci.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/8.jumpStep.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/9.jumpStepII.js (100%) rename NowCoder/{Leetcode => CodingInterviews}/findSumfromArray.js (100%) rename NowCoder/{CodingInterview => RealInterviewExamination}/MinimumReturnSubstring.js (100%) rename NowCoder/{CodingInterview => RealInterviewExamination}/checkIfLinkListPalindrome.js (100%) rename NowCoder/{CodingInterview => RealInterviewExamination}/commonPartOfTwoLinkList.js (94%) rename NowCoder/{CodingInterview => RealInterviewExamination}/findMaxEvenStrLength.js (100%) rename NowCoder/{CodingInterview => RealInterviewExamination}/findMaxLengthDNA.js (100%) rename NowCoder/{CodingInterview => RealInterviewExamination}/hanoiAdvanceProblems.js (100%) rename NowCoder/{CodingInterview => RealInterviewExamination}/reverseStackByRecursion.js (100%) rename NowCoder/{CodingInterview => RealInterviewExamination}/sortStackByStack.js (100%) diff --git a/NowCoder/Leetcode/1.checkDatainArray.js b/NowCoder/CodingInterviews/1.checkDatainArray.js similarity index 100% rename from NowCoder/Leetcode/1.checkDatainArray.js rename to NowCoder/CodingInterviews/1.checkDatainArray.js diff --git a/NowCoder/Leetcode/10.recCover.js b/NowCoder/CodingInterviews/10.recCover.js similarity index 100% rename from NowCoder/Leetcode/10.recCover.js rename to NowCoder/CodingInterviews/10.recCover.js diff --git a/NowCoder/Leetcode/11.numberOf1.js b/NowCoder/CodingInterviews/11.numberOf1.js similarity index 100% rename from NowCoder/Leetcode/11.numberOf1.js rename to NowCoder/CodingInterviews/11.numberOf1.js diff --git a/NowCoder/Leetcode/12.doublePower.js b/NowCoder/CodingInterviews/12.doublePower.js similarity index 100% rename from NowCoder/Leetcode/12.doublePower.js rename to NowCoder/CodingInterviews/12.doublePower.js diff --git a/NowCoder/Leetcode/13.reOrderArray.js b/NowCoder/CodingInterviews/13.reOrderArray.js similarity index 100% rename from NowCoder/Leetcode/13.reOrderArray.js rename to NowCoder/CodingInterviews/13.reOrderArray.js diff --git a/NowCoder/Leetcode/14.findKthToTail.js b/NowCoder/CodingInterviews/14.findKthToTail.js similarity index 100% rename from NowCoder/Leetcode/14.findKthToTail.js rename to NowCoder/CodingInterviews/14.findKthToTail.js diff --git a/NowCoder/Leetcode/15.ReverseList.js b/NowCoder/CodingInterviews/15.ReverseList.js similarity index 100% rename from NowCoder/Leetcode/15.ReverseList.js rename to NowCoder/CodingInterviews/15.ReverseList.js diff --git a/NowCoder/Leetcode/16.mergeTwosortedLink.js b/NowCoder/CodingInterviews/16.mergeTwosortedLink.js similarity index 100% rename from NowCoder/Leetcode/16.mergeTwosortedLink.js rename to NowCoder/CodingInterviews/16.mergeTwosortedLink.js diff --git a/NowCoder/Leetcode/17.hasSubtree.js b/NowCoder/CodingInterviews/17.hasSubtree.js similarity index 100% rename from NowCoder/Leetcode/17.hasSubtree.js rename to NowCoder/CodingInterviews/17.hasSubtree.js diff --git a/NowCoder/Leetcode/18.mirrorTree.js b/NowCoder/CodingInterviews/18.mirrorTree.js similarity index 100% rename from NowCoder/Leetcode/18.mirrorTree.js rename to NowCoder/CodingInterviews/18.mirrorTree.js diff --git a/NowCoder/Leetcode/19.printMatrixbyClockwise.js b/NowCoder/CodingInterviews/19.printMatrixbyClockwise.js similarity index 100% rename from NowCoder/Leetcode/19.printMatrixbyClockwise.js rename to NowCoder/CodingInterviews/19.printMatrixbyClockwise.js diff --git a/NowCoder/Leetcode/2.replaceSpaceinString.js b/NowCoder/CodingInterviews/2.replaceSpaceinString.js similarity index 100% rename from NowCoder/Leetcode/2.replaceSpaceinString.js rename to NowCoder/CodingInterviews/2.replaceSpaceinString.js diff --git a/NowCoder/Leetcode/20.createMinStackStructure.js b/NowCoder/CodingInterviews/20.createMinStackStructure.js similarity index 100% rename from NowCoder/Leetcode/20.createMinStackStructure.js rename to NowCoder/CodingInterviews/20.createMinStackStructure.js diff --git a/NowCoder/Leetcode/21.isPopOrder.js b/NowCoder/CodingInterviews/21.isPopOrder.js similarity index 100% rename from NowCoder/Leetcode/21.isPopOrder.js rename to NowCoder/CodingInterviews/21.isPopOrder.js diff --git a/NowCoder/Leetcode/22.printTreeFromTopToBottom.js b/NowCoder/CodingInterviews/22.printTreeFromTopToBottom.js similarity index 100% rename from NowCoder/Leetcode/22.printTreeFromTopToBottom.js rename to NowCoder/CodingInterviews/22.printTreeFromTopToBottom.js diff --git a/NowCoder/Leetcode/23.verifySquenceOfBST.js b/NowCoder/CodingInterviews/23.verifySquenceOfBST.js similarity index 100% rename from NowCoder/Leetcode/23.verifySquenceOfBST.js rename to NowCoder/CodingInterviews/23.verifySquenceOfBST.js diff --git a/NowCoder/Leetcode/24.findPathofBinary.js b/NowCoder/CodingInterviews/24.findPathofBinary.js similarity index 100% rename from NowCoder/Leetcode/24.findPathofBinary.js rename to NowCoder/CodingInterviews/24.findPathofBinary.js diff --git a/NowCoder/Leetcode/25.cloneComplexLinkList.js b/NowCoder/CodingInterviews/25.cloneComplexLinkList.js similarity index 100% rename from NowCoder/Leetcode/25.cloneComplexLinkList.js rename to NowCoder/CodingInterviews/25.cloneComplexLinkList.js diff --git a/NowCoder/Leetcode/26.convertBinaryTreetoDoubleLinkList.js b/NowCoder/CodingInterviews/26.convertBinaryTreetoDoubleLinkList.js similarity index 100% rename from NowCoder/Leetcode/26.convertBinaryTreetoDoubleLinkList.js rename to NowCoder/CodingInterviews/26.convertBinaryTreetoDoubleLinkList.js diff --git a/NowCoder/Leetcode/27.permutationString.js b/NowCoder/CodingInterviews/27.permutationString.js similarity index 100% rename from NowCoder/Leetcode/27.permutationString.js rename to NowCoder/CodingInterviews/27.permutationString.js diff --git a/NowCoder/Leetcode/28.moreThanHalfNum_Solution.js b/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js similarity index 100% rename from NowCoder/Leetcode/28.moreThanHalfNum_Solution.js rename to NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js diff --git a/NowCoder/Leetcode/29.getLeastNumbers_Solution.js b/NowCoder/CodingInterviews/29.getLeastNumbers_Solution.js similarity index 100% rename from NowCoder/Leetcode/29.getLeastNumbers_Solution.js rename to NowCoder/CodingInterviews/29.getLeastNumbers_Solution.js diff --git a/NowCoder/Leetcode/3.shiftListNode.js b/NowCoder/CodingInterviews/3.shiftListNode.js similarity index 100% rename from NowCoder/Leetcode/3.shiftListNode.js rename to NowCoder/CodingInterviews/3.shiftListNode.js diff --git a/NowCoder/Leetcode/30.findGreatestSumOfSubArray.js b/NowCoder/CodingInterviews/30.findGreatestSumOfSubArray.js similarity index 100% rename from NowCoder/Leetcode/30.findGreatestSumOfSubArray.js rename to NowCoder/CodingInterviews/30.findGreatestSumOfSubArray.js diff --git a/NowCoder/Leetcode/31.numberOf1Between1AndN_Solution.js b/NowCoder/CodingInterviews/31.numberOf1Between1AndN_Solution.js similarity index 100% rename from NowCoder/Leetcode/31.numberOf1Between1AndN_Solution.js rename to NowCoder/CodingInterviews/31.numberOf1Between1AndN_Solution.js diff --git a/NowCoder/Leetcode/32.PrintConnectMinNumberofArray.js b/NowCoder/CodingInterviews/32.PrintConnectMinNumberofArray.js similarity index 100% rename from NowCoder/Leetcode/32.PrintConnectMinNumberofArray.js rename to NowCoder/CodingInterviews/32.PrintConnectMinNumberofArray.js diff --git a/NowCoder/Leetcode/33.getUglyNumber_Solution.js b/NowCoder/CodingInterviews/33.getUglyNumber_Solution.js similarity index 100% rename from NowCoder/Leetcode/33.getUglyNumber_Solution.js rename to NowCoder/CodingInterviews/33.getUglyNumber_Solution.js diff --git a/NowCoder/Leetcode/34.firstNotRepeatingChar.js b/NowCoder/CodingInterviews/34.firstNotRepeatingChar.js similarity index 100% rename from NowCoder/Leetcode/34.firstNotRepeatingChar.js rename to NowCoder/CodingInterviews/34.firstNotRepeatingChar.js diff --git a/NowCoder/Leetcode/35.inversePairsNum.js b/NowCoder/CodingInterviews/35.inversePairsNum.js similarity index 100% rename from NowCoder/Leetcode/35.inversePairsNum.js rename to NowCoder/CodingInterviews/35.inversePairsNum.js diff --git a/NowCoder/Leetcode/36.findFirstCommonNodeofLinkNode.js b/NowCoder/CodingInterviews/36.findFirstCommonNodeofLinkNode.js similarity index 100% rename from NowCoder/Leetcode/36.findFirstCommonNodeofLinkNode.js rename to NowCoder/CodingInterviews/36.findFirstCommonNodeofLinkNode.js diff --git a/NowCoder/Leetcode/37.getNumberOfK.js b/NowCoder/CodingInterviews/37.getNumberOfK.js similarity index 100% rename from NowCoder/Leetcode/37.getNumberOfK.js rename to NowCoder/CodingInterviews/37.getNumberOfK.js diff --git a/NowCoder/Leetcode/38.treeDepth.js b/NowCoder/CodingInterviews/38.treeDepth.js similarity index 100% rename from NowCoder/Leetcode/38.treeDepth.js rename to NowCoder/CodingInterviews/38.treeDepth.js diff --git a/NowCoder/Leetcode/39.isBalancedTree.js b/NowCoder/CodingInterviews/39.isBalancedTree.js similarity index 100% rename from NowCoder/Leetcode/39.isBalancedTree.js rename to NowCoder/CodingInterviews/39.isBalancedTree.js diff --git a/NowCoder/Leetcode/4.reConstructBinaryTree.js b/NowCoder/CodingInterviews/4.reConstructBinaryTree.js similarity index 100% rename from NowCoder/Leetcode/4.reConstructBinaryTree.js rename to NowCoder/CodingInterviews/4.reConstructBinaryTree.js diff --git a/NowCoder/Leetcode/40.findNumsAppearOnce.js b/NowCoder/CodingInterviews/40.findNumsAppearOnce.js similarity index 100% rename from NowCoder/Leetcode/40.findNumsAppearOnce.js rename to NowCoder/CodingInterviews/40.findNumsAppearOnce.js diff --git a/NowCoder/Leetcode/41.findContinuousSequence.js b/NowCoder/CodingInterviews/41.findContinuousSequence.js similarity index 100% rename from NowCoder/Leetcode/41.findContinuousSequence.js rename to NowCoder/CodingInterviews/41.findContinuousSequence.js diff --git a/NowCoder/Leetcode/42.findNumbersWithSum.js b/NowCoder/CodingInterviews/42.findNumbersWithSum.js similarity index 100% rename from NowCoder/Leetcode/42.findNumbersWithSum.js rename to NowCoder/CodingInterviews/42.findNumbersWithSum.js diff --git a/NowCoder/Leetcode/43.loopLeftRotateStr.js b/NowCoder/CodingInterviews/43.loopLeftRotateStr.js similarity index 100% rename from NowCoder/Leetcode/43.loopLeftRotateStr.js rename to NowCoder/CodingInterviews/43.loopLeftRotateStr.js diff --git a/NowCoder/Leetcode/44.reverseWords.js b/NowCoder/CodingInterviews/44.reverseWords.js similarity index 100% rename from NowCoder/Leetcode/44.reverseWords.js rename to NowCoder/CodingInterviews/44.reverseWords.js diff --git a/NowCoder/Leetcode/45.isContinuous.js b/NowCoder/CodingInterviews/45.isContinuous.js similarity index 100% rename from NowCoder/Leetcode/45.isContinuous.js rename to NowCoder/CodingInterviews/45.isContinuous.js diff --git a/NowCoder/Leetcode/46.lastRemaining_Solution.js b/NowCoder/CodingInterviews/46.lastRemaining_Solution.js similarity index 100% rename from NowCoder/Leetcode/46.lastRemaining_Solution.js rename to NowCoder/CodingInterviews/46.lastRemaining_Solution.js diff --git a/NowCoder/Leetcode/47.sum_Solution.js b/NowCoder/CodingInterviews/47.sum_Solution.js similarity index 100% rename from NowCoder/Leetcode/47.sum_Solution.js rename to NowCoder/CodingInterviews/47.sum_Solution.js diff --git a/NowCoder/Leetcode/48.addTwoNum.js b/NowCoder/CodingInterviews/48.addTwoNum.js similarity index 100% rename from NowCoder/Leetcode/48.addTwoNum.js rename to NowCoder/CodingInterviews/48.addTwoNum.js diff --git a/NowCoder/Leetcode/49.strToInt.js b/NowCoder/CodingInterviews/49.strToInt.js similarity index 100% rename from NowCoder/Leetcode/49.strToInt.js rename to NowCoder/CodingInterviews/49.strToInt.js diff --git a/NowCoder/Leetcode/5.useTwoStackCreatQueue.js b/NowCoder/CodingInterviews/5.useTwoStackCreatQueue.js similarity index 100% rename from NowCoder/Leetcode/5.useTwoStackCreatQueue.js rename to NowCoder/CodingInterviews/5.useTwoStackCreatQueue.js diff --git a/NowCoder/Leetcode/50.duplicate.js b/NowCoder/CodingInterviews/50.duplicate.js similarity index 100% rename from NowCoder/Leetcode/50.duplicate.js rename to NowCoder/CodingInterviews/50.duplicate.js diff --git a/NowCoder/Leetcode/51.multiply.js b/NowCoder/CodingInterviews/51.multiply.js similarity index 100% rename from NowCoder/Leetcode/51.multiply.js rename to NowCoder/CodingInterviews/51.multiply.js diff --git a/NowCoder/Leetcode/52.matchParren.js b/NowCoder/CodingInterviews/52.matchParren.js similarity index 100% rename from NowCoder/Leetcode/52.matchParren.js rename to NowCoder/CodingInterviews/52.matchParren.js diff --git a/NowCoder/Leetcode/53.isNumeric.js b/NowCoder/CodingInterviews/53.isNumeric.js similarity index 100% rename from NowCoder/Leetcode/53.isNumeric.js rename to NowCoder/CodingInterviews/53.isNumeric.js diff --git a/NowCoder/Leetcode/54.firstAppearingOnce.js b/NowCoder/CodingInterviews/54.firstAppearingOnce.js similarity index 100% rename from NowCoder/Leetcode/54.firstAppearingOnce.js rename to NowCoder/CodingInterviews/54.firstAppearingOnce.js diff --git a/NowCoder/Leetcode/55.entryNodeOfLoop.js b/NowCoder/CodingInterviews/55.entryNodeOfLoop.js similarity index 100% rename from NowCoder/Leetcode/55.entryNodeOfLoop.js rename to NowCoder/CodingInterviews/55.entryNodeOfLoop.js diff --git a/NowCoder/Leetcode/56.deleteDuplicationLinkNode.js b/NowCoder/CodingInterviews/56.deleteDuplicationLinkNode.js similarity index 100% rename from NowCoder/Leetcode/56.deleteDuplicationLinkNode.js rename to NowCoder/CodingInterviews/56.deleteDuplicationLinkNode.js diff --git a/NowCoder/Leetcode/57.getNextNode.js b/NowCoder/CodingInterviews/57.getNextNode.js similarity index 100% rename from NowCoder/Leetcode/57.getNextNode.js rename to NowCoder/CodingInterviews/57.getNextNode.js diff --git a/NowCoder/Leetcode/58.isSymmetrical.js b/NowCoder/CodingInterviews/58.isSymmetrical.js similarity index 100% rename from NowCoder/Leetcode/58.isSymmetrical.js rename to NowCoder/CodingInterviews/58.isSymmetrical.js diff --git a/NowCoder/Leetcode/59.printTreewithZhizi.js b/NowCoder/CodingInterviews/59.printTreewithZhizi.js similarity index 100% rename from NowCoder/Leetcode/59.printTreewithZhizi.js rename to NowCoder/CodingInterviews/59.printTreewithZhizi.js diff --git a/NowCoder/Leetcode/6.minNumberInRotateArray.js b/NowCoder/CodingInterviews/6.minNumberInRotateArray.js similarity index 100% rename from NowCoder/Leetcode/6.minNumberInRotateArray.js rename to NowCoder/CodingInterviews/6.minNumberInRotateArray.js diff --git a/NowCoder/Leetcode/60.printTreebyLayer.js b/NowCoder/CodingInterviews/60.printTreebyLayer.js similarity index 100% rename from NowCoder/Leetcode/60.printTreebyLayer.js rename to NowCoder/CodingInterviews/60.printTreebyLayer.js diff --git a/NowCoder/Leetcode/61.serializeAndSerialize.js b/NowCoder/CodingInterviews/61.serializeAndSerialize.js similarity index 100% rename from NowCoder/Leetcode/61.serializeAndSerialize.js rename to NowCoder/CodingInterviews/61.serializeAndSerialize.js diff --git a/NowCoder/Leetcode/62.kthSmallNode.js b/NowCoder/CodingInterviews/62.kthSmallNode.js similarity index 100% rename from NowCoder/Leetcode/62.kthSmallNode.js rename to NowCoder/CodingInterviews/62.kthSmallNode.js diff --git a/NowCoder/Leetcode/63.getMidim.js b/NowCoder/CodingInterviews/63.getMidim.js similarity index 100% rename from NowCoder/Leetcode/63.getMidim.js rename to NowCoder/CodingInterviews/63.getMidim.js diff --git a/NowCoder/Leetcode/64.maxInWindows.js b/NowCoder/CodingInterviews/64.maxInWindows.js similarity index 100% rename from NowCoder/Leetcode/64.maxInWindows.js rename to NowCoder/CodingInterviews/64.maxInWindows.js diff --git a/NowCoder/Leetcode/65.hasPath.js b/NowCoder/CodingInterviews/65.hasPath.js similarity index 100% rename from NowCoder/Leetcode/65.hasPath.js rename to NowCoder/CodingInterviews/65.hasPath.js diff --git a/NowCoder/Leetcode/66.movingCountRobot.js b/NowCoder/CodingInterviews/66.movingCountRobot.js similarity index 100% rename from NowCoder/Leetcode/66.movingCountRobot.js rename to NowCoder/CodingInterviews/66.movingCountRobot.js diff --git a/NowCoder/Leetcode/7.outputFibonacci.js b/NowCoder/CodingInterviews/7.outputFibonacci.js similarity index 100% rename from NowCoder/Leetcode/7.outputFibonacci.js rename to NowCoder/CodingInterviews/7.outputFibonacci.js diff --git a/NowCoder/Leetcode/8.jumpStep.js b/NowCoder/CodingInterviews/8.jumpStep.js similarity index 100% rename from NowCoder/Leetcode/8.jumpStep.js rename to NowCoder/CodingInterviews/8.jumpStep.js diff --git a/NowCoder/Leetcode/9.jumpStepII.js b/NowCoder/CodingInterviews/9.jumpStepII.js similarity index 100% rename from NowCoder/Leetcode/9.jumpStepII.js rename to NowCoder/CodingInterviews/9.jumpStepII.js diff --git a/NowCoder/Leetcode/findSumfromArray.js b/NowCoder/CodingInterviews/findSumfromArray.js similarity index 100% rename from NowCoder/Leetcode/findSumfromArray.js rename to NowCoder/CodingInterviews/findSumfromArray.js diff --git a/NowCoder/CodingInterview/MinimumReturnSubstring.js b/NowCoder/RealInterviewExamination/MinimumReturnSubstring.js similarity index 100% rename from NowCoder/CodingInterview/MinimumReturnSubstring.js rename to NowCoder/RealInterviewExamination/MinimumReturnSubstring.js diff --git a/NowCoder/CodingInterview/checkIfLinkListPalindrome.js b/NowCoder/RealInterviewExamination/checkIfLinkListPalindrome.js similarity index 100% rename from NowCoder/CodingInterview/checkIfLinkListPalindrome.js rename to NowCoder/RealInterviewExamination/checkIfLinkListPalindrome.js diff --git a/NowCoder/CodingInterview/commonPartOfTwoLinkList.js b/NowCoder/RealInterviewExamination/commonPartOfTwoLinkList.js similarity index 94% rename from NowCoder/CodingInterview/commonPartOfTwoLinkList.js rename to NowCoder/RealInterviewExamination/commonPartOfTwoLinkList.js index b93b1fc..7fef710 100644 --- a/NowCoder/CodingInterview/commonPartOfTwoLinkList.js +++ b/NowCoder/RealInterviewExamination/commonPartOfTwoLinkList.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-05-13 09:26:26 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-05-13 09:32:46 + * @Last Modified time: 2019-07-12 15:29:01 */ diff --git a/NowCoder/CodingInterview/findMaxEvenStrLength.js b/NowCoder/RealInterviewExamination/findMaxEvenStrLength.js similarity index 100% rename from NowCoder/CodingInterview/findMaxEvenStrLength.js rename to NowCoder/RealInterviewExamination/findMaxEvenStrLength.js diff --git a/NowCoder/CodingInterview/findMaxLengthDNA.js b/NowCoder/RealInterviewExamination/findMaxLengthDNA.js similarity index 100% rename from NowCoder/CodingInterview/findMaxLengthDNA.js rename to NowCoder/RealInterviewExamination/findMaxLengthDNA.js diff --git a/NowCoder/CodingInterview/hanoiAdvanceProblems.js b/NowCoder/RealInterviewExamination/hanoiAdvanceProblems.js similarity index 100% rename from NowCoder/CodingInterview/hanoiAdvanceProblems.js rename to NowCoder/RealInterviewExamination/hanoiAdvanceProblems.js diff --git a/NowCoder/CodingInterview/reverseStackByRecursion.js b/NowCoder/RealInterviewExamination/reverseStackByRecursion.js similarity index 100% rename from NowCoder/CodingInterview/reverseStackByRecursion.js rename to NowCoder/RealInterviewExamination/reverseStackByRecursion.js diff --git a/NowCoder/CodingInterview/sortStackByStack.js b/NowCoder/RealInterviewExamination/sortStackByStack.js similarity index 100% rename from NowCoder/CodingInterview/sortStackByStack.js rename to NowCoder/RealInterviewExamination/sortStackByStack.js From e8fd95e6270ccc17906a2409172a68a11a99de1a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 14 Jul 2019 21:01:56 +0800 Subject: [PATCH 226/274] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E5=9B=9E=E6=96=87=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SortAlgorithmsbyJavaScript/MergeSort.js | 2 +- .../SortAlgorithmsbyJavaScript/sortTesting.js | 48 ++++++++++++++++++- Leetcode/7.reverseInteger.js | 22 ++++++++- 3 files changed, 67 insertions(+), 5 deletions(-) diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js index 8856a0f..c0e8ceb 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js @@ -25,7 +25,7 @@ function sortProgress(arrays, Ln, Rn) { sortProgress(arrays, midn + 1, Rn); merge(arrays, Ln, midn, Rn); console.log(arrays); -} +}. function merge(arrays, Ln, midn, Rn) { let temparrays = new Array(); diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js index 4a84eec..875de68 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-06-03 20:33:20 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-06-03 20:34:31 + * @Last Modified time: 2019-07-14 14:18:02 */ @@ -17,4 +17,48 @@ const HeapSort = require('./HeapSort'); let arrOne = [38,65,97,76,13,27,10]; -BubbleSort(arrOne); \ No newline at end of file +BubbleSort(arrOne); + + + +function quickSort(arr){ + if(arr === null || arr.length < 2){ + return arr; + } + + return quickSortProcess(arr, 0, arr.length-1); +} + +function quickSortProcess(arr, Ln, Rn){ + if(Ln < Rn){ + swap(arr, Ln+parseInt(Math.random()*(Rn-Ln+1)),Rn); + let p = partition(arr, Ln, Rn); + quickSortProcess(arr, Ln, p[0]-1); + quickSortProcess(arr, p[1]+1, Rn); + } +} + +function swap(arr, i,j){ + let tempData = arr[i]; + arr[i] = arr[j]; + arr[j] = tempData; +} + +// 对传入的每一部分进行分区域,并返回中间等于R的边界范围 +function partition(arr, L, R){ + let less = L-1; + let more = R; + while(L < more){ + if(arr[L] < arr[R]){ + swap(arr, ++less, L++); + }else if(arr[L]>arr[R]){ + swap(arr,--more,L); + } else { + L++; + } + } + swap(arr, more, R); + return [less+1, more]; + +} + diff --git a/Leetcode/7.reverseInteger.js b/Leetcode/7.reverseInteger.js index 37cca64..d5270e8 100644 --- a/Leetcode/7.reverseInteger.js +++ b/Leetcode/7.reverseInteger.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-05-23 16:27:45 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-05-23 16:47:40 + * @Last Modified time: 2019-07-14 20:57:03 */ /***** @@ -77,4 +77,22 @@ var reverse2 = function (x) { backNum = signLabel ? backNum : -backNum; return backNum; -}; \ No newline at end of file +}; + + + +const reduceMap = (fn, thisArg /*真想去掉thisArg这个参数*/ ) => { + return (list) => { + // 不怎么愿意写下面这两个判断条件 + if (typeof fn !== 'function') { + throw new TypeError(fn + 'is not a function') + } + if (!Array.isArray(list)) { + throw new TypeError('list must be a Array') + } + if (list.length === 0) return [] + return list.reduce((acc, value, index) => { + return acc.concat([ fn.call(thisArg, value, index, list) ]) + }, []) + } +} From 71452c57ee435bee52b655fb96de9755d38b5f33 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 15 Jul 2019 20:25:26 +0800 Subject: [PATCH 227/274] =?UTF-8?q?=E7=9C=9F=E4=BA=BA=E9=9D=A2=E8=AF=95?= =?UTF-8?q?=E9=A2=98=EF=BC=8C=E6=95=B0=E5=AD=97=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E6=9C=80=E5=A4=A7=E5=9B=9E=E6=96=87=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RealInterviewExamination/maxTractNum.js | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 NowCoder/RealInterviewExamination/maxTractNum.js diff --git a/NowCoder/RealInterviewExamination/maxTractNum.js b/NowCoder/RealInterviewExamination/maxTractNum.js new file mode 100644 index 0000000..66017f7 --- /dev/null +++ b/NowCoder/RealInterviewExamination/maxTractNum.js @@ -0,0 +1,41 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-14 20:58:36 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-14 21:01:02 + */ + + +/**** + * + * 输入数字字符串,求最大回文数 + * + * + * + */ + +function maxTractNum(str){ + let max = 0; + if(!str || str.length<=1){ + return Math.max(max,parseInt(str)) + } + this.dfs = function(str,i,j){ + let tempData = str.slice(i,j); + if(tempData === tempData.split('').reverse().join('')){ + if(parseInt(tempData)> max){ + max = parseInt(tempData); + } + } + if(j Date: Mon, 15 Jul 2019 20:40:34 +0800 Subject: [PATCH 228/274] =?UTF-8?q?=E5=AD=97=E8=8A=82=E8=B7=B3=E5=8A=A8?= =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=98=E6=B1=82=E6=9C=80=E5=A4=A7=E7=9A=84?= =?UTF-8?q?=E5=B9=82=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../otherExams/powerMax.js | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 NowCoder/RealInterviewExamination/otherExams/powerMax.js diff --git a/NowCoder/RealInterviewExamination/otherExams/powerMax.js b/NowCoder/RealInterviewExamination/otherExams/powerMax.js new file mode 100644 index 0000000..9e39870 --- /dev/null +++ b/NowCoder/RealInterviewExamination/otherExams/powerMax.js @@ -0,0 +1,48 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-15 19:47:23 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-15 20:24:34 + */ + + +/**** + * n = xi^yi + * 64 = 64^1=8^2=4^3=2^6 + * f(n) = max(yi) + * + * f(64)=max(1,2,3,6)=6 + * + * 给定区间 M,N + * 定义 g(M,N) = max(f(i)) + * M<=i<=N + * + * g(63,65)=6 + * g(61,63)=1 + * + * 字节跳动面试题 + * + */ + + +function maxPower(numM,numN){ + if(numM > numN){ + return 0; + } + let maxData = 1; + for (let i = numM; i <= numN; i++) { + for (let j = 63; j >=0; j--) { + if(Math.pow(i, 1/j) % 1 === 0){ + // JavaScript 中判断一个数是否是整数,可以对 1 进行取余。如果余数为0 则此数为整数 + if(j > maxData){ + maxData = j; + } + } + } + } + return maxData; +} + +let numM = 26; +let numN = 28; +console.log(maxPower(numM,numN)); \ No newline at end of file From 922a1b57c8617b2d31f435a3e3247857b9833969 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 18 Jul 2019 15:16:35 +0800 Subject: [PATCH 229/274] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E6=AD=A3=E5=88=99?= =?UTF-8?q?=E8=A1=A8=E8=BE=BE=E5=BC=8F=E5=A4=84=E7=90=86=E5=B8=B8=E8=A7=81?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handleProblemsbyRegExp.js | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 NowCoder/JavaScriptAbility/handleProblemsbyRegExp.js diff --git a/NowCoder/JavaScriptAbility/handleProblemsbyRegExp.js b/NowCoder/JavaScriptAbility/handleProblemsbyRegExp.js new file mode 100644 index 0000000..eeed794 --- /dev/null +++ b/NowCoder/JavaScriptAbility/handleProblemsbyRegExp.js @@ -0,0 +1,105 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-18 14:33:45 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-18 15:15:43 + */ + +/**** + * + * + * + * 给定字符串 str,检查其是否以元音字母结尾 + * + */ +function endsWithVowel(str) { + return str.search(/[aeiou]$/i)===-1?false:true; +} + +function endsWithVowel2(str) { + return (/[aeiou]$/i).test(str); +} + + + +/**** + * + * + * 给定字符串 str,检查其是否包含连续重复的字母(a-zA-Z),包含返回 true,否则返回 false + * + */ + +// \1 表示引用,引用括号中第一次出现的字符 +function containsRepeatingLetter(str) { + var ser = /([a-zA-Z])\1/gi; + return str.search(ser)===-1?false:true; +} + +function containsRepeatingLetter2(str) { + return (/([a-zA-Z])\1/gi).test(str); +} + + +/** + * + * + * 给定字符串 str,检查其是否包含 连续3个数字 + * 1、如果包含,返回最新出现的 3 个数字的字符串 + * 2、如果不包含,返回 false + * + * + * +*/ +function captureThreeNumbers(str) { + var ifHad = str.search(/[0-9]{3}/g); + if(ifHad !== -1){ + return str.slice(ifHad,ifHad+3); + }else { + return false + } +} + +function captureThreeNumbers2(str) { + var res = str.match(/\d{3}/g); + return res? res[0]:false; +} + + +/***** + * + * + * 给定字符串 str,检查其是否符合如下格式 + * 1、XXX-XXX-XXXX + * 2、其中 X 为 Number 类型 + * + */ + +function matchesPattern(str) { + return (/^\d{3}-\d{3}-\d{4}$/).test(str); +} + + +/*** + * + * 给定字符串 str,检查其是否符合美元书写格式 + * 1、以 $ 开始 + * 2、整数部分,从个位起,满 3 个数字用 , 分隔 + * 3、如果为小数,则小数部分长度为 2 + * 4、正确的格式如:$1,023,032.03 或者 $2.03, + * 5、错误的格式如:$3,432,12.12 或者 $34,344.3 + * + * +*/ + +function isUSD(str) { + return (/^\$\d{1,3}(,\d{3})*(\.\d{2})?$/g).test(str); +} + + + + + +// ! 正则表达式方法总结 +// test() 方法 是 正则表达式作为主体 RegExp.test(string) 匹配返回 true 不匹配返回 false +// search() 方法 是 字符串作为主体 String.search(RegExp) 匹配 返回 初始字符的位置,不匹配 返回 -1 +// match() 方法 是 字符串作为主体 String.match(RegExp) 匹配 则返回一个有内容的数组(首项为全局匹配内容,余下的而是子表达式的匹配内容) 不匹配则返回 null \ No newline at end of file From 297c26258fa5d43a26e2102f0224ddab8c81f091 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 18 Jul 2019 15:27:45 +0800 Subject: [PATCH 230/274] =?UTF-8?q?=E9=81=97=E7=95=99=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E4=BB=A3=E7=A0=81--=E6=A0=87=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2018Enterprise/changeTheChar-byteDance.js | 28 +++++++++++++ .../2018Enterprise/eventExample.-yongyou.js | 13 ++++-- NowCoder/2019/byteDance/test.js | 40 +++++++++++++++++++ .../executionEnvironmentContext.js | 11 +++++ NowCoder/JavaScriptAbility/returnFunction.js | 15 +++++++ 5 files changed, 104 insertions(+), 3 deletions(-) create mode 100644 NowCoder/2018Enterprise/changeTheChar-byteDance.js create mode 100644 NowCoder/2019/byteDance/test.js create mode 100644 NowCoder/JavaScriptAbility/executionEnvironmentContext.js create mode 100644 NowCoder/JavaScriptAbility/returnFunction.js diff --git a/NowCoder/2018Enterprise/changeTheChar-byteDance.js b/NowCoder/2018Enterprise/changeTheChar-byteDance.js new file mode 100644 index 0000000..cc8bc51 --- /dev/null +++ b/NowCoder/2018Enterprise/changeTheChar-byteDance.js @@ -0,0 +1,28 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-25 08:46:35 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-25 08:47:41 + */ + +/**** + * + * 字母交换m次,最多连续字母数量 + * + * + */ + +function maxContinueChar(str, m){ + +} + + + + + + +let dataList = readline().split(' '); +let str = dataList[0]; +let m = parseInt(dataList[1]); + +print(maxContinueChar(str, m)); \ No newline at end of file diff --git a/NowCoder/2018Enterprise/eventExample.-yongyou.js b/NowCoder/2018Enterprise/eventExample.-yongyou.js index 5946793..923a4cf 100644 --- a/NowCoder/2018Enterprise/eventExample.-yongyou.js +++ b/NowCoder/2018Enterprise/eventExample.-yongyou.js @@ -19,9 +19,16 @@ btn.onclick = function (){ } let EventEmitter = { - - on(){ + on(e){ let btn = document.getElementById('buttom'); - + btn.addEventListener(e,function(){ + console.log(this.id); + },true); + }, + trigger(e){ + let btn = document.getElementById('buttom'); + btn.dispatchEvent(e,function(){ + console.log(this.id); + },true); } } \ No newline at end of file diff --git a/NowCoder/2019/byteDance/test.js b/NowCoder/2019/byteDance/test.js new file mode 100644 index 0000000..20808a5 --- /dev/null +++ b/NowCoder/2019/byteDance/test.js @@ -0,0 +1,40 @@ +function maxHeightofList(data){ + let maxHeight = 0; + if(!data || data.length === 0){ + return maxHeight; + } + let len = data.length; + let copyArr = data.slice(0); + copyArr.sort((a,b)=>a-b); + let maxMid = Math.abs(copyArr[data.length-1]-copyArr[0]); + maxHeight = maxMid; + let states = []; + + this.dfs = function(N,total, num, data){ + if(total === len){ + if(Math.abs(data[num]-data[0])<=N){ + if(N Date: Thu, 18 Jul 2019 15:35:16 +0800 Subject: [PATCH 231/274] =?UTF-8?q?=E6=B8=85=E7=90=86=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js index c0e8ceb..8856a0f 100644 --- a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js @@ -25,7 +25,7 @@ function sortProgress(arrays, Ln, Rn) { sortProgress(arrays, midn + 1, Rn); merge(arrays, Ln, midn, Rn); console.log(arrays); -}. +} function merge(arrays, Ln, midn, Rn) { let temparrays = new Array(); From f40e7a8ed567453fbf84a36cfe47a2ec70c3390d Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 18 Jul 2019 22:46:03 +0800 Subject: [PATCH 232/274] =?UTF-8?q?leetcode=20=E9=83=A8=E5=88=86=E9=A2=98?= =?UTF-8?q?=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/27.RemoveElement.js | 37 ++++++++++++++++++ Leetcode/28.ImplementstrStr.js | 50 ++++++++++++++++++++++++ Leetcode/459.RepeatedSubstringPattern.js | 31 +++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 Leetcode/27.RemoveElement.js create mode 100644 Leetcode/28.ImplementstrStr.js create mode 100644 Leetcode/459.RepeatedSubstringPattern.js diff --git a/Leetcode/27.RemoveElement.js b/Leetcode/27.RemoveElement.js new file mode 100644 index 0000000..1c4bd9a --- /dev/null +++ b/Leetcode/27.RemoveElement.js @@ -0,0 +1,37 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-18 22:06:03 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-18 22:10:48 + */ + +/**** + * + * + * 额外空间复杂度为1的方法去除数组中值为 val 的项,返回新数组的长度 len + * 并且可以保证数组前 len 项是理想值 + * + */ + +var removeElement = function(nums, val) { + let len = 0; + nums.map((value,index)=>{ + if(value !== val){ + nums[len++] = value; + } + }) + return len; +}; + +// 改进版方法 +// 发现一个 问题 使用 var 会比 let 更快 +// 思路,从后往前,相等就删掉,索引也不会影响 +var removeElement2 = function(nums, val) { + for(var i=nums.length-1;i>=0;i--){ + if(nums[i]===val){ + nums.splice(i,1); + } + } + return nums.length; +}; + diff --git a/Leetcode/28.ImplementstrStr.js b/Leetcode/28.ImplementstrStr.js new file mode 100644 index 0000000..d56d192 --- /dev/null +++ b/Leetcode/28.ImplementstrStr.js @@ -0,0 +1,50 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-18 22:14:45 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-18 22:35:19 + */ + + +/***** + * + * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. + * + * + */ + +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function(haystack, needle) { + var reg = new RegExp(needle); + return haystack.search(reg); + // return haystack.indexof(needle); +}; + + +/**** + * + * 普通但是优化的解法 + * + */ + +var strStr2 = function(haystack, needle) { + if(!needle.length){ + return 0; + } + + if(haystack.length === needle.length && haystack !== needle){ + return -1; + } + + for (let i = 0; i < haystack.length; i++) { + let copy = haystack.slice(i, needle.length+i); + if(copy === needle){ + return i; + } + } + return -1; +} \ No newline at end of file diff --git a/Leetcode/459.RepeatedSubstringPattern.js b/Leetcode/459.RepeatedSubstringPattern.js new file mode 100644 index 0000000..061cfe5 --- /dev/null +++ b/Leetcode/459.RepeatedSubstringPattern.js @@ -0,0 +1,31 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-18 22:35:38 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-18 22:45:32 + */ + + +/****** + * + * Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. + * You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. + * + * + */ + +/** + * @param {string} s + * @return {boolean} + */ +var repeatedSubstringPattern = function(s) { + return (/^(\w+)\1+$/g).test(s); +}; + + +var repeatedSubstringPattern2 = function(s) { + var str = s+s; + return str.slice(1, str.length-1).includes(s); +}; + + From 5a3b9ca7910a5ff4bf31aea111355c213186a3b8 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 19 Jul 2019 10:14:11 +0800 Subject: [PATCH 233/274] =?UTF-8?q?=E6=95=B0=E5=AD=97=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E7=9A=84=E4=B9=9D=E5=AE=AB=E6=A0=BC=E5=AD=97=E6=AF=8D?= =?UTF-8?q?=E7=BB=84=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../17.LetterCombinationsofaPhoneNumber.js | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Leetcode/17.LetterCombinationsofaPhoneNumber.js diff --git a/Leetcode/17.LetterCombinationsofaPhoneNumber.js b/Leetcode/17.LetterCombinationsofaPhoneNumber.js new file mode 100644 index 0000000..e91dd53 --- /dev/null +++ b/Leetcode/17.LetterCombinationsofaPhoneNumber.js @@ -0,0 +1,98 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-19 09:32:56 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-19 10:12:35 + */ + + +/**** + * + * 九宫格手机键盘,将数字字符串转换成可能出现的字符串组合 + * + * input: '23' + * output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. + * + */ + +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function(digits) { + var wordMap = { + "2": ['a','b','c'], + "3": ['d','e','f'], + "4": ['g','h','i'], + "5": ['j','k','l'], + "6": ['m','n','o'], + "7": ['p','q','r','s'], + "8": ['t','u','v'], + "9": ['w','x','y','z'] + } + var ouside = []; + if(!digits || digits.length === 0){ + return ouside; + } + var initStr = digits; + // 采用回溯的思想解题,类似遍历的解法 + this.backtrack = function(str, tempDigits){ + if(tempDigits.length === 0){ + ouside.push(str); + }else { + var tempDigit = tempDigits.substring(0,1); + var tempArr = wordMap[tempDigit]; + for(var i=0;i Date: Sat, 20 Jul 2019 22:01:15 +0800 Subject: [PATCH 234/274] =?UTF-8?q?=E6=89=BE=E5=87=BA=E5=92=8C=E4=B8=8E?= =?UTF-8?q?=E7=9B=AE=E6=A0=87=E5=80=BC=E6=9C=80=E8=BF=91=E7=9A=84=E4=B8=89?= =?UTF-8?q?=E4=B8=AA=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LeetCode 16 && 15 --- Leetcode/15.3sum.js | 33 ++++++++++++++++++++-- Leetcode/16.3SumClosest.js | 56 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 Leetcode/16.3SumClosest.js diff --git a/Leetcode/15.3sum.js b/Leetcode/15.3sum.js index f784322..3129cc2 100644 --- a/Leetcode/15.3sum.js +++ b/Leetcode/15.3sum.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-05-25 15:53:51 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-05-25 16:20:12 + * @Last Modified time: 2019-07-20 21:59:21 */ @@ -69,4 +69,33 @@ let threeSum = function (nums) { }; let nums = [-1, 0, 1, 2, -1, -4]; -console.log(threeSum(nums)); \ No newline at end of file +console.log(threeSum(nums)); + +// best answer + +let threeSum2 = function (nums) { + let output = []; + nums.sort((a,b) => a-b); + for (let i = 0; i < nums.length; i++) { + if (i!==0 && nums[i] === nums[i-1]) { + continue; + } + let j = i+1; + let k = nums.length - 1; + while(j < k){ + let tempSum = nums[i] + nums[j] + nums[k]; + if(tempSum === 0){ + output.push([nums[i], nums[j], nums[k]]); + j++; + while(j a-b); + let minDec = Number.MAX_VALUE; + for(let i=0;i Date: Sat, 20 Jul 2019 22:25:22 +0800 Subject: [PATCH 235/274] =?UTF-8?q?=E6=8B=9B=E5=95=86=E9=93=B6=E8=A1=8C201?= =?UTF-8?q?9=E7=AC=94=E8=AF=95=E7=9C=9F=E9=A2=98--=E5=88=86=E7=B3=96?= =?UTF-8?q?=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2018Enterprise/departCandys.js | 62 +++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 NowCoder/2018Enterprise/departCandys.js diff --git a/NowCoder/2018Enterprise/departCandys.js b/NowCoder/2018Enterprise/departCandys.js new file mode 100644 index 0000000..9aa2be3 --- /dev/null +++ b/NowCoder/2018Enterprise/departCandys.js @@ -0,0 +1,62 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-20 22:23:04 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-20 22:25:16 + */ + + +/***** + * + * 招商银行2019笔试真题--分糖果 + * + * 假设你是一位很有爱的幼儿园老师,想要给幼儿园的小朋友们一些小糖果。 + * 但是,每个孩子最多只能给一块糖果。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的糖果的最小尺寸; + * 并且每块糖果 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个糖果 j 分配给孩子 i ,这个孩子会得到满足。 + * 你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 + * 注意:你可以假设胃口值为正。一个小朋友最多只能拥有一块糖果。 + * + * + * 输入: + * 第一行输入每个孩子的胃口值 + * 第二行输入每个糖果的尺寸 + * 孩子数和糖果数不超过1000 + * + * 输出: + * 能满足孩子数量的最大值 + * + */ + +function maxNumofKids(kids,candys){ + let output = 0; + kids.sort((a,b)=> a-b); + candys.sort((a,b)=> a-b); + let k=0; + for(let i=0;i=kids[k]){ + k++; + output++; + if(k===kids.length){ + break; + } + } + } + return output; +} + + + + +let data1 = readline().split(' '); +let kids = []; +for(let i=0; i< data1.length;i++){ + kids.push(parseInt(data1[i])); +} + +let data2 = readline().split(' '); +let candys = []; +for(let j=0; j< data2.length;j++){ + candys.push(parseInt(data2[j])); +} + +print(maxNumofKids(kids,candys)) \ No newline at end of file From d3132aef7da8bf117c62abf0feb4593e69f254e0 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 21 Jul 2019 11:17:27 +0800 Subject: [PATCH 236/274] =?UTF-8?q?=E6=89=BE=E5=88=B0=E6=89=80=E6=9C=89?= =?UTF-8?q?=E5=9B=9B=E6=95=B0=E7=9B=B8=E5=8A=A0=E7=AD=89=E4=BA=8E=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E5=80=BC=E7=9A=84=E7=BB=84=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/18.4Sum.js | 76 +++++++++++++++++++++++++ NowCoder/2018Enterprise/departCandys.js | 2 +- 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 Leetcode/18.4Sum.js diff --git a/Leetcode/18.4Sum.js b/Leetcode/18.4Sum.js new file mode 100644 index 0000000..4cb8fa4 --- /dev/null +++ b/Leetcode/18.4Sum.js @@ -0,0 +1,76 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-21 11:14:03 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-21 11:17:01 + */ + + +/****** + * + * Given an array nums of n integers and an integer target, + * are there elements a, b, c, and d in nums such that a + b + c + d = target? + * Find all unique quadruplets in the array which gives the sum of target. + * + * + * input: + * Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. + * + * output: + * + * A solution set is: + * [ + * [-1, 0, 0, 1], + * [-2, -1, 1, 2], + * [-2, 0, 0, 2] + * ] + * + * + * + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function(nums, target) { + if(nums.length <4){ + return []; + } + let output = []; + nums.sort((a,b) => a-b); + for(let i=0;i Date: Sun, 21 Jul 2019 16:58:41 +0800 Subject: [PATCH 237/274] =?UTF-8?q?leetcode=20=E7=AC=AC=E5=9B=9B=E9=A2=98?= =?UTF-8?q?=20=E4=BD=BF=E7=94=A8=20O(log(m+n))=E7=9A=84=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E6=89=BE=E5=87=BA=E6=95=B0=E7=BB=84?= =?UTF-8?q?=20nums1=20=E5=92=8C=20=E6=95=B0=E7=BB=84=20nums2=20=E7=9A=84?= =?UTF-8?q?=E4=B8=AD=E4=BD=8D=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Leetcode/4.MedianofTwoSortedArrays.js | 73 +++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Leetcode/4.MedianofTwoSortedArrays.js diff --git a/Leetcode/4.MedianofTwoSortedArrays.js b/Leetcode/4.MedianofTwoSortedArrays.js new file mode 100644 index 0000000..7c0b045 --- /dev/null +++ b/Leetcode/4.MedianofTwoSortedArrays.js @@ -0,0 +1,73 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-21 16:46:17 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-21 16:58:14 + */ + + +/***** + * + * 使用 O(log(m+n))的算法复杂度找出数组 nums1 和 数组 nums2 的中位数 + * + * + * + * + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + * + * 思路是分成两部分,左边与右边比较,如果左边能够确定,中位数一定出现在左边 + * + */ + + + +var findMedianSortedArrays = function(nums1, nums2) { + if(nums1.length > nums2.length){ // to keep m < n + [nums1,nums2]=[nums2,nums1]; + } + let m = nums1.length; + let n = nums2.length; + let minIndex = 0,maxIndex=m,halfLen=parseInt((m+n+1)/2); + while(minIndex <= maxIndex){ + let i = parseInt((minIndex + maxIndex)/2); // i 取 nums1 数组的中间部分 + let j = halfLen-i; // j 取 总数中位数 减去 i 的长度部分 + if(i < m && nums2[j-1]>nums1[i]){ + minIndex = i+1; + }else if(i>0 && nums1[i-1]>nums2[j]){ + maxIndex = i-1; + }else { + let maxLeft = 0; + if(i===0){ + maxLeft = nums2[j-1]; + }else if(j===0){ + maxLeft = nums1[i-1]; + } else { + maxLeft = Math.max(nums1[i-1], nums2[j-1]); + } + if((m+n)%2 === 1){ + return parseFloat(maxLeft); + } + let minRight = 0; + if(i===m){ + minRight = nums2[j]; + }else if(j===n){ + minRight = nums1[i]; + }else { + minRight = Math.min(nums2[j], nums1[i]); + } + return (maxLeft + minRight)/2.0; + } + } + + return 0.0; +}; + +let nums1 = [1,3]; +let nums2 = [2]; + +console.log(findMedianSortedArrays(nums1,nums2)); \ No newline at end of file From 22acadc896e19abf692be002d216c247d1961a0c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 22 Jul 2019 14:30:51 +0800 Subject: [PATCH 238/274] =?UTF-8?q?=E6=95=B4=E7=90=86=E4=B8=80=E9=81=8D?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E8=AE=B0=E5=BD=95=E5=81=9A=E8=BF=87=E7=9A=84?= =?UTF-8?q?=E7=BC=96=E7=A8=8B=E9=A2=98=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kuaishou/numNofCounts.js | 58 +++++++++++++++++++ .../2019SchoolInterview/kuaishou/strDic.js | 43 ++++++++++++++ .../neteasy}/findDirection-neteasy.js | 0 .../neteasy}/findNumofDataList-neteasy.js | 0 .../zhaoyin}/departCandys.js | 0 .../byteDance/0705-1.js | 0 .../byteDance/0705-2.js | 0 .../byteDance/0705-3.js | 0 .../byteDance/0705-4.js | 0 .../byteDance/0705-5.js | 0 .../byteDance/0707-1.js | 0 .../byteDance/0707-3.js | 0 .../byteDance/0707-4.js | 0 .../{2019 => 2020RealTime}/byteDance/test.js | 0 .../crazyCowProblem-byteDance.js | 0 .../findPrime-byteDance.js | 0 .../htmltime-oneWallet.html | 0 .../jumpGameX-byteDance.js | 0 .../stringNormalization-kuaishou.js | 0 NowCoder/{2019 => 2020RealTime}/vivo1.js | 0 NowCoder/{2019 => 2020RealTime}/vivo2.js | 0 NowCoder/{2019 => 2020RealTime}/vivo3.js | 0 22 files changed, 101 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/kuaishou/numNofCounts.js create mode 100644 NowCoder/2019SchoolInterview/kuaishou/strDic.js rename NowCoder/{2018Enterprise => 2019SchoolInterview/neteasy}/findDirection-neteasy.js (100%) rename NowCoder/{2018Enterprise => 2019SchoolInterview/neteasy}/findNumofDataList-neteasy.js (100%) rename NowCoder/{2018Enterprise => 2019SchoolInterview/zhaoyin}/departCandys.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0705-1.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0705-2.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0705-3.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0705-4.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0705-5.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0707-1.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0707-3.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/0707-4.js (100%) rename NowCoder/{2019 => 2020RealTime}/byteDance/test.js (100%) rename NowCoder/{2019 => 2020RealTime}/crazyCowProblem-byteDance.js (100%) rename NowCoder/{2019 => 2020RealTime}/findPrime-byteDance.js (100%) rename NowCoder/{2019 => 2020RealTime}/htmltime-oneWallet.html (100%) rename NowCoder/{2019 => 2020RealTime}/jumpGameX-byteDance.js (100%) rename NowCoder/{2019 => 2020RealTime}/stringNormalization-kuaishou.js (100%) rename NowCoder/{2019 => 2020RealTime}/vivo1.js (100%) rename NowCoder/{2019 => 2020RealTime}/vivo2.js (100%) rename NowCoder/{2019 => 2020RealTime}/vivo3.js (100%) diff --git a/NowCoder/2019SchoolInterview/kuaishou/numNofCounts.js b/NowCoder/2019SchoolInterview/kuaishou/numNofCounts.js new file mode 100644 index 0000000..3ce09ab --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/numNofCounts.js @@ -0,0 +1,58 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-22 14:17:41 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-22 14:23:15 + */ + + +/***** + * + * 数字序列第N位的值 + * + * 有一个无限长的数字序列 1,2,2,3,3,3,4,4,4,4,5,5,5,5,5。。。 + * (数字序列从1开始递增,且数字k在该序列中正好出现k次),求第n项是多少 + * + * 输入:输入为一个整数n + * 4 + * + * 输出:输出一个整数,即第n项的值 + * 3 + * + * + * + */ + +// first Version +function countNum1(n){ + let saveList = []; + for(let i=1;i<=n;i++){ + let temp = i; + while(temp--){ + saveList.push(i); + } + } + return saveList[n-1]; +} + + + +function countNum(n){ + let count = 0; + for(let i=1;i<=n;i++){ + let temp = i; + while(temp--){ + count++; + if (count === n) { + return i; + } + } + } +} + + +console.log(countNum(4)); + +// let data = readline().split(' '); +// let numN = parseInt(data[0]); +// print(countNum(numN)); diff --git a/NowCoder/2019SchoolInterview/kuaishou/strDic.js b/NowCoder/2019SchoolInterview/kuaishou/strDic.js new file mode 100644 index 0000000..18b4233 --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/strDic.js @@ -0,0 +1,43 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-22 14:28:59 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-22 14:30:17 + */ + + +/***** + * + * 字符串归一化 + * + * 通过键盘输入一串小写字母(a~z)组成的字符串。 + * 请编写一个字符串归一化程序,统计字符串中相同字符出现的次数,并按字典序输出字符及其出现次数。 + * 例如字符串"babcc"归一化后为"a1b2c2" + * + * + */ + +function strDic(arr){ + if(!arr || arr.length === 0){ + return ''; + } + let countArr=[]; + arr = arr.split('').sort().join(''); + for(let i=0;ia-b) + for(let temp in countArr){ + backStr+= String(temp)+String(countArr[temp]); + } + return backStr; +} + +let datas = readline().split(' '); +let arr = datas[0]; +print(strDic(arr)); \ No newline at end of file diff --git a/NowCoder/2018Enterprise/findDirection-neteasy.js b/NowCoder/2019SchoolInterview/neteasy/findDirection-neteasy.js similarity index 100% rename from NowCoder/2018Enterprise/findDirection-neteasy.js rename to NowCoder/2019SchoolInterview/neteasy/findDirection-neteasy.js diff --git a/NowCoder/2018Enterprise/findNumofDataList-neteasy.js b/NowCoder/2019SchoolInterview/neteasy/findNumofDataList-neteasy.js similarity index 100% rename from NowCoder/2018Enterprise/findNumofDataList-neteasy.js rename to NowCoder/2019SchoolInterview/neteasy/findNumofDataList-neteasy.js diff --git a/NowCoder/2018Enterprise/departCandys.js b/NowCoder/2019SchoolInterview/zhaoyin/departCandys.js similarity index 100% rename from NowCoder/2018Enterprise/departCandys.js rename to NowCoder/2019SchoolInterview/zhaoyin/departCandys.js diff --git a/NowCoder/2019/byteDance/0705-1.js b/NowCoder/2020RealTime/byteDance/0705-1.js similarity index 100% rename from NowCoder/2019/byteDance/0705-1.js rename to NowCoder/2020RealTime/byteDance/0705-1.js diff --git a/NowCoder/2019/byteDance/0705-2.js b/NowCoder/2020RealTime/byteDance/0705-2.js similarity index 100% rename from NowCoder/2019/byteDance/0705-2.js rename to NowCoder/2020RealTime/byteDance/0705-2.js diff --git a/NowCoder/2019/byteDance/0705-3.js b/NowCoder/2020RealTime/byteDance/0705-3.js similarity index 100% rename from NowCoder/2019/byteDance/0705-3.js rename to NowCoder/2020RealTime/byteDance/0705-3.js diff --git a/NowCoder/2019/byteDance/0705-4.js b/NowCoder/2020RealTime/byteDance/0705-4.js similarity index 100% rename from NowCoder/2019/byteDance/0705-4.js rename to NowCoder/2020RealTime/byteDance/0705-4.js diff --git a/NowCoder/2019/byteDance/0705-5.js b/NowCoder/2020RealTime/byteDance/0705-5.js similarity index 100% rename from NowCoder/2019/byteDance/0705-5.js rename to NowCoder/2020RealTime/byteDance/0705-5.js diff --git a/NowCoder/2019/byteDance/0707-1.js b/NowCoder/2020RealTime/byteDance/0707-1.js similarity index 100% rename from NowCoder/2019/byteDance/0707-1.js rename to NowCoder/2020RealTime/byteDance/0707-1.js diff --git a/NowCoder/2019/byteDance/0707-3.js b/NowCoder/2020RealTime/byteDance/0707-3.js similarity index 100% rename from NowCoder/2019/byteDance/0707-3.js rename to NowCoder/2020RealTime/byteDance/0707-3.js diff --git a/NowCoder/2019/byteDance/0707-4.js b/NowCoder/2020RealTime/byteDance/0707-4.js similarity index 100% rename from NowCoder/2019/byteDance/0707-4.js rename to NowCoder/2020RealTime/byteDance/0707-4.js diff --git a/NowCoder/2019/byteDance/test.js b/NowCoder/2020RealTime/byteDance/test.js similarity index 100% rename from NowCoder/2019/byteDance/test.js rename to NowCoder/2020RealTime/byteDance/test.js diff --git a/NowCoder/2019/crazyCowProblem-byteDance.js b/NowCoder/2020RealTime/crazyCowProblem-byteDance.js similarity index 100% rename from NowCoder/2019/crazyCowProblem-byteDance.js rename to NowCoder/2020RealTime/crazyCowProblem-byteDance.js diff --git a/NowCoder/2019/findPrime-byteDance.js b/NowCoder/2020RealTime/findPrime-byteDance.js similarity index 100% rename from NowCoder/2019/findPrime-byteDance.js rename to NowCoder/2020RealTime/findPrime-byteDance.js diff --git a/NowCoder/2019/htmltime-oneWallet.html b/NowCoder/2020RealTime/htmltime-oneWallet.html similarity index 100% rename from NowCoder/2019/htmltime-oneWallet.html rename to NowCoder/2020RealTime/htmltime-oneWallet.html diff --git a/NowCoder/2019/jumpGameX-byteDance.js b/NowCoder/2020RealTime/jumpGameX-byteDance.js similarity index 100% rename from NowCoder/2019/jumpGameX-byteDance.js rename to NowCoder/2020RealTime/jumpGameX-byteDance.js diff --git a/NowCoder/2019/stringNormalization-kuaishou.js b/NowCoder/2020RealTime/stringNormalization-kuaishou.js similarity index 100% rename from NowCoder/2019/stringNormalization-kuaishou.js rename to NowCoder/2020RealTime/stringNormalization-kuaishou.js diff --git a/NowCoder/2019/vivo1.js b/NowCoder/2020RealTime/vivo1.js similarity index 100% rename from NowCoder/2019/vivo1.js rename to NowCoder/2020RealTime/vivo1.js diff --git a/NowCoder/2019/vivo2.js b/NowCoder/2020RealTime/vivo2.js similarity index 100% rename from NowCoder/2019/vivo2.js rename to NowCoder/2020RealTime/vivo2.js diff --git a/NowCoder/2019/vivo3.js b/NowCoder/2020RealTime/vivo3.js similarity index 100% rename from NowCoder/2019/vivo3.js rename to NowCoder/2020RealTime/vivo3.js From 65ec037bdeff3f0aad525eca45c297ad2ff6533b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 22 Jul 2019 15:02:23 +0800 Subject: [PATCH 239/274] =?UTF-8?q?=E7=BD=91=E6=98=93=E4=BA=92=E5=A8=B1?= =?UTF-8?q?=E7=9C=9F=E9=A2=98=E4=BC=9A=E8=AF=9D=E5=88=97=E8=A1=A8=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../neteasyGame/sessionList.js | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/neteasyGame/sessionList.js diff --git a/NowCoder/2019SchoolInterview/neteasyGame/sessionList.js b/NowCoder/2019SchoolInterview/neteasyGame/sessionList.js new file mode 100644 index 0000000..e9558bc --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasyGame/sessionList.js @@ -0,0 +1,101 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-22 14:54:43 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-22 15:01:53 + */ + + +/***** + * + * 会话列表 + * + * 小云正在参与开发一个即时聊天工具,他负责其中的会话列表部分。 + * 会话列表为显示为一个从上到下的多行控件,其中每一行表示一个会话,每一个会话都可以以一个唯一正整数id表示。 + * 当用户在一个会话中发送或接收信息时,如果该会话已经在会话列表中,则会从原来的位置移到列表的最上方;如果没有在会话列表中,则在会话列表最上方插入该会话。 + * 小云在现在要做的工作是测试,他会先把会话列表清空等待接收信息。当接收完大量来自不同会话的信息后,就输出当前的会话列表,以检查其中是否有bug。 + * + * + * 输入: + * 输入的第一行为一个正整数T(T<=10),表示测试数据组数。 + * 接下来有T组数据。每组数据的第一行为一个正整数N(1<=N<=200),表示接收到信息的次数。 + * 第二行为N个正整数,按时间从先到后的顺序表示接收到信息的会话id。会话id不大于1000000000。 + * + * 输出: + * 对于每一组数据,输出一行,按会话列表从上到下的顺序,输出会话id。 + * 相邻的会话id以一个空格分隔,行末没有空格。 + * + * 输入实例: + * 3 + * 5 + * 1 2 3 4 5 + * 6 + * 1 100 1000 1000 100 1 + * 7 + * 1 6 3 3 1 8 1 + * + * 输出实例: + * + * 5 4 3 2 1 + * 1 100 1000 + * 1 8 3 6 + * + * + * + */ + + + +function sessionList(arr){ + let output = []; + function keepSession(lists){ + let currentList = []; + for(i=0;i-1){ + let index = currentList.indexOf(lists[i]); + currentList.splice(index,1); + } + currentList.unshift(lists[i]); + } + return currentList; + } + for(let j=0;j Date: Tue, 23 Jul 2019 10:59:22 +0800 Subject: [PATCH 240/274] =?UTF-8?q?=E7=BB=99=E5=87=BA=E5=AD=97=E6=AF=8D?= =?UTF-8?q?=E5=8D=A1=E7=89=87=E7=9A=84=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../neteasy/getMaxCore-meteasy.js | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/neteasy/getMaxCore-meteasy.js diff --git a/NowCoder/2019SchoolInterview/neteasy/getMaxCore-meteasy.js b/NowCoder/2019SchoolInterview/neteasy/getMaxCore-meteasy.js new file mode 100644 index 0000000..8da1127 --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasy/getMaxCore-meteasy.js @@ -0,0 +1,75 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-23 10:29:30 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-23 10:58:42 + */ + +/**** + * + * 字母卡片 + * + * 给你n张卡片,卡片上仅包含大写英文字母,现你可从这n张卡片中选出k张,要求得到尽可能高的分数。 + * 关于分数的计算方式,在你所选择的k张卡片中,含有相同字母的卡片分数为卡片数乘以相同卡片个数。 + * 就样例而言,选择九张D和其他任意一张,得到的结果为9*9+1 。 + * + * 输入: + * 输入包含两行,第一行含两个整数n,k(0b-a); // 按照出现次数从大到小排序 + let count = select; // 分层次解决问题 + for (let i=0;icount && count>0){ + maxCore += count*count; + count = 0; + }else if(count>0) { + count = count-values[i]; + maxCore += values[i]*values[i]; + } + } + return maxCore; +} + +// let select = 10; +// let str = "DZFDFZDFDDDDDDF"; +let select = 40; +let str = "JVLUPUORKENJXVWJXNKMPRXOVKBOTDPSAWZEQQULEEYCOZCRKV"; + +console.log(getMaxCore(select, str)); + + +let tempdata; +// 针对不定的输入数据 +while(tempdata=readline()){ + let datas = tempdata.split(' '); + let totalNum = parseInt(datas[0]); + let select = parseInt(datas[1]); + + let data = readline().split(' '); + let str = String(data[0]); + let core = getMaxCore(select, str); + if(core){ + print(core) + } +} \ No newline at end of file From ec622d54a825e6de5a4d966b54d258e10d0f1eb7 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 23 Jul 2019 16:07:04 +0800 Subject: [PATCH 241/274] =?UTF-8?q?=E6=8C=91=E9=80=89=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98=E5=8F=8A=E8=A7=A3=E5=86=B3=E6=96=B9?= =?UTF-8?q?=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../neteasy/findMaxWorkMoney.js | 131 ++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js diff --git a/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js b/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js new file mode 100644 index 0000000..5b20d51 --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js @@ -0,0 +1,131 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-23 14:52:39 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-23 16:06:36 + */ + +/*** + * + * 为了找到自己满意的工作,牛牛收集了每种工作的难度和报酬。牛牛选工作的标准是在难度不超过自身能力值的情况下,牛牛选择报酬最高的工作。 + * 在牛牛选定了自己的工作后,牛牛的小伙伴们来找牛牛帮忙选工作,牛牛依然使用自己的标准来帮助小伙伴们。牛牛的小伙伴太多了,于是他只好把这个任务交给了你。 + * + * + * 输入: + * 每个输入包含一个测试用例。 + * 每个测试用例的第一行包含两个正整数,分别表示工作的数量N(N<=100000)和小伙伴的数量M(M<=100000)。 + * 接下来的N行每行包含两个正整数,分别表示该项工作的难度Di(Di<=1000000000)和报酬Pi(Pi<=1000000000)。 + * 接下来的一行包含M个正整数,分别表示M个小伙伴的能力值Ai(Ai<=1000000000)。 + * 保证不存在两项工作的报酬相同。 + * + * 输出: + * 对于每个小伙伴,在单独的一行输出一个正整数表示他能得到的最高报酬。一个工作可以被多个人选择。 + * + * + * ***/ + + + +function findMaxPi(numM,workDi,workPi,datas){ + let outside = []; + let work = new Map(); + for(let i=0;ib[1]-a[1]); + for(let j=0;jka[0]-b[0]); + //for(let i=1;ia-b); + let maxData = 0; + for (let k = 0; k < len+lenD; k++) { + // 找所有比当前费用小的价值最大值 + maxData = Math.max(maxData, work.get(a[k])); + work.set(a[k],maxData); + } + for (let j = 0; j < lenD; j++) { + outside.push(work.get(datas[j])); + } + return outside; +} + + +// 遇到奇怪的输入时处理方式 + +let j=0; +let numN,numM,initData; +while(!j){ + let datasOne=readline().split(' '); + if(datasOne.length>=2){ + initData = datasOne; + numN = parseInt(initData[0]); + numM = parseInt(initData[1]); + j++; + } +} + +let workDP = []; +let i=0; +while(i=2){ + workDP.push([parseInt(tempData[0]),parseInt(tempData[1])]); + i++; + } +} +let state=0; +let datas = []; +while(!state){ + let dataDis= readline().split(' '); + if(dataDis.length>=numM){ + state = 1; + for(let j=0;j Date: Wed, 24 Jul 2019 22:24:55 +0800 Subject: [PATCH 242/274] =?UTF-8?q?=E6=B8=B8=E6=88=8F=E6=B5=B7=E6=8A=A5?= =?UTF-8?q?=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kuaishou/findKindsofStr-kuaishou.js | 60 +++++++++++++++++++ .../neteasy/findMaxWorkMoney.js | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 NowCoder/2019SchoolInterview/kuaishou/findKindsofStr-kuaishou.js diff --git a/NowCoder/2019SchoolInterview/kuaishou/findKindsofStr-kuaishou.js b/NowCoder/2019SchoolInterview/kuaishou/findKindsofStr-kuaishou.js new file mode 100644 index 0000000..362fc61 --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/findKindsofStr-kuaishou.js @@ -0,0 +1,60 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-24 21:52:44 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-24 22:24:35 + */ + + +/**** + * + * 游戏海报 + * + * 小明有26种游戏海报,用小写字母"a"到"z"表示。 + * 小明会把游戏海报装订成册(可能有重复的海报),册子可以用一个字符串来表示,每个字符就表示对应的海报,例如abcdea。 + * 小明现在想做一些“特别版”,然后卖掉。特别版就是会从所有海报(26种)中随机选一张,加入到册子的任意一个位置。 + * 那现在小明手里已经有一种海报册子,再插入一张新的海报后,他一共可以组成多少不同的海报册子呢? + * + * + * 输入: + * 海报册子的字符串表示,1 <= 字符串长度<= 20 + * + * 输出: + * 一个整数,表示可以组成的不同的海报册子种类数 + * + * 输入示例: a + * + * 输出实例:51 + * + * + */ + +function findKindsofStr(initStr){ + // 算法复杂度 O(26*N) + let back = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; + let len = initStr.length; + let store = [] + for(let i=0;i<26;i++){ + for(let j=0;j<=len;j++){ + store.push(initStr.slice(0,j)+back[i]+initStr.slice(j,len)); + } + } + let onlyStore = [...new Set(store)]; + return onlyStore.length; +} + + +let initDatas = readline().split(' '); +let initStr = initDatas[0]; +print(findKindsofStr(initStr)) + + +// 简单解法:排列问题 + +// (len(str) + 1) * 26 - len(str) +// 有 len(str)+1 个位置可以插入新的字符,但是可能因为重复字母导致插入前后是相同的字符串 + +function findKindsofStr2(initStr){ + let len = initStr.length; + return (len+1)*26 - len; +} \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js b/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js index 5b20d51..bc1720b 100644 --- a/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js +++ b/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-07-23 14:52:39 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-07-23 16:06:36 + * @Last Modified time: 2019-07-23 16:24:15 */ /*** From 0fd5ca6e843786edb13f47fe065eff316bec8c1e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 26 Jul 2019 21:22:56 +0800 Subject: [PATCH 243/274] =?UTF-8?q?2019=E5=B9=B4=E6=A0=A1=E6=8B=9B?= =?UTF-8?q?=E9=83=A8=E5=88=86=E7=AE=97=E6=B3=95=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kuaishou/minNumofthings.js | 51 +++++++++ .../neteasy/packageKindsOf.js | 69 ++++++++++++ .../2019SchoolInterview/pdd/findMinDec-pdd.js | 63 +++++++++++ .../2019SchoolInterview/pdd/minTimes-pdd.js | 102 ++++++++++++++++++ 4 files changed, 285 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/kuaishou/minNumofthings.js create mode 100644 NowCoder/2019SchoolInterview/neteasy/packageKindsOf.js create mode 100644 NowCoder/2019SchoolInterview/pdd/findMinDec-pdd.js create mode 100644 NowCoder/2019SchoolInterview/pdd/minTimes-pdd.js diff --git a/NowCoder/2019SchoolInterview/kuaishou/minNumofthings.js b/NowCoder/2019SchoolInterview/kuaishou/minNumofthings.js new file mode 100644 index 0000000..862fe3c --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/minNumofthings.js @@ -0,0 +1,51 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-25 14:14:51 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-25 14:15:43 + */ + +/***** + * + * + * + * + */ + + +// 2/3 时间复杂度太高 +function getAll(all){ + let count = Number.MAX_SAFE_INTEGER; + let tempState = all; + let ido = [7,5,3]; + + this.dfs = function(current,times){ + if(current === 0){ + if(count > times){ + count = times; + } + } + if(current>0){ + for(let j=0;ja-b); + for(let i=0;inumW){ + return; + } + if(total<=numW){ + outside++; + console.log(total); + } + for (let k = index; k < numN; k++) { + // 把当前值和没有经历过的值都来一遍 + this.dfs(k+1,total+vols[k]); + } + } + if(sum<=numW){ + // 当所有零食之和小于背包承重时,就有 2**numN 种方法 + return Math.pow(2,numN); + }else { + this.dfs(0,0); + } + return outside; +} + +let numN = 4; +let numW = 10; +let vols = [1,2,4,5]; +console.log(findMethods(numN,numW,vols)); \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/pdd/findMinDec-pdd.js b/NowCoder/2019SchoolInterview/pdd/findMinDec-pdd.js new file mode 100644 index 0000000..2144fb2 --- /dev/null +++ b/NowCoder/2019SchoolInterview/pdd/findMinDec-pdd.js @@ -0,0 +1,63 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-26 19:48:52 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-26 19:50:42 + */ + + +/***** + * + * + * 两两配对差值最小 + * + * 给定一个长度为偶数的数组arr,将该数组中的数字两两配对并求和,在这些和中选出最大和最小值, + * 请问该如何两两配对,才能让最大值和最小值的差值最小? + * + * 输入描述: + * 一共2行输入。 + * 第一行为一个整数n,2<=n<=10000, 第二行为n个数,组成目标数组,每个数大于等于2,小于等于100。 + * + * 输出描述: + * 输出最小的差值。 + * + * + * 输入: + * 4 + * 2 6 4 3 + * + * 输出: + * 1 + * + */ + +function findMinDec(datas){ + let min = Number.MAX_SAFE_INTEGER,max=0; + let len = datas.length; + datas.sort((a,b)=>a-b); + let store,sum; + let i=0,j=datas.length-1; + while(i0){ + maxNTime++; + alP=alP-nA; + } + minTime = Math.min(minTime, maxNTime); + alP = parseInt(hP); + function dfs(current,times){ + if(current<=0){ + minTime = Math.min(minTime, times); + return; + } + if(times>=minTime){ + return; + }else { + dfs(current-nA,times+1); + dfs(current-bA,times+2); + } + } + dfs(alP,0); + return minTime; +} + +let hP=100; +let nA=2; +let bA=5; +// console.log(minTimes(hP,nA,bA)); + + + +// 数学原理方案解决 +function minTimes2(hP,nA,bA){ + let minTime; + if(bA <= 2*nA){ + if(hP % nA === 0){ + minTime = hP/nA; + }else { + minTime = parseInt(hP/nA) + 1; + } + }else { + if(hP % bA === 0){ + minTime = 2*(hP/bA); + }else { + let tempA = hP % bA; + if(tempA <= nA){ + minTime = 2* parseInt(hP/bA)+1; + }else { + minTime = 2* parseInt(hP/bA)+2; + } + } + } + return minTime; +} +console.log(minTimes2(hP,nA,bA)); + +let hP = parseInt(readline().split(' ')[0]); +let nA = parseInt(readline().split(' ')[0]); +let bA = parseInt(readline().split(' ')[0]); + +print(minTimes(hP,nA,bA)); \ No newline at end of file From 9730c99fe7a5591d1384ca800cff014004f23233 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 27 Jul 2019 20:45:25 +0800 Subject: [PATCH 244/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20shopee=E7=9A=84?= =?UTF-8?q?=E4=B8=89=E9=81=93=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/shopee/1.js | 42 +++++++++++++++++++++++++++++++ NowCoder/2020RealTime/shopee/2.js | 23 +++++++++++++++++ NowCoder/2020RealTime/shopee/3.js | 25 ++++++++++++++++++ 3 files changed, 90 insertions(+) create mode 100644 NowCoder/2020RealTime/shopee/1.js create mode 100644 NowCoder/2020RealTime/shopee/2.js create mode 100644 NowCoder/2020RealTime/shopee/3.js diff --git a/NowCoder/2020RealTime/shopee/1.js b/NowCoder/2020RealTime/shopee/1.js new file mode 100644 index 0000000..3055f56 --- /dev/null +++ b/NowCoder/2020RealTime/shopee/1.js @@ -0,0 +1,42 @@ +function processData(data){ + let outside = []; + let store = new Map(); + data = data.toLowerCase(); + for(let i=0;ia.charCodeAt()-b.charCodeAt()); + reData.sort((a,b)=>a.charCodeAt()-b.charCodeAt()); + outside.push(reData.join('')); + outside.push(onceData.join('')); + return outside; +} + +let data = "aaaaa"; +console.log(processData(data)); + + +let datas = readline(); +let output = processData(datas); +if(output.length){ + for(let i=0;i/gi; + // let regexpGender = /<% gender %>/gi; + // afterPro = afterPro.replace(regexpName,tempData.name); + // afterPro = afterPro.replace(regexpGender,tempData.gender); + // return afterPro; + let tempData = { + "name":"Han Meimei", + "gender":"男" + } + let regexpName = new RegExp("<% name %>"); + let regexpGender = new RegExp("<% gender %>"); + data = data.replace(regexpName,tempData.name); + data = data.replace(regexpGender,tempData.gender); + return data; +} + + +let data = "<% name %>,欢迎来到这里,祝你早日找到<% gender %>盆友!"; +console.log(processData(data)); \ No newline at end of file From b72b75a58dd3f9b97b60908e24164cfe9150ac3a Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 28 Jul 2019 11:07:35 +0800 Subject: [PATCH 245/274] =?UTF-8?q?=E5=8A=9E=E5=85=AC=E5=AE=A4=E9=97=A8?= =?UTF-8?q?=E5=8F=A3=E5=88=B0=E5=BA=A7=E4=BD=8D=E7=9A=84=E8=B5=B0=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../shopee/pathSolutions.js | 230 ++++++++++++++++++ 1 file changed, 230 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/shopee/pathSolutions.js diff --git a/NowCoder/2019SchoolInterview/shopee/pathSolutions.js b/NowCoder/2019SchoolInterview/shopee/pathSolutions.js new file mode 100644 index 0000000..462a4bc --- /dev/null +++ b/NowCoder/2019SchoolInterview/shopee/pathSolutions.js @@ -0,0 +1,230 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-27 18:32:10 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-28 11:06:37 + */ + + +/**** + * + * + * shopee的办公室非常大,小虾同学的位置坐落在右上角,而大门却在左下角, + * 可以把所有位置抽象为一个网格(门口的坐标为0,0),小虾同学很聪明,每次只向上,或者向右走, + * 因为这样最容易接近目的地,但是小虾同学不想让自己的boss们看到自己经常在他们面前出没,或者迟到被发现。 + * 他决定研究一下如果他不通过boss们的位置,他可以有多少种走法? + * + * 输入描述: + * + * 第一行 x,y,n (0numX || ty>numY){ + return; + } + if(checkifNone(tx,ty)){ + dfs(tx+1,ty); + dfs(tx,ty+1); + }else{ + return; + } + } + dfs(0,0); + return solutions; +} + +// 以上时间复杂度过高 + + +/**** + * + * + * 动态规划的思想 + * 注意细节 + * + */ + +function waysofSolution2(numX,numY,bPs){ + let state = true; + let dp = []; + for (let i = 0; i <= numX; i++) { + dp[i] = []; + for (let j = 0; j <=numY; j++) { + dp[i][j]=0; + + } + dp[i][0]=1; + } + + for (let j = 0; j <=numY; j++) { + dp[0][j]=1; + } + for(let i=0;i 9?1:0; + tempState = tempData > 0; + } + // console.log(sum); + return sum; + } + + for (let i = 1; i <=numX; i++) { + for (let j = 1; j <=numY; j++) { + if(dp[i][j]===-1){ + continue; + } + if(dp[i-1][j]!==-1){ + dp[i][j] = bigNumAdd(dp[i][j],dp[i-1][j]); + } + if(dp[i][j-1]!==-1){ + dp[i][j] = bigNumAdd(dp[i][j],dp[i][j-1]); + } + } + } + // console.log(dp); + return dp[numX][numY]; +} + +// 最开始以上测试用例可以通过 50% ,经过测试和处理 +// JavaScript 整数位 只能存 16位 +// 需要使用额外的整数相加 + + + + + +let numX = 2; +let numY = 2; +let bPs = [ + [0,1] +] +console.log(waysofSolution2(numX,numY,bPs)); + + + +function bigNumAdd(a,b){ + let sum = ''; + let tempState = false,tempData=0; // 判断是否需要进位 + a = String(a).split(''); + b = String(b).split(''); + while(a.length || b.length || tempState){ + // parseInt 对 '' 会转换成 NaN,但是 ~~ 会转换成 0 + if(a.length && b.length){ + tempData += ~~a.pop() + ~~b.pop(); + }else if(!a.length && b.length){ + tempData += 0 + ~~b.pop(); + }else if(!b.length && a.length){ + tempData += ~~a.pop() + 0; + } + + sum = (tempData % 10) + sum; + tempData = tempData > 9?1:0; + tempState = tempData > 0; + } + // console.log(sum); + return sum; +} + +// let a = 35532486379567141; // 35532486379567140 +// let b = 18; +// let a = 3553248637956714; // 35532486379567140 +// let b = 8553248637956713; + +// console.log(bigNumAdd(a,b)); +// let initDatas = readline().split(' '); +// let numX = parseInt(initDatas[0]); +// let numY = parseInt(initDatas[1]); +// let numN = parseInt(initDatas[2]); + +// let bPs = []; +// let state = numN; +// while(state>0){ +// let tempData = readline().split(' '); +// bPs.push([parseInt(tempData[0]), parseInt(tempData[1])]); +// state--; +// } + +// print(waysofSolution(numX,numY,bPs)) \ No newline at end of file From 5f002edf51eadeeb68f1510dfb44fac9c5aa6ee7 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 29 Jul 2019 21:47:31 +0800 Subject: [PATCH 246/274] =?UTF-8?q?=E6=8B=BC=E5=A4=9A=E5=A4=9A=E7=A7=8D?= =?UTF-8?q?=E6=A0=91=E7=AE=97=E6=B3=95=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2019SchoolInterview/pdd/treeSolution.js | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/pdd/treeSolution.js diff --git a/NowCoder/2019SchoolInterview/pdd/treeSolution.js b/NowCoder/2019SchoolInterview/pdd/treeSolution.js new file mode 100644 index 0000000..7f7a992 --- /dev/null +++ b/NowCoder/2019SchoolInterview/pdd/treeSolution.js @@ -0,0 +1,148 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-26 21:32:46 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-28 14:50:04 + */ + + +/**** + * + * 种树方案 + * + * 小多想在美化一下自己的庄园。他的庄园毗邻一条小河,他希望在河边种一排树,共 M 棵。 + * 小多采购了 N 个品种的树,每个品种的数量是 Ai (树的总数量恰好为 M)。 + * 但是他希望任意两棵相邻的树不是同一品种的。小多请你帮忙设计一种满足要求的种树方案。 + * + * 输入描述: + * 第一行包含一个正整数 N,表示树的品种数量。 + * 第二行包含 N 个正整数,第 i (1 <= i <= N) 个数表示第 i 个品种的树的数量。 + * 数据范围: + * 1 <= N <= 1000 + * 1 <= M <= 2000 + * + * 输出描述: + * 输出一行,包含 M 个正整数,分别表示第 i 棵树的品种编号 (品种编号从1到 N)。 + * 若存在多种可行方案,则输出字典序最小的方案。若不存在满足条件的方案,则输出"-"。 + * + * + * + * + * + */ + + +// 时间复杂度太高 +function treeSolution(numN,trees){ + let solutions = []; + if(numN === 1){ + if(trees[0]>1){ + return '-'; + }else { + return '1'; + } + } + let store = trees.slice(0); + let i=0,j=1; + let state = true; + while(j0 && state){ + state = false; + solutions.push(i+1); + store[i] = store[i]-1; + }else if(!state && store[j]>0){ + state = true; + solutions.push(j+1); + store[j] = store[j]-1; + } + if(store[i]===0 && store[j]!==0){ + i = j; + j = j+1; + }else if(store[j]===0){ + j=j+1; + } + } + if(store[i]>0 && state){ + solutions.push(i+1); + store[i] = store[i]-1; + } + if(store[i]!==0){ + return '-'; + } + return solutions.join(' '); +} + +let numN = 3; +let trees = [4,2,1]; +console.log(treeSolution(numN,trees)); + + +// 判断及剪枝的方法 + +function treeSolution2(numN,trees){ + let M=0; + for (let i = 0; i < numN; i++) { + M+= trees[i]; + } + let odd = M%2===0? false:true; + let checkL=false; + if (odd) { + checkL = trees.some((a)=> a > (M+1)/2); //some 方法 如果有返回 true + }else { + checkL = trees.some((a)=> a > M/2); + } + if(checkL){ + return '-'; + } + + let ans = []; + function checkFite(left){ + for (let i = 0; i < numN; i++) { + if (trees[i]> (left + 1)/2) { + return false; + } + } + return true; + } + + function dfs(index){ + if(!checkFite(M-index)){ + return false; + } + if (index===M) { + return true; + } else { + for (let i = 0; i Date: Tue, 30 Jul 2019 11:26:38 +0800 Subject: [PATCH 247/274] =?UTF-8?q?=E7=BD=91=E6=98=93=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E9=A2=98=20=E7=89=9B=E7=89=9B=E7=9A=84=E9=97=B9=E9=92=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../neteasy/findLastGetUpTime.js | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/neteasy/findLastGetUpTime.js diff --git a/NowCoder/2019SchoolInterview/neteasy/findLastGetUpTime.js b/NowCoder/2019SchoolInterview/neteasy/findLastGetUpTime.js new file mode 100644 index 0000000..437b789 --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasy/findLastGetUpTime.js @@ -0,0 +1,95 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-30 10:49:42 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-30 11:26:19 + */ + + +/***** + * + * 牛牛的闹钟 + * + * 牛牛总是睡过头,所以他定了很多闹钟,只有在闹钟响的时候他才会醒过来并且决定起不起床。 + * 从他起床算起他需要X分钟到达教室,上课时间为当天的A时B分,请问他最晚可以什么时间起床 + * + * 输入描述: + * 每个输入包含一个测试用例。 + * 每个测试用例的第一行包含一个正整数,表示闹钟的数量N(N<=100)。 + * 接下来的N行每行包含两个整数,表示这个闹钟响起的时间为Hi(0<=A<24)时Mi(0<=B<60)分。 + * 接下来的一行包含一个整数,表示从起床算起他需要X(0<=X<=100)分钟到达教室。 + * 接下来的一行包含两个整数,表示上课时间为A(0<=A<24)时B(0<=B<60)分。 + * 数据保证至少有一个闹钟可以让牛牛及时到达教室。 + * + * + * 输出描述: + * 输出两个整数表示牛牛最晚起床时间。 + * + * + * 输入: + * 3 + * 5 0 + * 6 0 + * 7 0 + * 59 + * 6 59 + * + * 输出: + * 6 0 + * + * + */ + +function findLastGetUpTime(numN,clocks,numMi,classTime){ + let getUpTime=[0,0]; + function checkIfOntime(clock,numMi,classTime){ + let state = false; + let temp = clock[1]+numMi; + if(clock[0]< classTime[0]){ + if(temp<= 60){ + state = true; + }else { + let tempArr = []; + tempArr.push(clock[0]+ parseInt(temp/60)); + tempArr.push(temp%60); + state = checkIfOntime(tempArr,0,classTime) + } + }else if(clock[0]=== classTime[0]){ + if(temp <= classTime[1]){ + state = true; + } + } + return state; + } + for(let i=0;i Date: Tue, 30 Jul 2019 20:22:50 +0800 Subject: [PATCH 248/274] =?UTF-8?q?2020=E7=9B=B8=E5=85=B3=E7=AC=94?= =?UTF-8?q?=E8=AF=95=E9=A2=98=E6=95=B4=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit liulishuo --- NowCoder/2020RealTime/liulishuo/minPrice.js | 52 +++++++++++++++++++ .../5.useTwoStackCreatQueue.js | 8 +++ 2 files changed, 60 insertions(+) create mode 100644 NowCoder/2020RealTime/liulishuo/minPrice.js diff --git a/NowCoder/2020RealTime/liulishuo/minPrice.js b/NowCoder/2020RealTime/liulishuo/minPrice.js new file mode 100644 index 0000000..33feeab --- /dev/null +++ b/NowCoder/2020RealTime/liulishuo/minPrice.js @@ -0,0 +1,52 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-30 20:17:40 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-30 20:22:14 + */ + + +/***** + * + * 你需要爬上一个N层的楼梯,在爬楼梯过程中, 每阶楼梯需花费非负代价, + * 第i阶楼梯花费代价表示为cost[i],一旦你付出了代价,你可以在该阶基础上往上爬一阶或两阶。 + * 你可以从第 0 阶或者 第 1 阶开始,请找到到达顶层的最小的代价是多少。 + * N和cost[i]皆为整数,且N∈[2,1000],cost[i]∈ [0, 999]。 + * + * + * 输入描述: + * 输入为一串空格分割的整数,对应cost数组,例如 + * 10 15 20 + * + * + * 输出描述 + * 输出一个整数,表示花费的最小代价 + * 15 + * + * + * 动态规划问题 + * + * dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]) + * + */ + +function minPrice(data){ + let minP; + let storeA = []; + storeA.push(0); + storeA.push(0); + for(let i=2;i<=data.length;i++){ + storeA[i] = Math.min(storeA[i-1]+data[i-1],storeA[i-2]+data[i-2]); + } + minP = storeA[storeA.length-1]; + return minP; +} + +let datas = readline().split(' '); +let data = []; +for(let i=0;i Date: Wed, 31 Jul 2019 09:48:24 +0800 Subject: [PATCH 249/274] =?UTF-8?q?=E9=B8=A1=E9=B8=AD=E5=88=86=E7=B1=BB?= =?UTF-8?q?=E9=97=AE=E9=A2=98=20=E5=92=8C=20=E4=BB=8A=E5=B9=B4=E7=AC=AC?= =?UTF-8?q?=E5=87=A0=E5=A4=A9=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kuaishou/countDayinYear.js | 69 ++++++++++++++++++ .../zhaoyin/candDClassify.js | 72 +++++++++++++++++++ 2 files changed, 141 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/kuaishou/countDayinYear.js create mode 100644 NowCoder/2019SchoolInterview/zhaoyin/candDClassify.js diff --git a/NowCoder/2019SchoolInterview/kuaishou/countDayinYear.js b/NowCoder/2019SchoolInterview/kuaishou/countDayinYear.js new file mode 100644 index 0000000..2b8932b --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/countDayinYear.js @@ -0,0 +1,69 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-31 09:43:37 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-31 09:47:53 + */ + + +/***** + * + * 今年第几天 + * + * 输入年、月、日,计算该天是本年的第几天。 + * 输入: + * 包括三个整数年(1<=Y<=3000)、月(1<=M<=12)、日(1<=D<=31)。 + * 输出: + * 输入可能有多组测试数据,对于每一组测试数据, + * 输出一个整数,代表Input中的年、月、日对应本年的第几天。 + * + * 输入描述: + * 输入:1990 9 20 + * 输出描述: + * 输出:263 + * + * 输入示例: + * 2000 5 1 + * 输出示例: + * 122 + * + * + * + */ + + +function countDayinYear(year,month,day){ + let count=0; + let mons = [31,28,31,30,31,30,31,31,30,31,30,31]; + + // 判断是否是闰年的方法 + function checkifLeap(y){ + if((y%4===0 && y%100!==0) || y%400===0){ + return true; + }else{ + return false; + } + } + // 闰年改二月 + if(checkifLeap(year)){ + mons[1]=29; + } + // 计算已经过去的月份 + for(let i=0;iCCCDC->CCCCD这样就能使之前的两处鸡鸭相邻变为一处鸡鸭相邻,需要调整队形两次。 + * + * 输入描述: + * 输入一个长度为N,且只包含C和D的非空字符串。 + * + * 输出描述: + * 使得最后仅有一对鸡鸭相邻,最少的交换次数 + * + * 输入: + * CCDCC + * + * 输出: + * 2 + * + * 类似快慢指针的思想 + * + * 测试用例里面全是 C在左D在右的 + * + * + * + */ + + +// 第一个简单版本 + +function minChangeTime(data){ + let times = 0,count=0; + for(let i=0;i Date: Fri, 2 Aug 2019 22:13:14 +0800 Subject: [PATCH 250/274] =?UTF-8?q?acmcoder=20=E7=BC=96=E8=AF=91=E7=8E=AF?= =?UTF-8?q?=E5=A2=83=E6=B5=8B=E8=AF=95=E9=A2=98=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TestProjects/ACMOJ/percentStr.js | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 TestProjects/ACMOJ/percentStr.js diff --git a/TestProjects/ACMOJ/percentStr.js b/TestProjects/ACMOJ/percentStr.js new file mode 100644 index 0000000..a390245 --- /dev/null +++ b/TestProjects/ACMOJ/percentStr.js @@ -0,0 +1,49 @@ +/** + * + * 约德尔测试 + * +*/ + + +function percentStr(dataone,datatwo){ + let outside; + let count= 0; + for(let i=0;i='a' && dataone[i]<='z') || (dataone[i]>='A' && dataone[i]<='Z') || (dataone[i]>='0' && dataone[i]<='9')){ +// temp = '1'; +// } +// onestr+= temp; +// if(temp === datatwo[i]){ +// count++; +// } + + + +let dataone = read_line(); +let datatwo = read_line(); + +print(percentStr(dataone,datatwo)) + + +// let dataone = read_line().trim(); +// let datatwo = read_line().trim(); \ No newline at end of file From 322597f6d9c763c78781ae9a5dfd214fcac3fe20 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 5 Aug 2019 09:39:21 +0800 Subject: [PATCH 251/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=8A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E4=BA=86=E9=83=A8=E5=88=86=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kuaishou}/stringNormalization-kuaishou.js | 0 .../neteasy/findLeftCard.js | 103 +++++++++++++++ .../neteasy/findMinCandy.js | 47 +++++++ NowCoder/2020RealTime/DJI/1.js | 90 +++++++++++++ NowCoder/2020RealTime/DJI/2.js | 120 ++++++++++++++++++ .../crazyCowProblem-byteDance.js | 0 .../{ => byteDance}/findPrime-byteDance.js | 0 .../{ => byteDance}/jumpGameX-byteDance.js | 0 NowCoder/2020RealTime/{ => vivo}/vivo1.js | 0 NowCoder/2020RealTime/{ => vivo}/vivo2.js | 0 NowCoder/2020RealTime/{ => vivo}/vivo3.js | 0 NowCoder/2020RealTime/yuanfudao/1.js | 61 +++++++++ TestProjects/ACMOJ/checkArray.js | 67 ++++++++++ TestProjects/ACMOJ/jd/processArr.js | 82 ++++++++++++ 14 files changed, 570 insertions(+) rename NowCoder/{2020RealTime => 2019SchoolInterview/kuaishou}/stringNormalization-kuaishou.js (100%) create mode 100644 NowCoder/2019SchoolInterview/neteasy/findLeftCard.js create mode 100644 NowCoder/2019SchoolInterview/neteasy/findMinCandy.js create mode 100644 NowCoder/2020RealTime/DJI/1.js create mode 100644 NowCoder/2020RealTime/DJI/2.js rename NowCoder/2020RealTime/{ => byteDance}/crazyCowProblem-byteDance.js (100%) rename NowCoder/2020RealTime/{ => byteDance}/findPrime-byteDance.js (100%) rename NowCoder/2020RealTime/{ => byteDance}/jumpGameX-byteDance.js (100%) rename NowCoder/2020RealTime/{ => vivo}/vivo1.js (100%) rename NowCoder/2020RealTime/{ => vivo}/vivo2.js (100%) rename NowCoder/2020RealTime/{ => vivo}/vivo3.js (100%) create mode 100644 NowCoder/2020RealTime/yuanfudao/1.js create mode 100644 TestProjects/ACMOJ/checkArray.js create mode 100644 TestProjects/ACMOJ/jd/processArr.js diff --git a/NowCoder/2020RealTime/stringNormalization-kuaishou.js b/NowCoder/2019SchoolInterview/kuaishou/stringNormalization-kuaishou.js similarity index 100% rename from NowCoder/2020RealTime/stringNormalization-kuaishou.js rename to NowCoder/2019SchoolInterview/kuaishou/stringNormalization-kuaishou.js diff --git a/NowCoder/2019SchoolInterview/neteasy/findLeftCard.js b/NowCoder/2019SchoolInterview/neteasy/findLeftCard.js new file mode 100644 index 0000000..ccd1d23 --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasy/findLeftCard.js @@ -0,0 +1,103 @@ +function findLeftCard(numN,datas){ + let backList = []; + function multiply(num1, num2) { + if(isNaN(num1) || isNaN(num2)) return ''; + var len1 = String(num1).length, + len2 = String(num2).length; + var ans = []; + for (var i = len1 - 1; i >= 0; i--) { + for (var j = len2 - 1; j >= 0; j--) { + var index1 = i + j; + var index2 = i + j + 1; + var mul = parseInt(String(num1)[i]) * parseInt(String(num2)[j]) + (ans[index2] || 0); + ans[index1] = Math.floor(mul / 10) + (ans[index1] || 0); + ans[index2] = mul % 10; + } + } + var result = ans.join(''); + return +result === 0 ? '0' : result.replace(/^0+/,''); + } + function getState(matrix){ + let n = matrix[0]; + let m = matrix[1]; + if(n>m){ + [m,n] = [n,m]; + } + if(n===1&&m==1){ + return 1; + }else if(n===1&&m>1){ + return m-2; + }else if(n>1 && n<=m){ + if(n>10000||m>10000){ + return multiply(n-2, m-2); + }else{ + return (n-2)*(m-2); + } + + } + } + + for(let i=0;i= 0; i--) { //这里倒过来遍历很妙,不需要处理进位了 + for (var j = len2 - 1; j >= 0; j--) { + var index1 = i + j; + var index2 = i + j + 1; + var mul = parseInt(String(num1)[i]) * parseInt(String(num2)[j]) + (ans[index2] || 0); + ans[index1] = Math.floor(mul / 10) + (ans[index1] || 0); + ans[index2] = mul % 10; + } + } + // console.log(ans); + var result = ans.join(''); + //这里结果有可能会是多个零的情况,需要转成数字判断 + //原来写的是return +result === 0 ? '0' : result,result字符串会出现有前置0的情况 + return +result === 0 ? '0' : result.replace(/^0+/,''); +} + + + +function multiply(num1, num2) { + if(isNaN(num1) || isNaN(num2)) return ''; + var len1 = String(num1).length, + len2 = String(num2).length; + var ans = []; + for (var i = len1 - 1; i >= 0; i--) { + for (var j = len2 - 1; j >= 0; j--) { + var index1 = i + j; + var index2 = i + j + 1; + var mul = parseInt(String(num1)[i]) * parseInt(String(num2)[j]) + (ans[index2] || 0); + ans[index1] = Math.floor(mul / 10) + (ans[index1] || 0); + ans[index2] = mul % 10; + } + } + var result = ans.join(''); + return +result === 0 ? '0' : result.replace(/^0+/,''); +} \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/neteasy/findMinCandy.js b/NowCoder/2019SchoolInterview/neteasy/findMinCandy.js new file mode 100644 index 0000000..d51db97 --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasy/findMinCandy.js @@ -0,0 +1,47 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-03 14:35:16 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-03 14:35:55 + */ + + + +function findMinCandy(numN,numM,person){ + let minCandy=0; + let store = {}; + let max=0; + for(let i=0;imax){ + max = store.get(tempN); + } + } + } + + +} + + + + + + + + + +let inits = readline().split(' '); +let numN = parseInt(inits[0]); +let numM = parseInt(inits[1]); + +let person = [],temp; +for(let i=0;i480?0:count; +} + + + +let numN=8,numA=2,numX=8; +let dataN = [60, 60, 60, 60, 60, 60, 60, 60]; +// let numN=4,numA=3,numX=3; +// let dataN = [333, 77, 100, 13]; + +console.log(processData2(numN,numA,numX,dataN)); + + + +// let initdata,numN,numA,numX,temp; +// while(initdata= read_line()){ +// initdata = initdata.split(' '); +// numN = parseInt(initdata[0]); +// numA = parseInt(initdata[1]); +// numX = parseInt(initdata[2]); +// let temp = numN; +// let dataN = []; +// while(temp>0){ +// dataN.push(readInt()); +// temp--; +// } +// print(processData(numN,numA,numX,dataN)) +// } \ No newline at end of file diff --git a/NowCoder/2020RealTime/DJI/2.js b/NowCoder/2020RealTime/DJI/2.js new file mode 100644 index 0000000..b0fe952 --- /dev/null +++ b/NowCoder/2020RealTime/DJI/2.js @@ -0,0 +1,120 @@ + +/***** + * + * 零食问题,最大满意度 + * + * + * + */ + + +function processData(numN,numT,dataN){ + let maxV = numT; + let arrV = []; + let arrL = []; + dataN.sort((a,b)=>b[1]-a[1]); + for (let i = 0; i < numN; i++) { + arrV.push(dataN[i][0]); + arrL.push(dataN[i][1]); + let count = dataN[i][2]; + while(count>1){ + arrV.push(dataN[i][0]); + arrL.push(dataN[i][1]); + count--; + } + } + let maxLength = arrV.length; + let dp = []; + for (let j = 0; j <=maxLength; j++) { + dp[j]=[]; + dp[j][0]=0; + } + for (let k = 0; k <= maxLength; k++) { + for (let w = 0; w <= maxV; w++) { + if (k == 0 || w == 0) { + dp[k][w] = 0; + } else if (arrV[k - 1] <= w) { + a = arrL[k - 1] + dp[k - 1][w - arrV[k - 1]]; + b = dp[k - 1][w]; + dp[k][w] = (a > b) ? a : b; + } else { + dp[k][w] = dp[k - 1][w]; + } + } + } + return dp[maxLength][maxV]; +} + +let numN=3,numT=100; +let dataN=[ + [26,100,4], + [5,1,4], + [5,2,2] +]; +console.log(processData(numN,numT,dataN)); + + + + + + + + + + + + + +// function solution(arr1, arr2, arr3) { + +// var sum = arr1[0]; + +// var maxValue; + +// maxValue = 0; +// var i, w, a, b, kS = []; + +// let maxLength = arr2.length; + +// for (let i = 0; i <= arr2.length; i++) { +// kS[i] = []; +// } + +// for (let j = 0; j <= maxLength; j++) { +// for (let w = 0; w <= sum; w++) { +// if (j == 0 || w == 0) { +// kS[j][w] = 0; +// } else if (arr2[j - 1] <= w) { +// a = arr3[j - 1] + kS[j - 1][w - arr2[j - 1]]; +// b = kS[j - 1][w]; +// kS[j][w] = (a > b) ? a : b; +// } else { +// kS[j][w] = kS[j - 1][w]; +// } +// } +// } + +// maxValue = kS[maxLength][sum]; + +// return maxValue; + +// } + + +let initdata,numN,numT,temp; +while(initdata= read_line()){ + initdata = initdata.split(' '); + numN = parseInt(initdata[0]); + numT = parseInt(initdata[1]); + let temp = numN; + let dataN = []; + while(temp>0){ + let tempC = [] + tempC.push(readInt()); + tempC.push(readInt()); + tempC.push(readInt()); + dataN.push(tempC); + temp--; + } + print(processData(numN,numT,dataN)) +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/crazyCowProblem-byteDance.js b/NowCoder/2020RealTime/byteDance/crazyCowProblem-byteDance.js similarity index 100% rename from NowCoder/2020RealTime/crazyCowProblem-byteDance.js rename to NowCoder/2020RealTime/byteDance/crazyCowProblem-byteDance.js diff --git a/NowCoder/2020RealTime/findPrime-byteDance.js b/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js similarity index 100% rename from NowCoder/2020RealTime/findPrime-byteDance.js rename to NowCoder/2020RealTime/byteDance/findPrime-byteDance.js diff --git a/NowCoder/2020RealTime/jumpGameX-byteDance.js b/NowCoder/2020RealTime/byteDance/jumpGameX-byteDance.js similarity index 100% rename from NowCoder/2020RealTime/jumpGameX-byteDance.js rename to NowCoder/2020RealTime/byteDance/jumpGameX-byteDance.js diff --git a/NowCoder/2020RealTime/vivo1.js b/NowCoder/2020RealTime/vivo/vivo1.js similarity index 100% rename from NowCoder/2020RealTime/vivo1.js rename to NowCoder/2020RealTime/vivo/vivo1.js diff --git a/NowCoder/2020RealTime/vivo2.js b/NowCoder/2020RealTime/vivo/vivo2.js similarity index 100% rename from NowCoder/2020RealTime/vivo2.js rename to NowCoder/2020RealTime/vivo/vivo2.js diff --git a/NowCoder/2020RealTime/vivo3.js b/NowCoder/2020RealTime/vivo/vivo3.js similarity index 100% rename from NowCoder/2020RealTime/vivo3.js rename to NowCoder/2020RealTime/vivo/vivo3.js diff --git a/NowCoder/2020RealTime/yuanfudao/1.js b/NowCoder/2020RealTime/yuanfudao/1.js new file mode 100644 index 0000000..0a41820 --- /dev/null +++ b/NowCoder/2020RealTime/yuanfudao/1.js @@ -0,0 +1,61 @@ +function processStr(numN,datas){ + let output = []; + + function proStr(str){ + let pdstr="" + let store = []; + state = false; + let count = ""; + for (let j = 0; j < str.length; j++) { + let temp = str[j]; + if(temp>='0'&& temp<='9'){ + count += temp; + state= true; + // console.log(count); + }else if(temp === '('){ + count = ""; + pdstr += store.join(''); + store=[]; + }else if(temp === ')'){ + count=""; + state = true; + }else{ + if(count !=='' && state){ + // console.log(count); + let tstr = ''; + let add = Number(count); + cstr = store.join(''); + let k=0; + while(ka-b); + let i=1,j=arr.length-1; + function checkSort(array){ + let stat = true; + for (let j = 1; j < array.length; j++) { + if(array[j]=arr[i-1] && arr[j-1]=arr[i-1] && arr[j-1]>arr[j]){ + i++; + }else { + let tempArr = arr.slice(i-1,j+1); + countArr = [...arr.slice(0,i-1),...tempArr.reverse(),...arr.slice(j+1,arr.length)]; + if(checkSort(countArr)){ + state = true; + } + break; + } + } + + if(state){ + return 'yes'; + }else { + return 'no'; + } +} + +// let arr = [2,1,3,4]; +let arr = [1,2,3,8,4,6,5,9]; +console.log(checkArray(arr)); + + +// var n = readInt(); +// var arr = []; +// while (arr.length < n) { +// arr.push(readInt()); +// } + + +// let numN = readInt() +// let datas = read_line().split(' '); +// let arr = []; +// for(let i=0;iparseInt(a)); + dataB.map((a)=>parseInt(a)); + dataA.sort((a,b)=>a-b); + dataB.sort((a,b)=>a-b); + output = [...dataA,...dataB]; + let only = [...new Set(output)]; + only.sort((a,b)=>a-b); + return only.join(' '); + // return [...new Set(output)].sort((a,b)=>a-b).join(' '); +} + + + +// let dataA = [11, 18, 42, 47, 56, 64, 69, 75, 79, 81, 87, 95, 97, 106, 118, 122, 124, 125, 127, 136, 145, 148, 156, 175]; +// let dataB = [3, 5, 18, 22, 25, 37, 41, 43, 50, 52, 60, 76, 83, 103, 114, 118, 120, 132, 133, 134, 147, 161]; +let dataA = strone.split(' '); +let dataB = strtwo.split(' '); + +console.log(processData(dataA,dataB)); + + + +function processData2(dataA,dataB){ + let output = []; + dataA = dataA.map((a)=>parseInt(a)); + dataB = dataB.map((a)=>parseInt(a)); + // dataA.sort((a,b)=>a-b); + // dataB.sort((a,b)=>a-b); + output = [...dataA,...dataB]; + let only =Array.from(new Set(output)); + only.sort((a,b)=>a-b); + return only.join(' '); +} + + +// 错误的读取方式 +// ACMCODER JavaScript 处理过程一次read_line()只能读取 1024 个字符,需要使用 readInt() 来读取指定个数字 +let data,aB,numA,numB,dataA,dataB; +while(data=read_line()){ + aB = data.split(' '); + if(aB.length===2){ + numA = parseInt(aB[0]); + numB = parseInt(aB[1]); + dataA = read_line().trim().split(' '); + dataB = read_line().trim().split(' '); + print(processData2(dataA,dataB)); + } +} + + +// 正确的读取方式 + +let data,aB,numA,numB,dataA,dataB; +while(data=read_line()){ + aB = data.split(' '); + if(aB.length===2){ + numA = parseInt(aB[0]); + numB = parseInt(aB[1]); + dataA = []; + // 确定多少数字,就读多少数字 + while(numA>0){ + dataA.push(readInt()); + numA--; + } + dataB = []; + while(numB>0){ + dataB.push(readInt()); + numB--; + } + print(processData(dataA,dataB)); + } +} \ No newline at end of file From bd46e92ad6a8411e8d8b230797597f28a89f5ae3 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 5 Aug 2019 10:30:27 +0800 Subject: [PATCH 252/274] =?UTF-8?q?yfd=E5=AD=97=E6=AF=8D=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E5=B1=95=E5=BC=80=E6=AD=A3=E5=88=99=E8=A1=A8=E8=BE=BE=E5=BC=8F?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/yfd/1.js | 123 +++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 NowCoder/2020RealTime/yfd/1.js diff --git a/NowCoder/2020RealTime/yfd/1.js b/NowCoder/2020RealTime/yfd/1.js new file mode 100644 index 0000000..9477cc1 --- /dev/null +++ b/NowCoder/2020RealTime/yfd/1.js @@ -0,0 +1,123 @@ +/****** + * + * 字母压缩展开 + * + * "A2B" => "AAB" + * "D((A2B)2)2B" => "DAABAABAABAABB" + * + * + * + */ + + +// 此方法不通过 +function processStr(numN,datas){ + let output = []; + + function proStr(str){ + let pdstr="" + let store = []; + state = false; + let count = ""; + for (let j = 0; j < str.length; j++) { + let temp = str[j]; + if(temp>='0'&& temp<='9'){ + count += temp; + state= true; + // console.log(count); + }else if(temp === '('){ + count = ""; + pdstr += store.join(''); + store=[]; + }else if(temp === ')'){ + count=""; + state = true; + }else{ + if(count !=='' && state){ + // console.log(count); + let tstr = ''; + let add = Number(count); + cstr = store.join(''); + let k=0; + while(k Date: Mon, 5 Aug 2019 16:15:38 +0800 Subject: [PATCH 253/274] Create findMaxGun.js --- .../RealInterviewExamination/findMaxGun.js | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 NowCoder/RealInterviewExamination/findMaxGun.js diff --git a/NowCoder/RealInterviewExamination/findMaxGun.js b/NowCoder/RealInterviewExamination/findMaxGun.js new file mode 100644 index 0000000..dc7a6c1 --- /dev/null +++ b/NowCoder/RealInterviewExamination/findMaxGun.js @@ -0,0 +1,87 @@ +function findMax(numN,numM,Guns,plugins){ + let max = 0; + function findGuns(gun){ + let temp = parseFloat(gun[0]); + let tempNum = parseInt(gun[1]); + let times = 1; + for(let m=0;mplugins.get(tempData[0])){ + plugins.set(tempData[0],tempData[1]); + } + }else{ + plugins.set(tempData[0],tempData[1]); + } +} +print(findMax(numN,numM,Guns,plugins)) + + + + + + + +function findMax(numN,numM,Guns,plugins){ + let max = 0; + + for(let k=0;kparseFloat(state)){ + plugins[tempData[0]]=tempData[1]; + } + }else{ + plugins[tempData[0]]=tempData[1]; + } + } + print(findMax(numN,numM,Guns,plugins)); +} \ No newline at end of file From e372056fb9eff5a43edd80d02576403be941c0ba Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 7 Aug 2019 17:11:04 +0800 Subject: [PATCH 254/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=87=A0=E9=81=93?= =?UTF-8?q?=E7=AE=80=E5=8D=95=E7=9A=84=E7=AE=97=E6=B3=95=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2019SchoolInterview/huawei/16to10.js | 17 +++++ .../2019SchoolInterview/huawei/diffandSort.js | 35 ++++++++++ .../huawei/findMaxBottle.js | 19 ++++++ .../2019SchoolInterview/kuaishou/zipStr.js | 43 ++++++++++++ .../mogujie/blockSolution.js | 66 +++++++++++++++++++ 5 files changed, 180 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/huawei/16to10.js create mode 100644 NowCoder/2019SchoolInterview/huawei/diffandSort.js create mode 100644 NowCoder/2019SchoolInterview/huawei/findMaxBottle.js create mode 100644 NowCoder/2019SchoolInterview/kuaishou/zipStr.js create mode 100644 NowCoder/2019SchoolInterview/mogujie/blockSolution.js diff --git a/NowCoder/2019SchoolInterview/huawei/16to10.js b/NowCoder/2019SchoolInterview/huawei/16to10.js new file mode 100644 index 0000000..fa65063 --- /dev/null +++ b/NowCoder/2019SchoolInterview/huawei/16to10.js @@ -0,0 +1,17 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-07 16:48:28 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-07 16:48:28 + */ + + +function process(str){ + return parseInt(str); +} +let str; +while(str=readline()){ + if(str){ + print(process(str)); + } +} \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/huawei/diffandSort.js b/NowCoder/2019SchoolInterview/huawei/diffandSort.js new file mode 100644 index 0000000..a9d6750 --- /dev/null +++ b/NowCoder/2019SchoolInterview/huawei/diffandSort.js @@ -0,0 +1,35 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-07 16:38:53 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-07 16:44:14 + */ + + +function diffandSort(arr){ + let afterArr=[]; + for(let j=0;ja-b); + return afterArr; +} + +let numN; +while(numN=readline()){ + numN = parseInt(numN); + let arr = []; + let temp; + for(let i=0;i Date: Thu, 8 Aug 2019 20:15:10 +0800 Subject: [PATCH 255/274] =?UTF-8?q?=E5=8D=8E=E4=B8=BA=E7=9A=84=E4=B8=89?= =?UTF-8?q?=E9=81=93=E7=AC=94=E8=AF=95=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/huawei/0807/1.js | 38 ++++++++++++++ NowCoder/2020RealTime/huawei/0807/2.js | 49 +++++++++++++++++++ NowCoder/2020RealTime/huawei/0807/3.js | 13 +++++ NowCoder/2020RealTime/huawei/0807/test.js | 36 ++++++++++++++ .../28.moreThanHalfNum_Solution.js | 1 + 5 files changed, 137 insertions(+) create mode 100644 NowCoder/2020RealTime/huawei/0807/1.js create mode 100644 NowCoder/2020RealTime/huawei/0807/2.js create mode 100644 NowCoder/2020RealTime/huawei/0807/3.js create mode 100644 NowCoder/2020RealTime/huawei/0807/test.js diff --git a/NowCoder/2020RealTime/huawei/0807/1.js b/NowCoder/2020RealTime/huawei/0807/1.js new file mode 100644 index 0000000..c811f9f --- /dev/null +++ b/NowCoder/2020RealTime/huawei/0807/1.js @@ -0,0 +1,38 @@ +function processStr(str){ + let allStr = str.split('@'); + let hadStr = allStr[1]; + let initStr = allStr[0]; + if(hadStr.length===0){ + return initStr; + } + let dics = initStr.split(','); + let initMap = new Map(); + for (let i = 0; i < dics.length; i++) { + let tempData = dics[i].split(':'); + initMap.set(tempData[0],parseInt(tempData[1])); + } + let used = hadStr.split(','); + for (let j = 0; j < used.length; j++) { + let tempDataU = used[j].split(':'); + let hadNum = initMap.get(tempDataU[0]); + if(hadNum-parseInt(tempDataU[1])>0){ + initMap.set(tempDataU[0],hadNum-parseInt(tempDataU[1])); + }else{ + initMap.delete(tempDataU[0]); + } + } + let output=""; + for(let [key,value] of initMap){ + output+= key+':'+value+','; + } + output = output.substring(0,output.length-1); + return output; +} + +let str = readline(); +print(processStr(str)); + +// let str = "a:3,b:5,c:2@a:1,b:2"; +let str = "a:3,b:5,c:2@a:3,b:2"; +console.log(processStr(str)); + diff --git a/NowCoder/2020RealTime/huawei/0807/2.js b/NowCoder/2020RealTime/huawei/0807/2.js new file mode 100644 index 0000000..600ce53 --- /dev/null +++ b/NowCoder/2020RealTime/huawei/0807/2.js @@ -0,0 +1,49 @@ +function findKeyValue(numM,labels,hasChild,pouds,values,keys){ + + let store = []; + let leafNodes = []; + let leafValues = []; + for (let i = 0; i < hasChild.length; i++) { + if(hasChild[i]===0){ + leafNodes.push(i); + leafValues.push(labels[i]); + } + + } + let lastLabel = keys[keys.length-1]; + if(leafValues.indexOf(lastLabel)===-1){ + return 0; + } + + for (let k = 0; k < leafValues.length; k++) { + if(leafValues[k]===lastLabel){ + return values[k]; + } + } + +} + + + + + + +// let numM = parseInt(readline()); +// let labels = readline().split(' '); +// let hasChild = readline().split(' '); +// let pouds = readline().split(' '); +// let numV = parseInt(readline()); +// let values = readline().split(' '); +// let numK = parseInt(readline()); +// let keys = readline().split(' '); + +let numM = 15; +let labels = [115,112,116,97,111,121,114,101,107,112,121,114,102,115,116]; +let hasChild = [0,0,0,1,1,0,1,0,0,0,1,1,1,1]; +let pouds = [1,1,0,1,0,1,1,1,0,0,0,1,1,0,0]; +let numV = 8; +let values = [1,2,3,4,5,6,7,8]; +let numK = 3; +let keys = [116,114,112]; +// console.log(object); +console.log(findKeyValue(numM,labels,hasChild,pouds,values,keys)) diff --git a/NowCoder/2020RealTime/huawei/0807/3.js b/NowCoder/2020RealTime/huawei/0807/3.js new file mode 100644 index 0000000..46a1e16 --- /dev/null +++ b/NowCoder/2020RealTime/huawei/0807/3.js @@ -0,0 +1,13 @@ + + +function process(str){ + let data = eval(str); + if(data){ + return 1; + }else{ + return 0; + } +} + +let str = readline(); +print(process(str)); diff --git a/NowCoder/2020RealTime/huawei/0807/test.js b/NowCoder/2020RealTime/huawei/0807/test.js new file mode 100644 index 0000000..4cfdee9 --- /dev/null +++ b/NowCoder/2020RealTime/huawei/0807/test.js @@ -0,0 +1,36 @@ +var M = parseInt(readline()); +var labels = readline().split(" "); +var hasChild = readline().split(" "); +var pouds = readline().split(" "); +var N = parseInt(readline()); +var values = readline().split(" "); +var P = parseInt(readline()); +var key = readline().split(" "); +let i = 0; +while(i < P){ + let temp = key[i]; + let index = labels.indexOf(temp); + if(index > -1){ + if(i == P-1){ + if(hasChild[index] == 0){ + let count = 0; + for(let j = 0; j < index; j++){ + if(hasChild[j]==0){ + count ++; + } + } + print(+values[count]); + }else{ + print(0); + } + }else{ + if(hasChild[index] == 1 ){ + i++; + }else{ + print(0); + } + } + }else{ + print(0); + } +} \ No newline at end of file diff --git a/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js b/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js index 2a3a806..8ba99a4 100644 --- a/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js +++ b/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js @@ -18,6 +18,7 @@ function MoreThanHalfNum_Solution(numbers) { } var countArr = []; for (let i = 0; i < numbers.length; i++) { + // countArr[numbers[i]] = countArr[numbers[i]]+1 || 1; if (countArr[numbers[i]]) { countArr[numbers[i]] = countArr[numbers[i]] + 1; if (countArr[numbers[i]] > numbers.length/2) { From 5d5ab7e0a540bd1cf23ece8f210524eaf03159fc Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sun, 11 Aug 2019 21:47:48 +0800 Subject: [PATCH 256/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E9=83=A8?= =?UTF-8?q?=E5=88=86=E7=AC=94=E8=AF=95=E9=A2=98=E7=9B=AE=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/EasyNetGame/1.java | 44 ++++++++++++++ NowCoder/2020RealTime/EasyNetGame/2.java | 57 +++++++++++++++++ NowCoder/2020RealTime/EasyNetGame/3.java | 68 +++++++++++++++++++++ NowCoder/2020RealTime/EasyNetGame/4.java | 53 ++++++++++++++++ NowCoder/2020RealTime/byteDance/0811-1.js | 74 +++++++++++++++++++++++ 5 files changed, 296 insertions(+) create mode 100644 NowCoder/2020RealTime/EasyNetGame/1.java create mode 100644 NowCoder/2020RealTime/EasyNetGame/2.java create mode 100644 NowCoder/2020RealTime/EasyNetGame/3.java create mode 100644 NowCoder/2020RealTime/EasyNetGame/4.java create mode 100644 NowCoder/2020RealTime/byteDance/0811-1.js diff --git a/NowCoder/2020RealTime/EasyNetGame/1.java b/NowCoder/2020RealTime/EasyNetGame/1.java new file mode 100644 index 0000000..753aed5 --- /dev/null +++ b/NowCoder/2020RealTime/EasyNetGame/1.java @@ -0,0 +1,44 @@ +import java.util.Scanner; +import java.util.ArrayList; +public class Main { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + while (in.hasNextInt()) { + int numT = in.nextInt(); + int count = 0; + int numN; + + while(count store = new ArrayList(); + int k =0; + for(int j=0;jm){ + cur=m; + } + } + } + return cur; + } + +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/EasyNetGame/3.java b/NowCoder/2020RealTime/EasyNetGame/3.java new file mode 100644 index 0000000..fa56f0f --- /dev/null +++ b/NowCoder/2020RealTime/EasyNetGame/3.java @@ -0,0 +1,68 @@ +import java.util.Scanner; +import java.util.ArrayList; +import java.util.List; +public class Main { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + while (in.hasNextInt()) { + int numT = in.nextInt(); + int count = 0; + while(count indexList = new ArrayList(); + for(int j=0;j maxN){ + maxN=tempMax; + } + } + } + return maxN; + } + public static int findMaxNumN(String[] strL){ + int max=0; + int count=0; + int lenL = strL.length; + for(int j=0;j max){ + max=count; + } + count=0; + }else{ + count++; + } + } + if(count>max){ + max=count; + } + return max; + } +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/EasyNetGame/4.java b/NowCoder/2020RealTime/EasyNetGame/4.java new file mode 100644 index 0000000..ac265e9 --- /dev/null +++ b/NowCoder/2020RealTime/EasyNetGame/4.java @@ -0,0 +1,53 @@ +import java.util.Scanner; +import java.util.ArrayList; +public class Main { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + while (in.hasNextLong()) { + long numN = in.nextLong(); + long count = 0; + long[] arr = new long[numN]; + while(countnum){ + sum++; + }else if(index==0&&arr[index]>num){ + sum=1; + } + index++; + } + return sum; + } +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/byteDance/0811-1.js b/NowCoder/2020RealTime/byteDance/0811-1.js new file mode 100644 index 0000000..201ab29 --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/0811-1.js @@ -0,0 +1,74 @@ +function findWaysSum(numN,arr){ + let output = [0,0,0]; + let store = []; + for (let i = 0; i < numN; i++) { + store[i]=[]; + for (let j = 0; j < numN; j++) { + store[i][j]=0; + } + } + for (let k = 0; k < arr.length; k++) { + let tempArr = arr[k]; + store[tempArr[0]-1][tempArr[1]-1]=1; + store[tempArr[1]-1][tempArr[0]-1]=1; + } + for (let i = 0; i < numN; i++) { + for (let j = i+1; j < numN; j++) { + if(store[i][j]===0){ + store[i][j]=findminPath(i,j); + } + addToSum(store[i][j]); + } + } + + function findminPath(a,b){ + if(store[a][b]!==0){ + return store[a][b]; + }else{ + if(store[a].indexOf(1)!==-1){ + let c = store[a].indexOf(1); + return 1+findminPath(c,b); + }else if(store[b].indexOf(1)!==-1){ + let c = store[b].indexOf(1); + return 1+findminPath(c,a); + }else{ + return 0; + } + } + } + + function addToSum(len){ + if(len%3==0){ + output[0]+=len; + }else if(len%3==1){ + output[1]+=len; + }else if(len%3==2){ + output[2]+=len; + } + } + let maxValue = Math.pow(10,9)+7; + for (let i = 0; i < output.length; i++) { + if(output[i]>maxValue){ + output[i]= output[i]%maxValue; + } + } + return output.join(' '); +} + +// let numN = parseInt(readline()); +// let arr = []; +// let count=1; +// while(count Date: Sun, 11 Aug 2019 22:12:28 +0800 Subject: [PATCH 257/274] =?UTF-8?q?=E6=95=B0=E7=BB=84=E5=B1=95=E5=BC=80?= =?UTF-8?q?=E6=8C=87=E5=AE=9A=E5=B1=82=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/pdd/flattenArr.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 NowCoder/2020RealTime/pdd/flattenArr.js diff --git a/NowCoder/2020RealTime/pdd/flattenArr.js b/NowCoder/2020RealTime/pdd/flattenArr.js new file mode 100644 index 0000000..8cfe1a3 --- /dev/null +++ b/NowCoder/2020RealTime/pdd/flattenArr.js @@ -0,0 +1,24 @@ +function flattenArr(arr,times){ + times = times || 1; + let result = []; + while (times>0) { + result = []; + for (let i = 0; i < arr.length; i++) { + if(Array.isArray(arr[i])){ + result = result.concat(arr[i]); + }else{ + result.push(arr[i]); + } + } + arr = result.slice(); + times--; + } + return result; +} + + +let arr = [1,2,[3,4],[5,[6,7]],[8,9],[[11,12,[13,14,[15,16],[17,18,[19,20,21]]]],[22,23,[24,25]]]]; +console.log(flattenArr(arr,1)); +// console.log(flattenArr(arr,2)); +// console.log(flattenArr(arr,3)); +// console.log(flattenArr(arr,4)); \ No newline at end of file From 09d84bc7d714c4fb4e2f4f456dee870745b89bdf Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 12 Aug 2019 22:21:01 +0800 Subject: [PATCH 258/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=87=A0=E9=81=93?= =?UTF-8?q?=E7=AE=97=E6=B3=95=E9=A2=98=E7=9A=84=E8=A7=A3=E9=A2=98=E6=80=9D?= =?UTF-8?q?=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2019SchoolInterview/mogujie/findWays.js | 62 ++++++++ .../2019SchoolInterview/mogujie/processStr.js | 29 ++++ NowCoder/2020RealTime/DJI/2.js | 64 +++++--- NowCoder/2020RealTime/beike/1.js | 31 ++++ NowCoder/2020RealTime/beike/2.js | 0 NowCoder/2020RealTime/beike/3.js | 137 ++++++++++++++++++ NowCoder/2020RealTime/pdd/flattenArr.js | 41 +++++- 7 files changed, 344 insertions(+), 20 deletions(-) create mode 100644 NowCoder/2019SchoolInterview/mogujie/findWays.js create mode 100644 NowCoder/2019SchoolInterview/mogujie/processStr.js create mode 100644 NowCoder/2020RealTime/beike/1.js create mode 100644 NowCoder/2020RealTime/beike/2.js create mode 100644 NowCoder/2020RealTime/beike/3.js diff --git a/NowCoder/2019SchoolInterview/mogujie/findWays.js b/NowCoder/2019SchoolInterview/mogujie/findWays.js new file mode 100644 index 0000000..eaeb2fb --- /dev/null +++ b/NowCoder/2019SchoolInterview/mogujie/findWays.js @@ -0,0 +1,62 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-12 22:03:17 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-12 22:06:25 + */ + + +/**** + * 蘑菇街 + * + * 有一个X*Y的网格,小团要在此网格上从左上角到右下角,只能走格点且只能向右或向下走。 + * 请设计一个算法,计算小团有多少种走法。给定两个正整数int x,int y,请返回小团的走法数目。 + * + * 输入描述 + * 输入包括一行,空格隔开的两个正整数x和y,取值范围[1,10]。 + * + * 输出描述 + * 输出一行,表示走法的数目 + * + * + * 动态规划的公式: + * + * dp[i][j]=dp[i-1][j]+dp[i][j-1] + * + * 附加条件: + * dp[0][j]=1; + * dp[i][0]=1; + * + * + */ + +function findWays(x,y){ + let dps = []; + for(let i=0;i<=x;i++){ + dps[i]=[]; + dps[i][0]=1; + for(let j=0;j<=y;j++){ + if(i===0){ + dps[i][j]=1; + } + } + } + for(let i=1;i<=x;i++){ + for(let j=1;j<=y;j++){ + dps[i][j]=dps[i-1][j]+dps[i][j-1]; + } + } + return dps[x][y]; +} + + + + +// let init = readline().split(' '); +// let x=parseInt(init[0]); +// let y=parseInt(init[1]); +// print(findWays(x,y)); + +let x=3; +let y=2; +console.log(findWays(x,y)); \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/mogujie/processStr.js b/NowCoder/2019SchoolInterview/mogujie/processStr.js new file mode 100644 index 0000000..3d367cc --- /dev/null +++ b/NowCoder/2019SchoolInterview/mogujie/processStr.js @@ -0,0 +1,29 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-07 10:39:50 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-12 22:20:37 + */ + + +function processStr(str){ + let output=[]; + let resStr = str.split('').reverse().join(''); + let len = str.length; + let left=0,right=0; + right = len-resStr.indexOf(str[0]); + for (let i = 0; i < len; i++) { + let sec = len-resStr.indexOf(str[i]); + if(i!==sec&&ib?a:b; + }else{ + dps[j][k]=dps[j-1][k]; + } + } + + } + return dps[len][maxValue]; +} +let datas = [26,5,6,15,37,63]; +let values = [100,1,2,25,48,97]; +let maxValue = 100; +console.log(zeroOnePackage(datas,values,maxValue)); +// 多重背包问题 @@ -101,20 +131,20 @@ console.log(processData(numN,numT,dataN)); // } -let initdata,numN,numT,temp; -while(initdata= read_line()){ - initdata = initdata.split(' '); - numN = parseInt(initdata[0]); - numT = parseInt(initdata[1]); - let temp = numN; - let dataN = []; - while(temp>0){ - let tempC = [] - tempC.push(readInt()); - tempC.push(readInt()); - tempC.push(readInt()); - dataN.push(tempC); - temp--; - } - print(processData(numN,numT,dataN)) -} \ No newline at end of file +// let initdata,numN,numT,temp; +// while(initdata= read_line()){ +// initdata = initdata.split(' '); +// numN = parseInt(initdata[0]); +// numT = parseInt(initdata[1]); +// let temp = numN; +// let dataN = []; +// while(temp>0){ +// let tempC = [] +// tempC.push(readInt()); +// tempC.push(readInt()); +// tempC.push(readInt()); +// dataN.push(tempC); +// temp--; +// } +// print(processData(numN,numT,dataN)) +// } \ No newline at end of file diff --git a/NowCoder/2020RealTime/beike/1.js b/NowCoder/2020RealTime/beike/1.js new file mode 100644 index 0000000..087b82f --- /dev/null +++ b/NowCoder/2020RealTime/beike/1.js @@ -0,0 +1,31 @@ +function findMinData(numN,arr){ + let output = []; + if(arr.length!==numN || numN<=2){ + return "" + } + function decNum(a,b){ + let numa = BigInt(a); + let numb = BigInt(b); + let result = numa-numb; + result = String(result); + return Math.abs(result); + + } + let min = decNum(arr[0],arr[1]); + output.push(arr[0]); + output.push(arr[1]); + + for(let i=2;imax){ + max=tempArr.length; + } + return; + }else{ + if(tArr.length===0){ + tArr.push(arr[index]); + let misArr = tArr.concat(); + dfs(index+1,misArr,arr); + }else{ + if(arr[index]>tArr[tArr.length-1]){ + let misArr = tArr.concat(); + misArr.push(arr[index]); + dfs(index+1,misArr,arr); + } + dfs(index+1,tArr,arr); + } + } + } + for(let i=0;imax){ + max=tempArr.length; + } + return; + }else{ + if(tempArr.length===0){ + tempArr.push(arr[index]); + dfs(index+1,tempArr,arr); + }else{ + if(arr[index]>tempArr[tempArr.length-1]){ + tempArr.push(arr[index]); + dfs(index+1,tempArr,arr); + } + dfs(index+1,tempArr,arr); + } + } + } + for(let i=0;iarr[j]){ + fs[i] = Math.max(fs[j]+1,fs[i]); + } + } + } + for (let k = 0; k < arr.length; k++) { + max = Math.max(max, fs[k]); + } + return max; +} + +console.time('LISUsingDP'); +console.log(LISUsingDP(arr)); // 0.457ms +console.timeEnd('LISUsingDP'); + + + +// 二分查找的思路 + +function LISbyBinSearch(arr){ + let mList = []; + mList[0]=Number.MAX_VALUE; + for (let i = 1; i <= arr.length; i++) { + mList[i] = Number.MAX_VALUE; + } + function binSearch(list,item){ + let start=0,end=list.length-1; + while(start0; k--) { + if(mList[k]!==Number.MAX_VALUE){ + return k; + } + } + return 1; +} + +console.time('LISbyBinSearch'); +console.log(LISbyBinSearch(arr)); // 0.472ms +console.timeEnd('LISbyBinSearch'); \ No newline at end of file diff --git a/NowCoder/2020RealTime/pdd/flattenArr.js b/NowCoder/2020RealTime/pdd/flattenArr.js index 8cfe1a3..3ec1d5f 100644 --- a/NowCoder/2020RealTime/pdd/flattenArr.js +++ b/NowCoder/2020RealTime/pdd/flattenArr.js @@ -17,8 +17,43 @@ function flattenArr(arr,times){ } -let arr = [1,2,[3,4],[5,[6,7]],[8,9],[[11,12,[13,14,[15,16],[17,18,[19,20,21]]]],[22,23,[24,25]]]]; -console.log(flattenArr(arr,1)); +// let arr = [1,2,[3,4],[5,[6,7]],[8,9],[[11,12,[13,14,[15,16],[17,18,[19,20,21]]]],[22,23,[24,25]]]]; +// console.log(flattenArr(arr,1)); // console.log(flattenArr(arr,2)); // console.log(flattenArr(arr,3)); -// console.log(flattenArr(arr,4)); \ No newline at end of file +// console.log(flattenArr(arr,4)); + + + +// 按次数,并非按层 +// 此时是按照层展开 +function flat (arr, depth){ + let res = [], + depthArg = depth || 1, + depthNum = 0, + flatMap = (arr) => { + arr.map((element, index, array) => { + if(Object.prototype.toString.call(element).slice(8, -1) === "Array"){ + if( depthNum < depthArg ) { + depthNum++; + // console.log(depthNum); + flatMap(element); + }else{ + res.push(element); + } + }else { + res.push(element); + } + if( index === array.length -1 ) { + // console.log('times'); + // 每处理一次数组,就把深度重新置零 + depthNum = 0; + } + }); + }; + flatMap(arr); + return res; +} +var arr = [1,2,[3,4],[5,[6,7],6,[6,7],6,7],8,[9,10],11]; +// console.log(flat(arr,1)); +console.log(flattenArr(arr,1)); \ No newline at end of file From bd5aece972c8b8c8e19ce9e0a38673f309cf8d67 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 13 Aug 2019 10:25:21 +0800 Subject: [PATCH 259/274] =?UTF-8?q?=E5=88=86=E5=89=B2=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2019SchoolInterview/mogujie/processStr.js | 50 +++++++++++++++---- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/NowCoder/2019SchoolInterview/mogujie/processStr.js b/NowCoder/2019SchoolInterview/mogujie/processStr.js index 3d367cc..193b1d5 100644 --- a/NowCoder/2019SchoolInterview/mogujie/processStr.js +++ b/NowCoder/2019SchoolInterview/mogujie/processStr.js @@ -2,26 +2,56 @@ * @Author: SkylineBin * @Date: 2019-08-07 10:39:50 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-08-12 22:20:37 + * @Last Modified time: 2019-08-13 10:24:56 */ +/**** + * + * 题目描述:给定一个由小写字母组成的字符串s,请将其分割成尽量多的子串,并保证每个字母最多只在其中一个子串中出现。 + * 请返回由一个或多个整数表示的分割后各子串的长度。 + * + * 输入描述:来自标准输入的一行由小写字母组成的字符串。 + * + * 输出描述:字符串最优分割后各子串的长度,多个数字之间由空格分隔。 + * + * 输入: + * ababbacadefgdehijhklij + * + * 输出: + * 8 6 8 + * + * + */ + + + function processStr(str){ let output=[]; let resStr = str.split('').reverse().join(''); let len = str.length; - let left=0,right=0; - right = len-resStr.indexOf(str[0]); + let storeB=[]; + let left,right; + for (let i = 0; i < len; i++) { - let sec = len-resStr.indexOf(str[i]); - if(i!==sec&&ia[0]-b[0]); + output.push(storeB[0]); + let lt,rt,index; + for (let j = 1; j < storeB.length; j++) { + lt = storeB[j][0]; + rt = storeB[j][1]; + index = output.length-1; + if(lt<=output[index][1]&&rt>=output[index][1]){ + output[index][1]=rt; + }else if(lt>output[index][1]){ + output.push(storeB[j]); } - } - - - + let outside = output.map((a)=>a[1]-a[0]+1); + return outside; } From 4126aacd190c7a92ac1370068834422fee7aaeb3 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Tue, 13 Aug 2019 11:53:19 +0800 Subject: [PATCH 260/274] =?UTF-8?q?=E5=88=86=E7=B3=96=E6=9E=9C=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2019SchoolInterview/mogujie/minCandy.js | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/mogujie/minCandy.js diff --git a/NowCoder/2019SchoolInterview/mogujie/minCandy.js b/NowCoder/2019SchoolInterview/mogujie/minCandy.js new file mode 100644 index 0000000..12297b2 --- /dev/null +++ b/NowCoder/2019SchoolInterview/mogujie/minCandy.js @@ -0,0 +1,95 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-13 10:57:56 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-13 11:28:07 + */ + +/******** + * + * 有N个孩子站成一排,每个孩子有一个分值。给这些孩子派发糖果,需要满足如下需求: + * 1、每个孩子至少分到一个糖果 + * 2、分值更高的孩子比他相邻位的孩子获得更多的糖果 + * 求至少需要分发多少糖果? + * + * + * 输入描述: + * 0,1,0 + * 输出描述: + * 4 + * + * 输入: + * 5,4,1,1 + * + * 输出: + * 7 + * + * + */ + + +function minCandy(datas){ + let len = datas.length; + let candys = new Array(len); + if(len===2){ + if(datas[0]!==datas[1]){ + return 3; + }else{ + return 2; + } + } + if(len===1){ + return 1; + } + candys[len-1]=1; + // 用于修正已经分配的糖果 + function reflow(index,arr){ + arr[index]=1; + let len=arr.length; + let store=[]; + index++; + store.push(index); + while(index=0;i--){ + if(datas[i]>datas[i+1]){ + candys[i]=candys[i+1]+1; + }else if(datas[i]===datas[i+1]){ + candys[i]=candys[i+1]; + }else{ + if(candys[i+1]>1){ + // 注意为了最小化,这里一定要给1,贪心的思想 + // candys[i]=candys[i+1]-1; + candys[i]=1; + }else{ + candys=reflow(i,candys); + } + } + } + // console.log(datas); + // console.log(candys); + let sum=candys.reduce((a,b)=>a+b); + return sum; +} + +// let datas=[2,3,4,1,5,6,2,1]; // 15 +let datas=[2,3,4,9,6,8,4,3,2]; // 21 +// let datas=[2,3,4,1,5,6,2,1]; // 15 +// let datas=[5,4,1,1]; // 7 +// let datas=[2,8,3,6]; // 6 + +console.log(minCandy(datas)); \ No newline at end of file From 053c16e857cddd11227fef00200bf8d57f831cab Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 16 Aug 2019 21:41:28 +0800 Subject: [PATCH 261/274] =?UTF-8?q?=E9=83=A8=E5=88=86=E7=AC=94=E8=AF=95?= =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=98=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/360/1.js | 0 NowCoder/2020RealTime/baidu/baidu.js | 14 ++++++++++ NowCoder/2020RealTime/vivo/vivo3.js | 10 ++++--- NowCoder/2020RealTime/yfd/2.js | 39 ++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 NowCoder/2020RealTime/360/1.js create mode 100644 NowCoder/2020RealTime/baidu/baidu.js create mode 100644 NowCoder/2020RealTime/yfd/2.js diff --git a/NowCoder/2020RealTime/360/1.js b/NowCoder/2020RealTime/360/1.js new file mode 100644 index 0000000..e69de29 diff --git a/NowCoder/2020RealTime/baidu/baidu.js b/NowCoder/2020RealTime/baidu/baidu.js new file mode 100644 index 0000000..2b11494 --- /dev/null +++ b/NowCoder/2020RealTime/baidu/baidu.js @@ -0,0 +1,14 @@ +function getUsers(nums,num){ + let output=[]; + let index=0; + while(index Date: Fri, 16 Aug 2019 21:43:14 +0800 Subject: [PATCH 262/274] =?UTF-8?q?Promise=E5=BC=82=E6=AD=A5=E4=B8=8E?= =?UTF-8?q?=E5=B9=B6=E5=8F=91=E7=9A=84=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/yfd/3.js | 64 ++++++++++++++++++++++++++++ NowCoder/2020RealTime/yfd/4.js | 17 ++++++++ NowCoder/2020RealTime/yfd/example.js | 28 ++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 NowCoder/2020RealTime/yfd/3.js create mode 100644 NowCoder/2020RealTime/yfd/4.js create mode 100644 NowCoder/2020RealTime/yfd/example.js diff --git a/NowCoder/2020RealTime/yfd/3.js b/NowCoder/2020RealTime/yfd/3.js new file mode 100644 index 0000000..7e1b629 --- /dev/null +++ b/NowCoder/2020RealTime/yfd/3.js @@ -0,0 +1,64 @@ +function batchLoad(urls, concurrency){ + let res=[]; + let len = urls.length; + let index=0; + let current=[]; + return new Promise((resolve,reject)=>{ + + function processData(){ + if(index===len){ + return Promise.resolve(); + } + const url = urls[index++]; + let p = load(url); // load 的返回是一个Promise + res.push(p); + let e = p.then(()=>current.splice(current.indexOf(e),1)); + // 有一个promise执行完毕,就从当前数组中删除这个 + current.push(e); + let r = Promise.resolve(); + // 如果当前的并发数少于限定的大小时,使用 r 实例新的 promise 并执行 + if(current.length>=concurrency){ + r = Promise.race(current); + // 如果超过并发的限制,需要等待有promise 完成后再开始新的连接 + } + return r.then(()=> processData()); + } + + processData().then(()=> resolve(Promise.all(res))); + }) + +} + + +function load(url){ + return new Promise((rs,rj)=>{ + setTimeout(()=>{ + // rs() or rj(); + rs(url); + },100) + }) +} + +batchLoad(['a','b','c'],2).then(data => { + // data = [a,err,c]; + console.log(data); +}) + + + // for(let i=0;i{ + // res[i]=res; + // count--; + // index++; + // }).catch((err)=>{ + // res[i]=err; + // count--; + // }); + + // } + // if(index===len-1){ + // state=false; + // } + // } \ No newline at end of file diff --git a/NowCoder/2020RealTime/yfd/4.js b/NowCoder/2020RealTime/yfd/4.js new file mode 100644 index 0000000..90db9cc --- /dev/null +++ b/NowCoder/2020RealTime/yfd/4.js @@ -0,0 +1,17 @@ +Array.prototype.copySlice= function(i,j){ + let arr = this; + i = i || 0; + j = j || arr.length; + let res = []; + for (let k = 0; k < arr.length; k++) { + if(k>=i&&k iteratorFn(item, array)); + // 放入promises数组 + ret.push(p); + // promise执行完毕,从executing数组中删除 + const e = p.then(() => executing.splice(executing.indexOf(e), 1)); + // 插入executing数字,表示正在执行的promise + executing.push(e); + // 使用Promise.rece,每当executing数组中promise数量低于poolLimit,就实例化新的promise并执行 + let r = Promise.resolve(); + if (executing.length >= poolLimit) { + r = Promise.race(executing); + } + // 递归,直到遍历完array + return r.then(() => enqueue()); + }; + return enqueue().then(() => Promise.all(ret)); +} \ No newline at end of file From 8cb93e5af0db4ba23f7a85f9fee2d6d804425677 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Sat, 17 Aug 2019 22:19:56 +0800 Subject: [PATCH 263/274] =?UTF-8?q?=E8=85=BE=E8=AE=AF=E7=AC=94=E8=AF=95?= =?UTF-8?q?=E9=A2=98=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/tx/1.js | 106 +++++++++++++++++++++++++++++++++ NowCoder/2020RealTime/tx/2.js | 27 +++++++++ NowCoder/2020RealTime/tx/3.js | 19 ++++++ NowCoder/2020RealTime/tx/4.js | 39 ++++++++++++ NowCoder/2020RealTime/tx/5.js | 40 +++++++++++++ NowCoder/2020RealTime/yfd/1.js | 2 - 6 files changed, 231 insertions(+), 2 deletions(-) create mode 100644 NowCoder/2020RealTime/tx/1.js create mode 100644 NowCoder/2020RealTime/tx/2.js create mode 100644 NowCoder/2020RealTime/tx/3.js create mode 100644 NowCoder/2020RealTime/tx/4.js create mode 100644 NowCoder/2020RealTime/tx/5.js diff --git a/NowCoder/2020RealTime/tx/1.js b/NowCoder/2020RealTime/tx/1.js new file mode 100644 index 0000000..4610519 --- /dev/null +++ b/NowCoder/2020RealTime/tx/1.js @@ -0,0 +1,106 @@ +function processArr(datas){ + let output = []; + + function strRegExp(str){ + let pStr = str; + let regexp1 = /[a-zA-Z][0-9]+/; //匹配字符后面是数字的 + let regexp2 = /\(\w*\)[0-9]+/; // 匹配括号后面是数字的 + + // 处理掉字符后面是数字的情况 + let turnOne = pStr.match(regexp1); + while(turnOne!== null){ + let matchStr = turnOne[0]; + let rStr = matchStr[0]; + let len = matchStr.length; + let times = parseInt(matchStr.substring(1,len)); + pStr = pStr.replace(matchStr, rStr.repeat(times)); + turnOne = pStr.match(regexp1); + } + + // 处理括号后面是数字的情况 + let turnTwo = pStr.match(regexp2); + while(turnTwo!== null){ + let matchStr = turnTwo[0]; + let proStr = matchStr.split(')'); + let rStr = proStr[0].substring(1,proStr[0].length); + let times = parseInt(proStr[1]); + pStr = pStr.replace(matchStr, rStr.repeat(times)); + turnTwo = pStr.match(regexp2); + } + return pStr; + } + + + for (let i = 0; i < datas.length; i++) { + output.push(strRegExp(datas[i])); + } + return output; + +} + + +function strRegExp(str){ + let pStr = str; + let regexp1 = /\[[0-9]+\|[A-Z]+\]/; //匹配字符后面是数字的 + // let regexp2 = /\(\w*\)[0-9]+/; // 匹配括号后面是数字的 + + // 处理掉字符后面是数字的情况 + let turnOne = pStr.match(regexp1); + console.log(turnOne); + while(turnOne!== null){ + let matchStr = turnOne[0]; + let datas = matchStr.split('|'); + let rStr = datas[1].substring(0,datas[1].length-1); + let times = parseInt(datas[0].substring(1,datas[0].length)); + pStr = pStr.replace(matchStr, rStr.repeat(times)); + turnOne = pStr.match(regexp1); + } + + // let turnOne = pStr.match(regexp1); + // while(turnOne!== null){ + // let matchStr = turnOne[0]; + // let rStr = matchStr[0]; + // let len = matchStr.length; + // let times = parseInt(matchStr.substring(1,len)); + // pStr = pStr.replace(matchStr, rStr.repeat(times)); + // turnOne = pStr.match(regexp1); + // } + + // // 处理括号后面是数字的情况 + // let turnTwo = pStr.match(regexp2); + // while(turnTwo!== null){ + // let matchStr = turnTwo[0]; + // let proStr = matchStr.split(')'); + // let rStr = proStr[0].substring(1,proStr[0].length); + // let times = parseInt(proStr[1]); + // pStr = pStr.replace(matchStr, rStr.repeat(times)); + // turnTwo = pStr.match(regexp2); + // } + return pStr; +} + +let str ="HG[3|B[2|CA]]F"; + +console.log(strRegExp(str)); + + +function processStr(str){ + let pStr = str; + let regexp1 = /\[[0-9]+\|[A-Z]+\]/; + let turnOne = pStr.match(regexp1); + while(turnOne!== null){ + let matchStr = turnOne[0]; + let datas = matchStr.split('|'); + let rStr = datas[1].substring(0,datas[1].length-1); + let times = parseInt(datas[0].substring(1,datas[0].length)); + pStr = pStr.replace(matchStr, rStr.repeat(times)); + turnOne = pStr.match(regexp1); + } + return pStr; +} + + + + +// let str = readline(); +// print(processStr(str)) \ No newline at end of file diff --git a/NowCoder/2020RealTime/tx/2.js b/NowCoder/2020RealTime/tx/2.js new file mode 100644 index 0000000..8b50d97 --- /dev/null +++ b/NowCoder/2020RealTime/tx/2.js @@ -0,0 +1,27 @@ + +function isPrivate(ip){ + // TODO + // if(ip==="127.0.0.0"||ip==="127.0.0.8"){ + // return true; + // } + let regexpCy = /127.0.0.[0-8]/; + if(regexpCy.test(ip)){ + return true; + } + let regexpA = /10(.((\d{1,2})|(1\d{1,2})|2([0-4]\d)|(25[0-5]))){3}/; + if(regexpA.test(ip)){ + return true; + } + let regexpB = /172.(1[6-9]|2\d|3[01])(.((\d{1,2})|(1\d{1,2})|2([0-4]\d)|(25[0-5]))){2}/; + if(regexpB.test(ip)){ + return true; + } + let regexpC = /192.168(.((\d{1,2})|(1\d{1,2})|2([0-4]\d)|(25[0-5]))){2}/; + if(regexpC.test(ip)){ + return true; + } + return false; +} + +let ip="0.0.0.0"; +console.log(isPrivate(ip)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/tx/3.js b/NowCoder/2020RealTime/tx/3.js new file mode 100644 index 0000000..b5d4530 --- /dev/null +++ b/NowCoder/2020RealTime/tx/3.js @@ -0,0 +1,19 @@ +function camel(str) { + // TODO + let outStr=""; + let len = str.length; + let state=false; + for(let i=0;inumN){ + ts=ts-numN; + } + if(startN<=ts&&endN>ts){ + return true; + }else{ + return false; + } + } + for(let s=1;s<=numN;s++){ + let tCount=0; + for(let i=0;icount){ + time=s; + count=tCount; + } + } + + return time; +} + +let numN=3; +let numAs=[2,5,6]; +let numU=1; +let numV=3; +console.log(maxNumberofMeeting(numN,numAs,numU,numV)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/tx/5.js b/NowCoder/2020RealTime/tx/5.js new file mode 100644 index 0000000..e13a5c2 --- /dev/null +++ b/NowCoder/2020RealTime/tx/5.js @@ -0,0 +1,40 @@ +function minTimes(n,m,x,y,datas){ + let row=m; + let col=n; + let count =0; + let withiw = 0; + let withib =0; + let state; + for (let i = 0; i < row; i++) { + let numb=0; + let numw=0; + for (let j = 0; j < col; j++) { + if(datas[j][i]==="#"){ + numb++; + }else if(datas[j][i]==="."){ + numw++; + } + } + if(numb=x&&withiw=x&&withib Date: Fri, 23 Aug 2019 16:49:32 +0800 Subject: [PATCH 264/274] =?UTF-8?q?=E6=89=BE=E7=B4=A0=E6=95=B0=E7=9A=84?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../byteDance/findPrime-byteDance.js | 91 ++++++++++++++++++- 1 file changed, 88 insertions(+), 3 deletions(-) diff --git a/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js b/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js index 8b4b813..0ce752b 100644 --- a/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js +++ b/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js @@ -2,7 +2,7 @@ * @Author: SkylineBin * @Date: 2019-06-30 21:53:06 * @Last Modified by: SkylineBin - * @Last Modified time: 2019-06-30 22:18:58 + * @Last Modified time: 2019-08-23 16:41:27 */ @@ -39,5 +39,90 @@ function findPrime(N) { return list.join(' '); } -let N=10; -console.log(findPrime(N)); \ No newline at end of file +// let N=10; +// console.log(findPrime(N)); + +// 以上算法复杂度为 O(N^2) + +// 简化思路 + +// 方法二,简化原理,只需要判断 从 2~x^(1/2) 是否存在一个数能被x整除 +// 使用 j*j <= i 替代 j<=parseInt(Math.sqrt(x)) 可以降低计算的时间复杂度 +function findPrime2(N) { + let list = []; + if(N<=2){ + return list.join(' '); + } + var i = 2, j = 2; + let state; + while(i Date: Fri, 23 Aug 2019 16:50:22 +0800 Subject: [PATCH 265/274] =?UTF-8?q?Bilibili2020=E6=A0=A1=E6=8B=9B=E7=BC=96?= =?UTF-8?q?=E7=A8=8B=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/Bilibili/1.js | 13 +++++++++++ NowCoder/2020RealTime/Bilibili/2.js | 33 ++++++++++++++++++++++++++++ NowCoder/2020RealTime/Bilibili/3.js | 34 +++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 NowCoder/2020RealTime/Bilibili/1.js create mode 100644 NowCoder/2020RealTime/Bilibili/2.js create mode 100644 NowCoder/2020RealTime/Bilibili/3.js diff --git a/NowCoder/2020RealTime/Bilibili/1.js b/NowCoder/2020RealTime/Bilibili/1.js new file mode 100644 index 0000000..1671b7a --- /dev/null +++ b/NowCoder/2020RealTime/Bilibili/1.js @@ -0,0 +1,13 @@ +function findWays(n){ + if(n===1||n===2){ + return n; + }else{ + return findWays(n-1)+findWays(n-2); + } +} + +// let n=parseInt(readline()); +// print(findWays(n)); + +let n=9; +console.log(findWays(n)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/Bilibili/2.js b/NowCoder/2020RealTime/Bilibili/2.js new file mode 100644 index 0000000..83db1d8 --- /dev/null +++ b/NowCoder/2020RealTime/Bilibili/2.js @@ -0,0 +1,33 @@ +function findDataofSum(numN,nums,sumD){ + let output=[]; + let before=0; + let after=numN-1; + while(beforesumD){ + after--; + }else{ + output.push(nums[before]); + output.push(nums[after]); + break; + } + } + if(output.length===0){ + return "notfound"; + }else{ + return output.join(" "); + } +} + +// let numN = parseInt(readline()); +// let nums=[]; +// let count=0; +// let datas = readline().split(' '); +// while(count Date: Mon, 26 Aug 2019 09:08:26 +0800 Subject: [PATCH 266/274] update --- DataStructures/Sort/binSearch.js | 12 +++ NowCoder/2020RealTime/beike/0823/1.js | 40 +++++++++ NowCoder/2020RealTime/beike/0823/2.js | 34 ++++++++ NowCoder/2020RealTime/beike/0823/3.js | 42 ++++++++++ NowCoder/2020RealTime/beike/0823/4.js | 61 ++++++++++++++ NowCoder/2020RealTime/jd/1.js | 115 ++++++++++++++++++++++++++ NowCoder/2020RealTime/jd/2.js | 53 ++++++++++++ NowCoder/2020RealTime/mt/1.js | 38 +++++++++ 8 files changed, 395 insertions(+) create mode 100644 DataStructures/Sort/binSearch.js create mode 100644 NowCoder/2020RealTime/beike/0823/1.js create mode 100644 NowCoder/2020RealTime/beike/0823/2.js create mode 100644 NowCoder/2020RealTime/beike/0823/3.js create mode 100644 NowCoder/2020RealTime/beike/0823/4.js create mode 100644 NowCoder/2020RealTime/jd/1.js create mode 100644 NowCoder/2020RealTime/jd/2.js create mode 100644 NowCoder/2020RealTime/mt/1.js diff --git a/DataStructures/Sort/binSearch.js b/DataStructures/Sort/binSearch.js new file mode 100644 index 0000000..e7f8c9e --- /dev/null +++ b/DataStructures/Sort/binSearch.js @@ -0,0 +1,12 @@ +function binSearch(left,right,val,arr){ + + let mid = left + parseInt((right-left)/2); + if(valarr[mid]){ + return binSearch(mid+1,right,val,arr); + }else{ + return mid; + } + return -1; +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/beike/0823/1.js b/NowCoder/2020RealTime/beike/0823/1.js new file mode 100644 index 0000000..95a8c24 --- /dev/null +++ b/NowCoder/2020RealTime/beike/0823/1.js @@ -0,0 +1,40 @@ +function strCycle(sArr,nArr){ + let output=[]; + function cycleStr(str,num){ + if(num===0){ + return str; + }else{ + let tstr= str.substring(str.length-1,str.length)+str.substring(0,str.length-1); + return cycleStr(tstr,num-1); + } + } + for (let i = 0; i < sArr.length; i++) { + output.push(cycleStr(sArr[i],nArr[i])); + } + return output; +} + +let num = readInt(); +let sArr=[]; +let nArr=[]; +let count=0; +while(counta-b); + for(let i = 0; i < c.length; i++) { + sum+=c[i]; + if(sum=tempD[1]){ + sum+=tempD[1]; + count++; + } + tC++; + } + } + return count; +} + + + + +let n=readInt(); +let m=readInt(); +let arrs=[]; +for (let i = 0; i < n; i++) { + arrs[i]=[]; + arrs[i].push(readInt()); + arrs[i].push(readInt()); +} + +print(maxNums(n,m,arrs)); + + + +let n = 4; +let m = 100; +let arrs=[ + [3,40], + [3,6], + [1,1], + [1,5] +]; +console.log(maxNums(n,m,arrs)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/beike/0823/4.js b/NowCoder/2020RealTime/beike/0823/4.js new file mode 100644 index 0000000..d6235f7 --- /dev/null +++ b/NowCoder/2020RealTime/beike/0823/4.js @@ -0,0 +1,61 @@ +function maxSub(n,things){ + let sum=0,maxS=0,minS=0; + things.sort((a,b)=>a-b); + sum = things.reduce((a,b)=>a+b,0); + let left=sum,right=0; + let len=things.length; + for (let k = len-1; k >=0; k--) { + let tS = Math.abs(left-right); + right+=things[k]; + left-=things[k]; + if(Math.abs(left-right)>tS){ + minS=tS; + maxS = len-k-1; + break; + } + } + return [minS,maxS].join(" "); +} + + + +// let n=readInt(); +// let things=[]; +// for (let i = 0; i < n; i++) { +// things.push(readInt()); +// } +// print(maxSub(n,things)) + + +// let n=6; +// let things=[1,2,3,4,5,6]; +// console.log(maxSub(n,things)); + + + + + + + +function maxSub2(n,things){ + let sum=0,maxS=0,minS=0; + let sumLeft=0,sumRight=0; + let len=things.length; + let left=0,right=len-1; + while(left<=right){ + if(sumLeft="a"&&s<="z"){ + return true; + }else{ + return false; + } + } + let onceC=1; + for(let i=0;i="a"&&s<="z"){ + return true; + }else{ + return false; + } + } + // let bC=0,lC=0; + // for (let k = 0; k < n; k++) { + // if(str[k]!==copyBigStr[k]){ + // bC++; + // } + // if(str[k]!==copyLittleStr[k]){ + // lC++; + // } + // } + + // if(bC>lC){ + // for (let j = 0; j < n; j++) { + + + // } + + + // }else{ + // count+=1; + // for(let i=0;ib[1]-a[1]); + let sDatas = []; + let tempSData = [store[0][0]]; + for (let i = 1; i < store.length; i++) { + if(store[i][1]===store[i-1][1]){ + let tempA=tempSData.concat(store[i][0]); + if(i===store.length-1){ + sDatas.push(tempA); + } + }else{ + sDatas.push(tempSData.slice()); + tempSData=[store[i][0]]; + } + } + for (let j = 0; j < sDatas.length; j++) { + let tempD = sDatas[j]; + for (let q = 0; q < copyArr.length; q++) { + let temp = copyArr[q].split(' '); + if(tempD.indexOf(temp[0])!==-1){ + output.push(copyArr[q]); + } + } + } + return output; +} + + +let arr=[ + "ZHANG SAN", + "LI SI", + "WANG WU", + "WANG LIU", + "WANG QI", + "ZHANG WU", + "LI WU" +]; +console.log(sortNames(arr)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/mt/1.js b/NowCoder/2020RealTime/mt/1.js new file mode 100644 index 0000000..3879b82 --- /dev/null +++ b/NowCoder/2020RealTime/mt/1.js @@ -0,0 +1,38 @@ +function BSTree(){ + + let Node = function(val){ + this.val = val; + this.left = null; + this.right = null; + } + + let root = null; + + let insertNewNode = function(rootNode, node){ + if(node.val < rootNode.val){ + if(rootNode.left === null){ + rootNode.left = node; + }else{ + insertNewNode(rootNode.left, node); + } + }else { + if(rootNode.right === null){ + rootNode.right = node; + }else{ + insertNewNode(rootNode.right, node); + } + } + } + + this.insert = function(val){ + let newNode = new Node(val); + if(root===null){ + root = newNode; + }else{ + insertNewNode(root,newNode); + } + } +} + +let TreeWalker = new BSTree(); +TreeWalker.insert(1); \ No newline at end of file From 61176fed753d544287fd8e9be81ea53a7c5f138e Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 26 Aug 2019 09:08:51 +0800 Subject: [PATCH 267/274] neteasy --- NowCoder/2020RealTime/mt/2.js | 0 NowCoder/2020RealTime/neteasy/1.js | 14 ++++++++++++ NowCoder/2020RealTime/neteasy/2.js | 29 ++++++++++++++++++++++++ NowCoder/2020RealTime/neteasy/3.js | 15 +++++++++++++ NowCoder/2020RealTime/neteasy/4.js | 36 ++++++++++++++++++++++++++++++ 5 files changed, 94 insertions(+) create mode 100644 NowCoder/2020RealTime/mt/2.js create mode 100644 NowCoder/2020RealTime/neteasy/1.js create mode 100644 NowCoder/2020RealTime/neteasy/2.js create mode 100644 NowCoder/2020RealTime/neteasy/3.js create mode 100644 NowCoder/2020RealTime/neteasy/4.js diff --git a/NowCoder/2020RealTime/mt/2.js b/NowCoder/2020RealTime/mt/2.js new file mode 100644 index 0000000..e69de29 diff --git a/NowCoder/2020RealTime/neteasy/1.js b/NowCoder/2020RealTime/neteasy/1.js new file mode 100644 index 0000000..f2861f2 --- /dev/null +++ b/NowCoder/2020RealTime/neteasy/1.js @@ -0,0 +1,14 @@ +function maxNum(numA,numB){ + if(numB === 0){ + return numA; + }else { + return maxNum(numB, numA % numB); + } +} + + + + +let numA = 7951346523609888 +let numB =6998915114363550; +console.log(maxNum(numA,numB)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/neteasy/2.js b/NowCoder/2020RealTime/neteasy/2.js new file mode 100644 index 0000000..1e6f52f --- /dev/null +++ b/NowCoder/2020RealTime/neteasy/2.js @@ -0,0 +1,29 @@ + +function findMininMax(numN,data){ + let output = []; + + function findMax(){ + + } + function findMin(){ + + } + + function getMinofMaxNum(data,k){ + let tempArr = data.slice(0); + let store = []; + for(let j=0;j<=data.length-k;j++){ + let arr = data.slice(j,j+k); + store.push(Math.max(...arr)); + } + return Math.min(...store); + } + for(let i=1;i<=numN;i++){ + output.push(getMinofMaxNum(data,i)) + } + return output; +} + +let numN = 6; +let data = [1, 3, 2, 4, 6, 5]; +console.log(findMininMax(numN,data)); diff --git a/NowCoder/2020RealTime/neteasy/3.js b/NowCoder/2020RealTime/neteasy/3.js new file mode 100644 index 0000000..2200a8a --- /dev/null +++ b/NowCoder/2020RealTime/neteasy/3.js @@ -0,0 +1,15 @@ +function findDicSort(numN,data){ + let output; + output = data.slice(0); + let tempState = data[0]%2===0?true:false; + for (let i = 1; i < numN; i++) { + if(data[i]%2===0 && !tempState){ + return output.sort((a,b)=>a-b); + } + } + return output; +} + +let numN = 10; +let data = [53941, 38641, 31525, 75864, 29026, 12199, 83522, 58200, 64784, 80987]; +console.log(findDicSort(numN,data)); diff --git a/NowCoder/2020RealTime/neteasy/4.js b/NowCoder/2020RealTime/neteasy/4.js new file mode 100644 index 0000000..30d17ea --- /dev/null +++ b/NowCoder/2020RealTime/neteasy/4.js @@ -0,0 +1,36 @@ +function findAnswer(numN,numQ,dataInit,ques){ + let countArr = []; + for (let j = 0; j < ques.length; j++) { + let count = 0; + for (let i = 0; i < dataInit.length; i++) { + if(dataInit[i]>=ques[j]){ + dataInit[i]-=1; + count++; + } + } + countArr.push(count); + } + return countArr; +} + +let numN=4,numQ=3,dataInit=[1,2,3,4],ques=[4,3,1]; +console.log(findAnswer(numN,numQ,dataInit,ques)); + + +// 4 3 +// 1 2 3 4 +// 4 +// 3 +// 1 + + +for(let j=0;j Date: Sun, 1 Sep 2019 16:00:57 +0800 Subject: [PATCH 268/274] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=80=E6=B3=A2?= =?UTF-8?q?=E5=AE=9E=E6=97=B6=E7=AE=97=E6=B3=95=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2019SchoolInterview/huawei/sortArr.js | 6 ++ .../kuaishou/longthNonRepeatSubString.js | 21 ++++++ .../kuaishou/maxCommonLength.js | 39 +++++++++++ .../kuaishou/minDepthofFabonaciiNum.js | 12 ++++ .../2019SchoolInterview/neteasy/threeNums.js | 44 ++++++++++++ NowCoder/2020RealTime/neteasy/video1.js | 32 +++++++++ NowCoder/2020RealTime/pufa/1.js | 25 +++++++ NowCoder/2020RealTime/pufa/2.js | 36 ++++++++++ NowCoder/2020RealTime/pufa/lanOne.js | 25 +++++++ NowCoder/2020RealTime/pufa/lanThree.js | 15 ++++ NowCoder/2020RealTime/pufa/lanTwo.js | 23 +++++++ NowCoder/2020RealTime/pufa/xiangThree.js | 67 ++++++++++++++++++ NowCoder/2020RealTime/sina/1.html | 69 +++++++++++++++++++ NowCoder/2020RealTime/sina/2.html | 43 ++++++++++++ 14 files changed, 457 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/huawei/sortArr.js create mode 100644 NowCoder/2019SchoolInterview/kuaishou/longthNonRepeatSubString.js create mode 100644 NowCoder/2019SchoolInterview/kuaishou/maxCommonLength.js create mode 100644 NowCoder/2019SchoolInterview/kuaishou/minDepthofFabonaciiNum.js create mode 100644 NowCoder/2019SchoolInterview/neteasy/threeNums.js create mode 100644 NowCoder/2020RealTime/neteasy/video1.js create mode 100644 NowCoder/2020RealTime/pufa/1.js create mode 100644 NowCoder/2020RealTime/pufa/2.js create mode 100644 NowCoder/2020RealTime/pufa/lanOne.js create mode 100644 NowCoder/2020RealTime/pufa/lanThree.js create mode 100644 NowCoder/2020RealTime/pufa/lanTwo.js create mode 100644 NowCoder/2020RealTime/pufa/xiangThree.js create mode 100644 NowCoder/2020RealTime/sina/1.html create mode 100644 NowCoder/2020RealTime/sina/2.html diff --git a/NowCoder/2019SchoolInterview/huawei/sortArr.js b/NowCoder/2019SchoolInterview/huawei/sortArr.js new file mode 100644 index 0000000..46478a2 --- /dev/null +++ b/NowCoder/2019SchoolInterview/huawei/sortArr.js @@ -0,0 +1,6 @@ +function sortArr(arr){ + + +} + +let arr=[2,1,5,4,3,7,9,8,6]; \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/kuaishou/longthNonRepeatSubString.js b/NowCoder/2019SchoolInterview/kuaishou/longthNonRepeatSubString.js new file mode 100644 index 0000000..a59cf49 --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/longthNonRepeatSubString.js @@ -0,0 +1,21 @@ +function maxLengthofSub(str){ + let max=1; + if(!str||str.length===0){ + return 0; + } + for(let i=0;imaxCommon){ + maxCommon=tempStr.length; + } + } + } + } + return maxCommon; +} + + + + + +let inits=readline().split(','); +let str1=inits[0]; +let str2=inits[1]; +print(maxCommonLength(str1,str2)) \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/kuaishou/minDepthofFabonaciiNum.js b/NowCoder/2019SchoolInterview/kuaishou/minDepthofFabonaciiNum.js new file mode 100644 index 0000000..edf81f3 --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/minDepthofFabonaciiNum.js @@ -0,0 +1,12 @@ +function minDepth(num){ + let before=0,after=1; + while(before<=num&&after<=num){ + after+=before; + before=after-before; + } + return Math.min(Math.abs(before-num),Math.abs(after-num)); +} + + +let num = parseInt(readline()); +print(minDepth(num)); \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/neteasy/threeNums.js b/NowCoder/2019SchoolInterview/neteasy/threeNums.js new file mode 100644 index 0000000..8ca4d53 --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasy/threeNums.js @@ -0,0 +1,44 @@ +function countThreeNums(left,right){ + let count=0; + while(left<=right){ + let tN=''; + let tc=1; + let num; + while(tc<=left){ + tN+=tc; + tc++; + } + // num=parseInt(tN); + // console.log(num); + let tNums = tN.split('').map((a)=>parseInt(a)); + num = tNums.reduce((a,b)=>a+b,0); + if(num%3===0){ + count++; + } + left++; + } + return count; +} + +// let left=2; +// let right=5; +let left=10; +let right=110; +console.log(countThreeNums(left,right)); + + +// 复杂度稍降的写法 +// 只需要计算序号 +// i%3=1 不能被整除 +// i%3=2 可以被整除 +// i%3=0 可以被整除 +function countThreeNums2(left,right){ + let count=0; + while(left<=right){ + if(left%3!==1){ + count++; + } + left++; + } + return count; +} diff --git a/NowCoder/2020RealTime/neteasy/video1.js b/NowCoder/2020RealTime/neteasy/video1.js new file mode 100644 index 0000000..9fd705b --- /dev/null +++ b/NowCoder/2020RealTime/neteasy/video1.js @@ -0,0 +1,32 @@ + + + + + + +// 实现事件的防抖 + + + +// 二叉树的广度优先遍历的非递归的写法 + + +// 二叉树的广度优先遍历的递归的写法 +function printBinTree(head,layer){ + layer = layer || 0; + let store=[]; + if(head===null){ + return null; + } + if(!store[layer]){ + store[layer]=[head.val]; + }else{ + store[layer].push(head); + } + if(store.left!==null){ + printBinTree(store.left,layer+1); + } + if(store.right!==null){ + printBinTree(store.right,layer+1); + } +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/pufa/1.js b/NowCoder/2020RealTime/pufa/1.js new file mode 100644 index 0000000..9d2f4a3 --- /dev/null +++ b/NowCoder/2020RealTime/pufa/1.js @@ -0,0 +1,25 @@ +function duplicate(numbers, duplication) +{ + // write code here + //这里要特别注意~找到任意重复的一个值并赋值到duplication[0] + //函数返回True/False + var temparr = {}; + for (let i = 0; i < numbers.length; i++) { + if (temparr[numbers[i]]) { + temparr[numbers[i]]++; + // console.log(temparr); + // if (temparr[numbers[i]] === 2) { + // duplication[0] = numbers[i]; + // return true; + // } + } else { + temparr[numbers[i]] = 1; + } + } + console.log(temparr); + return false; +} + +let numbers='abdshkjfbasdghdg'.split(''); +let s=[]; +console.log(duplicate(numbers, s)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/pufa/2.js b/NowCoder/2020RealTime/pufa/2.js new file mode 100644 index 0000000..0ebd9b1 --- /dev/null +++ b/NowCoder/2020RealTime/pufa/2.js @@ -0,0 +1,36 @@ +var minarr = []; +var arr = []; + +function push(node) { + arr.push(node); + if (minarr.length === 0) { + minarr.push(node); + } else { + if (node < minarr[0]) { + minarr.unshift(node); + } else { + minarr.unshift(minarr[0]); + } + } +} + +function pop() { + arr.pop(); + minarr.shift(); +} + +function top() { + return arr[0]; +} + +function min() { + return minarr[0]; +} + + +push(1); +push(2); +push(3); +console.log(min()); +push(0); +console.log(min()); \ No newline at end of file diff --git a/NowCoder/2020RealTime/pufa/lanOne.js b/NowCoder/2020RealTime/pufa/lanOne.js new file mode 100644 index 0000000..03159f8 --- /dev/null +++ b/NowCoder/2020RealTime/pufa/lanOne.js @@ -0,0 +1,25 @@ +function processStr(str){ + var store = new Map(); + var len = str.length; + for (let i = 0; i < len; i++) { + if(store.get(str[i])){ + store.set(str[i],store.get(str[i])+1); + }else{ + store.set(str[i],1); + } + } + var arrs=[]; + for(let [key,values] of store){ + arrs.push([values,String(key).repeat(values)]); + } + arrs.sort((a,b)=>b[0]-a[0]); + let output=''; + for (let j = 0; j < arrs.length; j++) { + output+=arrs[j][1]; + } + return output; + +} + +let str = "abcfdfajfdfsfdbfbafafd"; +console.log(processStr(str)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/pufa/lanThree.js b/NowCoder/2020RealTime/pufa/lanThree.js new file mode 100644 index 0000000..fe83f69 --- /dev/null +++ b/NowCoder/2020RealTime/pufa/lanThree.js @@ -0,0 +1,15 @@ +function countTimes(n){ + if(n===1){ + return 0; + }else{ + if(n%2===0){ + n=n/2; + }else{ + n=((n*3)+1)/2; + } + return 1+countTimes(n); + } +} + +let n =28; +console.log(countTimes(n)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/pufa/lanTwo.js b/NowCoder/2020RealTime/pufa/lanTwo.js new file mode 100644 index 0000000..d2936fe --- /dev/null +++ b/NowCoder/2020RealTime/pufa/lanTwo.js @@ -0,0 +1,23 @@ +function processStr(str){ + var count=0; + var len = str.length; + var temp=''; + if(str[0]>='0'&&str[0]<='9'){ + temp=str[0]; + } + for (let i = 1; i < len; i++) { + if(str[i]>='0'&&str[i]<='9'){ + temp+=str[i]; + }else{ + if(temp.length>0){ + count+=parseInt(temp); + temp=''; + } + } + } + return count; + +} + +let str = "abc24fdfajf435d43fsf34dbfb324afafd"; +console.log(processStr(str)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/pufa/xiangThree.js b/NowCoder/2020RealTime/pufa/xiangThree.js new file mode 100644 index 0000000..60c6635 --- /dev/null +++ b/NowCoder/2020RealTime/pufa/xiangThree.js @@ -0,0 +1,67 @@ +function addTwoNums(num1,num2){ + let res=''; + let copyN1=String(num1).split(''); + let copyN2=String(num2).split(''); + let state=0; + let output=[]; + while(copyN1.length>0&©N2.length>0){ + let t1=parseInt(copyN1.pop()); + let t2=parseInt(copyN2.pop()); + let temp=t1+t2+state; + if(temp>=10){ + temp= temp%10; + state=1; + }else{ + state=0; + } + output.push(temp); + } + if(copyN1.length>0&©N2.length===0){ + if(state){ + while(copyN1.length>0){ + temp=parseInt(copyN1.pop())+state; + if(temp>=10){ + temp= temp%10; + state=1; + }else{ + state=0; + } + output.push(temp); + } + }else{ + while(copyN1.length>0){ + output.push(copyN1.pop()); + } + } + } + if(copyN2.length>0&©N1.length===0){ + if(state){ + while(copyN2.length>0){ + temp=parseInt(copyN2.pop())+state; + if(temp>=10){ + temp= temp%10; + state=1; + }else{ + state=0; + } + output.push(temp); + } + }else{ + while(copyN2.length>0){ + output.push(copyN2.pop()); + } + } + } + if(state){ + output.push(state); + } + res=output.reverse().join(''); + return res; +} + +// let num1='788927347946'; +// let num2='80388927348946'; +let num1='11'; +let num2='19'; + +console.log(addTwoNums(num1,num2)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/sina/1.html b/NowCoder/2020RealTime/sina/1.html new file mode 100644 index 0000000..81e7a92 --- /dev/null +++ b/NowCoder/2020RealTime/sina/1.html @@ -0,0 +1,69 @@ + + + + + + CSS Keyframe + + + + +
+
+
+ + + + \ No newline at end of file diff --git a/NowCoder/2020RealTime/sina/2.html b/NowCoder/2020RealTime/sina/2.html new file mode 100644 index 0000000..9dd777f --- /dev/null +++ b/NowCoder/2020RealTime/sina/2.html @@ -0,0 +1,43 @@ + + + + + + KeyFrame Clock + + + + +
+
+
+ + + \ No newline at end of file From 64d479800d5890d94f401a4dc083076faf99a86b Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Thu, 5 Sep 2019 20:38:47 +0800 Subject: [PATCH 269/274] add some algorithms --- Leetcode/14.LongestCommonPrefix.js | 125 ++++++++++++++++++ .../2019SchoolInterview/weipinhui/strAdd.js | 83 ++++++++++++ .../xiaomi/stringOfXiaoming.js | 18 +++ NowCoder/2020RealTime/xiaohongshu/1.js | 39 ++++++ NowCoder/2020RealTime/xiaohongshu/2.js | 51 +++++++ 5 files changed, 316 insertions(+) create mode 100644 Leetcode/14.LongestCommonPrefix.js create mode 100644 NowCoder/2019SchoolInterview/weipinhui/strAdd.js create mode 100644 NowCoder/2019SchoolInterview/xiaomi/stringOfXiaoming.js create mode 100644 NowCoder/2020RealTime/xiaohongshu/1.js create mode 100644 NowCoder/2020RealTime/xiaohongshu/2.js diff --git a/Leetcode/14.LongestCommonPrefix.js b/Leetcode/14.LongestCommonPrefix.js new file mode 100644 index 0000000..853e43b --- /dev/null +++ b/Leetcode/14.LongestCommonPrefix.js @@ -0,0 +1,125 @@ +/* + * @Author: SkylineBin + * @Date: 2019-09-05 12:47:36 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-09-05 13:01:14 + */ + + +/**** + * + * + * 一组字符串的最长公共顺序子串 + * + * 要从头开始,有一个不一样就终止判断 + * + * + */ + + +var longestCommonPrefix = function(strs) { + if(strs.length===0){ + return ''; + }else if(strs.length===1){ + return strs[0]; + } + strs.sort((a,b)=>a.length-b.length); + let len = strs[0].length; + let max=0,res=''; + let initStr = strs[0]; + let i=0; + for(let j=i+1;j<=len;j++){ + let state=true; + let temp = initStr.substring(i,j); + for(let k=1;kmax){ + max=temp.length; + res=temp; + } + }else{ + break; + } + } + return res; +}; + +let strs=["c","c"]; +console.log(longestCommonPrefix(strs)); + + +/***** + * + * Leetcode 上别人的更优解 + * + * + * + */ + +function longestCommonPrefix(strs){ + if(!strs || (strs.length===0)){ + return ""; + } + strs.sort((a,b)=>a.length-b.length); + const first=strs[0]; + if(!first){ + return ""; + } + let prefix=""; + first.split('').every((strC,index)=>{ + if(strs.every(str => str[index]===strC)){ + prefix+= strC; + return true; + }else{ + return false; + } + }); + return prefix; +} + + + + + + + +/**** + * + * 一组字符串中的所有公共连续子串,,不一定从头开始 + * + * + */ +var longestCommonPrefixNonSort = function(strs) { + if(strs.length===0){ + return ''; + }else if(strs.length===1){ + return strs[0]; + } + strs.sort((a,b)=>a.length-b.length); + let len = strs[0].length; + let max=0,res=''; + let initStr = strs[0]; + for(let i=0;imax){ + max=temp.length; + res=temp; + } + } + } + } + return res; +}; \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/weipinhui/strAdd.js b/NowCoder/2019SchoolInterview/weipinhui/strAdd.js new file mode 100644 index 0000000..4b5bdf3 --- /dev/null +++ b/NowCoder/2019SchoolInterview/weipinhui/strAdd.js @@ -0,0 +1,83 @@ +/* + * @Author: SkylineBin + * @Date: 2019-09-01 16:06:49 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-09-01 16:07:24 + */ + + +/**** + * + * 二进制字符串相加 + * + * + */ + +function addTwoStringNums(str1,str2){ + let res=''; + let copyN1=str1.split(''); + let copyN2=str2.split(''); + let state=0; + let output=[]; + while(copyN1.length>0&©N2.length>0){ + let t1=parseInt(copyN1.pop()); + let t2=parseInt(copyN2.pop()); + let temp=t1+t2+state; + if(temp>=2){ + temp= temp%2; + state=1; + }else{ + state=0; + } + output.push(temp); + } + if(copyN1.length>0&©N2.length===0){ + if(state){ + while(copyN1.length>0){ + temp=parseInt(copyN1.pop())+state; + if(temp>=2){ + temp= temp%2; + state=1; + }else{ + state=0; + } + output.push(temp); + } + }else{ + while(copyN1.length>0){ + output.push(copyN1.pop()); + } + } + } + if(copyN2.length>0&©N1.length===0){ + if(state){ + while(copyN2.length>0){ + temp=parseInt(copyN2.pop())+state; + if(temp>=2){ + temp= temp%2; + state=1; + }else{ + state=0; + } + output.push(temp); + } + }else{ + while(copyN2.length>0){ + output.push(copyN2.pop()); + } + } + } + if(state){ + output.push(state); + } + res=output.reverse().join(''); + return res; +} + + + + +let datas=readline().split(' '); +let str1=datas[0]; +let str2=datas[1]; +print(addTwoStringNums(str1,str2)) \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/xiaomi/stringOfXiaoming.js b/NowCoder/2019SchoolInterview/xiaomi/stringOfXiaoming.js new file mode 100644 index 0000000..7ae51a2 --- /dev/null +++ b/NowCoder/2019SchoolInterview/xiaomi/stringOfXiaoming.js @@ -0,0 +1,18 @@ +function changeStr(strs,num){ + return strs.slice(strs.length-num,strs.length)+strs.slice(0,strs.length-num); +} + +let inits=readline().split(' '); +let N = parseInt(inits[0]); +let T = parseInt(inits[1]); +let strs=readline(); +let count=0; +while(count0){ + output.pop(); + } + + } + } + return output.join(''); +} + + +let str="a<{ + return (a[0]+a[1])-(b[0]+b[1]); + }); + copy2.sort((a,b)=>(a[1]-b[1])); + console.log(copy1); + console.log(copy2); + var count1=1; + var tempS=copy1[0]; + for(var j=1;j=tempS[0]&©1[j][1]>=tempS[1]){ + tempS=copy1[j]; + count1++; + } + } + var count2=1; + var tempS2=copy2[0]; + for(var j=1;j=tempS2[0]&©2[j][1]>=tempS2[1]){ + tempS2=copy2[j]; + count2++; + } + } + return Math.max(count1,count2)+1; +} + + +var num=4; +var xArr=[3,1,1,2]; +var hArr=[2,1,3,2]; +console.log(maxCount(num,xArr,hArr)); + + +// var num; +// while(num=readInt()){ +// var count=0; +// var xArr=[]; +// var hArr=[]; +// while(count Date: Fri, 13 Sep 2019 10:46:40 +0800 Subject: [PATCH 270/274] =?UTF-8?q?=E9=83=A8=E5=88=86=E7=9C=9F=E9=A2=98?= =?UTF-8?q?=E8=A7=A3=E9=A2=98=E8=BF=87=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NowCoder/2020RealTime/byteDance/0908/2.js | 23 +++++ NowCoder/2020RealTime/byteDance/exam | 0 NowCoder/2020RealTime/exams/1.js | 108 ++++++++++++++++++++++ NowCoder/2020RealTime/exams/2.js | 60 ++++++++++++ NowCoder/2020RealTime/exams/3.java | 28 ++++++ NowCoder/2020RealTime/exams/3.js | 24 +++++ NowCoder/2020RealTime/exams/4.js | 22 +++++ NowCoder/2020RealTime/huawei/0907/1.js | 37 ++++++++ NowCoder/2020RealTime/huawei/0907/2.js | 40 ++++++++ NowCoder/2020RealTime/huawei/0907/3.js | 39 ++++++++ NowCoder/2020RealTime/pufa/xiangThree.js | 3 + TestProjects/ACMOJ/qunaer/1.js | 83 +++++++++++++++++ 12 files changed, 467 insertions(+) create mode 100644 NowCoder/2020RealTime/byteDance/0908/2.js create mode 100644 NowCoder/2020RealTime/byteDance/exam create mode 100644 NowCoder/2020RealTime/exams/1.js create mode 100644 NowCoder/2020RealTime/exams/2.js create mode 100644 NowCoder/2020RealTime/exams/3.java create mode 100644 NowCoder/2020RealTime/exams/3.js create mode 100644 NowCoder/2020RealTime/exams/4.js create mode 100644 NowCoder/2020RealTime/huawei/0907/1.js create mode 100644 NowCoder/2020RealTime/huawei/0907/2.js create mode 100644 NowCoder/2020RealTime/huawei/0907/3.js create mode 100644 TestProjects/ACMOJ/qunaer/1.js diff --git a/NowCoder/2020RealTime/byteDance/0908/2.js b/NowCoder/2020RealTime/byteDance/0908/2.js new file mode 100644 index 0000000..dc61435 --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/0908/2.js @@ -0,0 +1,23 @@ +function findMinTimes(x,y,z,k){ + [x,y,z] = [x,y,z].sort((a,b)=>a-b);// 从小到大排序后赋值 + function twoTimes(a,b,k){ // 两个数就装满k的次数 + let count=0; + let temp=a; + while(temp%b!==k){ + count+=2; + temp+=a; + count++; + } + return count; + } + return Math.min.apply(null,[twoTimes(x,y,k),twoTimes(x,z,k),twoTimes(x,z,k)]); // 求三个数里面两个两个求取的最小值 +} + + + + +let x=3; +let y=5; +let z=8; +let k=4; +console.log(findMinTimes(x,y,z,k)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/byteDance/exam b/NowCoder/2020RealTime/byteDance/exam new file mode 100644 index 0000000..e69de29 diff --git a/NowCoder/2020RealTime/exams/1.js b/NowCoder/2020RealTime/exams/1.js new file mode 100644 index 0000000..80f7ab8 --- /dev/null +++ b/NowCoder/2020RealTime/exams/1.js @@ -0,0 +1,108 @@ +function findLastTurn(num){ + var m =5; + var n=num; + var output; + if (n===0 || m===0) { + return -1; + } + let lucky = []; + let currentList = []; + let tempLen = 0; + for (let i = 0; i < n; i++) { + currentList.push(i); + } + adjustArr = function (arr, tempNo) { + let tempTable = []; + for (let k = 0; k < arr.length; k++) { + if (k > tempNo) { + tempTable.push(arr[k]); + } + } + for (let j = 0; j < tempNo; j++) { + tempTable.push(arr[j]); + } + return tempTable; + } + for (let i = 0; i < n; i++) { + tempLen = currentList.length; + let tempWho = 0; + if (m >= tempLen) { + tempWho = (m-1) % tempLen; + } else { + tempWho = m-1; + } + lucky.push(currentList[tempWho]); + currentList = adjustArr(currentList, tempWho); + } + + output = lucky.indexOf(num-1)+1; + + + return output; +} + + +// var num; +// while(num = readInt()){ +// print(findLastTurn(num)); +// } + + + + +// var num = readInt(); +// print(findLastTurn(num)); + +// var num = 8; +// console.log(findLastTurn(num)); + + + + + + + +function findLastTurn2(num){ + var m = 5; + var n=num; + if (n===0) { + return 0; + } + let lucky = []; + let currentList = []; + let tempLen = 0; + for (let i = 0; i < n; i++) { + currentList.push(i); + } + for (let i = 0; i < n; i++) { + tempLen = currentList.length; + let tempWho = 0; + if (m >= tempLen) { + tempWho = (m-1) % tempLen; + } else { + tempWho = m-1; + } + lucky.push(currentList[tempWho]); + if(currentList[tempWho]===num-1){ + break; + } + currentList = [].concat(currentList.slice(tempWho+1,currentList.length),currentList.slice(0,tempWho)); + } + return lucky.length; +} + + +// var num; +// while(num = readInt()){ +// print(findLastTurn(num)); +// } + + +var num = 1000; +console.log(findLastTurn2(num)); + +// let count=0; +// for (let j = 0; j < num; j++) { +// if(num%5==0) + +// } \ No newline at end of file diff --git a/NowCoder/2020RealTime/exams/2.js b/NowCoder/2020RealTime/exams/2.js new file mode 100644 index 0000000..12f0188 --- /dev/null +++ b/NowCoder/2020RealTime/exams/2.js @@ -0,0 +1,60 @@ +function minChangeTimes(num,arrA,arrB){ + var minTimes=Number.MAX_VALUE; + if(num==1&&arrA[0]===arrB[0]){ + return 0; + } + + var dp=[]; + for (let j = 0; j < num; j++) { + dp[j]=0; + } + var temp; + for (let i = 0; i < num; i++) { + temp=Number.MAX_VALUE; + for (let k = 0; k < num; k++) { + temp = Math.min(temp,dp[k]); + dp[k]=Math.abs(k-arrB.indexOf(arrA[k]))+temp; + } + } + + return dp[num-1]; +} + + +var num; +while(num=readInt()){ + var arrA=[]; + var arrB=[]; + var count=0; + while(counta===arrayB[index]); +} + + + + + +var num=4; +var arrA=[4,2,1,3]; +var arrB=[3,2,4,1]; + +console.log(minChangeTimes(num,arrA,arrB)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/exams/3.java b/NowCoder/2020RealTime/exams/3.java new file mode 100644 index 0000000..6b9048b --- /dev/null +++ b/NowCoder/2020RealTime/exams/3.java @@ -0,0 +1,28 @@ +public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + + int cnt; + double sum = 0; + for (int i = 0; i < n; i++) { + cnt = 4; + int tem = sc.nextInt(); + sum = 2; + while (tem > 0) { + if (sum >= tem) { break; } + cnt++; + if (cnt % 4 == 1) { + sum = sum + 0.5 + cnt / 4 - 1; + } else if (cnt % 4 == 2 || cnt % 4 == 3) { + sum = sum + 1.5 + cnt / 4 - 1; + } else { + sum = sum + 2.5 + cnt / 4 - 2; + } + + } + System.out.println(cnt); + + + } + +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/exams/3.js b/NowCoder/2020RealTime/exams/3.js new file mode 100644 index 0000000..713db90 --- /dev/null +++ b/NowCoder/2020RealTime/exams/3.js @@ -0,0 +1,24 @@ +while (n = readInt()) { + var count; + var sun; + for (var i = 0; i < n; i++) { + count = 4; + var tem = readInt(); + sum = 2; + while (tem > 0) { + if (sum >= tem) { + break; + } + count++; + + if (count % 4 === 1) { + sum = sum + 0.5 + parseInt(count / 4) - 1; + } else if (count % 4 == 2 || count % 4 == 3) { + sum = sum + 1.5 + parseInt(count / 4) - 1; + } else { + sum = sum + 2.5 + parseInt(count / 4) - 2; + } + } + print(count); + } +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/exams/4.js b/NowCoder/2020RealTime/exams/4.js new file mode 100644 index 0000000..31b3ada --- /dev/null +++ b/NowCoder/2020RealTime/exams/4.js @@ -0,0 +1,22 @@ +for(var i=0;i<3;i++){ + setTimeout(_=>{ + console.log(i); + }) +} + + +for(let i=0;i<3;i++){ + setTimeout(_=>{ + console.log(i); + }) +} + + + +for (let i = 0; i < 5; i++) { + (function(i){ + setTimeout(function(){ + console.log(i); + },1000) + })(i) +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/huawei/0907/1.js b/NowCoder/2020RealTime/huawei/0907/1.js new file mode 100644 index 0000000..1e54549 --- /dev/null +++ b/NowCoder/2020RealTime/huawei/0907/1.js @@ -0,0 +1,37 @@ +function findMinSteps(datas){ + let minS = Number.MAX_VALUE; + let len = datas.length; + if(!len||len===0){ + return 0; + } + if(len===1){ + return 0; + } + let state=false; + function dfs(index,count){ + if(indexparseInt(a)); +print(findMinSteps(datas)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/huawei/0907/2.js b/NowCoder/2020RealTime/huawei/0907/2.js new file mode 100644 index 0000000..d0192b6 --- /dev/null +++ b/NowCoder/2020RealTime/huawei/0907/2.js @@ -0,0 +1,40 @@ +function findtoPart(n,m){ + if(m>n){ + return 0; + } + let count=n; + let store=[]; + function dfs(n,m,start,current,stores){ + if(currenta!==start)){ + stores.push(start); + let temp = current; + for(let i=0;ia!==i)){ + dfs(n,m,i,temp+1,stores.slice()); + } + } + } + + }else if(current===m){ + stores.sort((a,b)=>a-b); + let datas= stores.join(''); + if(store && store.every((a)=>a!==datas)){ + store.push(stores.join('')); + count++; + }else if(!store){ + store.push(stores.join('')); + count++; + } + } + } + for(let i=0;i=0;j--){ + let cTemp = computes[j].split('='); + let tempBefore=cTemp[1]; + for(let key in Dics){ + if(Dics.hasOwnProperty(key)){ + while(tempBefore.indexOf(key)!==-1){ + tempBefore=tempBefore.replace(key,"("+Dics[key]+")"); + } + } + } + Dics[cTemp[0]]=tempBefore; + } + let lastCompute = Dics[last]; + let afterCom=""; + for(let k=0;k y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); + if (condition) { + state = !state; + } + + } + return state; +} + + +var data; +while (data = read_line()) { + var datas = data.split(" "); + var len = datas.length; + var point = datas[0].split(","); + var count = 1; + var edgePoints = []; + while (count < len) { + edgePoints.push(datas[count].split(",")); + count++; + } + print(checkIfIn(point, edgePoints)); +} + + + +// var point=[1,1.5]; +// var edgePoints=[[0,0],[2,0],[1,2],[0,2]]; +var point = [2, 1]; +var edgePoints = [ + [0, 0], + [2, 0], + [1, 1], + [1, 2], + [0, 2] +]; +console.log(checkIfIn(point, edgePoints)); + + + + + +function bigNumAdd(a, b) { + let sum = ''; + let tempState = false, + tempData = 0; + a = String(a).split(''); + b = String(b).split(''); + while (a.length || b.length || tempState) { + if (a.length && b.length) { + tempData += ~~a.pop() + ~~b.pop(); + } else if (!a.length && b.length) { + tempData += 0 + ~~b.pop(); + } else if (!b.length && a.length) { + tempData += ~~a.pop() + 0; + } + + sum = (tempData % 10) + sum; + tempData = tempData > 9 ? 1 : 0; + tempState = tempData > 0; + } + return sum; +} + +var line; +while (line=readline()) { + line = line.split(' '); + var a = line[0]; + var b = line[1]; + print(bigNumAdd(a, b)); +} \ No newline at end of file From cb58e72f1749722b4e31fc52121c200936bd0a58 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Fri, 13 Sep 2019 11:09:10 +0800 Subject: [PATCH 271/274] =?UTF-8?q?leetcode=20452=20=E5=B0=84=E7=AE=AD?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E8=B4=AA=E5=BF=83=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...52.MinimumNumberofArrowstoBurstBalloons.js | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Leetcode/452.MinimumNumberofArrowstoBurstBalloons.js diff --git a/Leetcode/452.MinimumNumberofArrowstoBurstBalloons.js b/Leetcode/452.MinimumNumberofArrowstoBurstBalloons.js new file mode 100644 index 0000000..0e1f5c6 --- /dev/null +++ b/Leetcode/452.MinimumNumberofArrowstoBurstBalloons.js @@ -0,0 +1,44 @@ +/* + * @Author: SkylineBin + * @Date: 2019-09-12 21:08:56 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-09-12 21:10:48 + */ + +/***** + * + * 射气球的最小只箭 + * + * 使用贪心算法 + * + * + * + */ + + +var findMinArrowShots = function(points) { + if(!points || points.length===0){ + return 0; + } + points.sort((a,b)=>a[0]-b[0]); + var count=1; + var rangeLeft=points[0][0]; + var rangeRight=points[0][1]; + for(var i=1;irangeRight){ + count++; + rangeLeft=tempPoint[0]; + rangeRight=tempPoint[1]; + }else if(tempPoint[1]>=rangeRight&&tempPoint[0]<=rangeRight){ + rangeLeft=tempPoint[0]; + }else if(tempPoint[1]<=rangeRight&&tempPoint[0]>=rangeLeft){ + rangeLeft=tempPoint[0]; + rangeRight=tempPoint[1]; + } + } + return count; +}; + +var points=[[0,9],[1,8],[7,8],[1,6],[9,16],[7,13],[7,10],[6,11],[6,9],[9,13]]; +console.log(findMinArrowShots(points)); \ No newline at end of file From 51fb803c65b649178f8c813e87770be013988f1c Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Wed, 25 Sep 2019 09:43:35 +0800 Subject: [PATCH 272/274] =?UTF-8?q?=E9=83=A8=E5=88=86=E7=A7=8B=E6=8B=9B?= =?UTF-8?q?=E7=9C=9F=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2019SchoolInterview/kuaishou/magicWays.js | 62 +++++++++++++ NowCoder/2019SchoolInterview/momenta/1.js | 54 +++++++++++ NowCoder/2020RealTime/huawei/leftandright.js | 60 +++++++++++++ NowCoder/2020RealTime/vipkid/1.c | 41 +++++++++ NowCoder/2020RealTime/vipkid/1.js | 90 +++++++++++++++++++ NowCoder/2020RealTime/zhaoyin/1.js | 52 +++++++++++ 6 files changed, 359 insertions(+) create mode 100644 NowCoder/2019SchoolInterview/kuaishou/magicWays.js create mode 100644 NowCoder/2019SchoolInterview/momenta/1.js create mode 100644 NowCoder/2020RealTime/huawei/leftandright.js create mode 100644 NowCoder/2020RealTime/vipkid/1.c create mode 100644 NowCoder/2020RealTime/vipkid/1.js create mode 100644 NowCoder/2020RealTime/zhaoyin/1.js diff --git a/NowCoder/2019SchoolInterview/kuaishou/magicWays.js b/NowCoder/2019SchoolInterview/kuaishou/magicWays.js new file mode 100644 index 0000000..9b5f8fd --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/magicWays.js @@ -0,0 +1,62 @@ +function allWaysofOut(numN){ + let maxD=1000; + let store=[]; + store[0]=1; + store[1]=0; + for(let i=2;i<=maxD;i++){ + store[i]=0; + } + for(let i=0;i<=maxD;i++){ + let temp = 1; + while(temp<=i){ + store[i]+=store[i-temp]; + temp*=2; + store[i]%= Math.pow(10,9)+3; + } + } + return store[numN]; +} + +let numN = 100; +console.log(allWaysofOut(numN)); + + +// 混合处理及提交版本 + + +function allWaysofOut(numNs){ + let maxD=1000; + let store=[]; + store[0]=1; + store[1]=0; + for(let i=2;i<=maxD;i++){ + store[i]=0; + } + for(let i=0;i<=maxD;i++){ + let temp = 1; + while(temp<=i){ + store[i]+=store[i-temp]; + temp*=2; + store[i]%= Math.pow(10,9)+3; + } + } + let outputs=[]; + for(let i=0;ia-b); + console.log(datas); + let len = datas.length; + if(currentparseInt((len-1)/2)){ + if(current%2 === len%2){ + return 2*current+1-len-1; + }else{ + return 2*current+1-len; + } + }else{ + return 0; + } +} + + +let datas=[67, 94, 59, 4, 20, 4, 6, 81, 26, 27]; +let numN = 10; +let numX = 96; + + +function leastAddNum2(numN,numX,datas){ + datas.sort((a,b)=>a-b); + let cMid = parseInt((numN-1)/2); + let left=0,right=0,count=0; + for (let i = 0; i < numN; i++) { + if(datas[i]===numX){ + count++; + }else if(datas[i]numX){ + right++; + } + } + if(left<=cMid){ + if(cMid=0){ + if(arr[len]%2===0){ + var temp=arr.splice(len,1)[0]; + arr.push(temp); + } + len--; + } + return arr; +} + + +var arr=[1,2,3,4,5,6,7,8,6,7,9,0]; +console.log(moveArrs(arr)); + +// 时间复杂度O(N),空间复杂度O(N),对原有顺序有要求 +function moveArrs2(arr){ + var len = arr.length; + var res=[]; + for (let i = 0; i =0; i--) { + if(arr[i]%2===1){ + res.unshift(arr[i]); + } + } + return res; +} + +var arr2=[1,2,3,4,5,6,7,8,6,7,9,0]; +console.log(moveArrs2(arr2)); + + +// 双指针版本 +function moveArrs3(arr){ + var len = arr.length; + var res=[]; + var left=0,right=len-1; + while(left=0){ + if(arr[left]%2===0){ + res.push(arr[left]); + } + if(arr[right]%2===1){ + res.unshift(arr[right]); + } + left++; + right--; + } + return res; +} + +var arr3=[1,2,3,4,5,6,7,8,6,7,9,0]; +console.log(moveArrs3(arr3)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/vipkid/1.c b/NowCoder/2020RealTime/vipkid/1.c new file mode 100644 index 0000000..e11f9e7 --- /dev/null +++ b/NowCoder/2020RealTime/vipkid/1.c @@ -0,0 +1,41 @@ +#include +#include +using namespace std; +int a[1999999]={0}; +int y; +int ss =0 ; +void dfs(int n,int cnt,int pre) +{ +if(n==0) +{ +ss++; +printf("%d=",y); +for(int i=1;i>n; +y = n; +dfs(n,0,1); +return 0; +} \ No newline at end of file diff --git a/NowCoder/2020RealTime/vipkid/1.js b/NowCoder/2020RealTime/vipkid/1.js new file mode 100644 index 0000000..97bdb55 --- /dev/null +++ b/NowCoder/2020RealTime/vipkid/1.js @@ -0,0 +1,90 @@ +function outputSum1(num) { + var res = []; + + var a=[]; + for (let i = 0; i < 10000; i++) { + a[i]=0; + + } + var y; + var ss = 0; + function dfs(n, cnt, pre) { + if (n == 0) { + ss++; + var temp=""; + for (var i = 1; i < cnt; i++) { + temp+=a[i]+"+"; + } + temp+=a[cnt]; + if (ss % 4 == 0) + res.push(temp); + else { + if (a[1] != y) + temp=""; + } + } + for (var i = pre; i <= n; i++) { + a[++cnt] = i; + dfs(n-i, cnt, i); + cnt--; + } + } + dfs(num,0,1); + return res; +} + + +function outputSum(num) { + var res = []; + var back=[]; + var y=0,count=0,pos=-1; + var n=num; + function dfs(x) { + if(y===n){ + count++; + temp=""; + for (var i = 0; i < pos; i++) { + temp+= res[i]+"+"; + } + temp+=res[pos]; + + if(back.indexOf(temp)===-1){ + back.push(temp); + } + + return; + } + if(y>n){ + return; + } + for (let i =x; i < n+1; i++) { + res[++pos]=i; + y+=i; + dfs(i); + pos--; + y-=i; + + } + + } + dfs(1); + return back; +} + +// var num = readInt(); +// var res = outputSum(num); +// for (var i = 0; i < res.length; i++) { +// print(res[i]); +// } + + +var num=4; +var res = outputSum2(num); +for (var i = 0; i < res.length; i++) { + console.log(res[i]); +} + + + + + diff --git a/NowCoder/2020RealTime/zhaoyin/1.js b/NowCoder/2020RealTime/zhaoyin/1.js new file mode 100644 index 0000000..7937271 --- /dev/null +++ b/NowCoder/2020RealTime/zhaoyin/1.js @@ -0,0 +1,52 @@ +function updateNums(str){ + let res=[]; + let len = str.length; + if(str[0]!=='R' || str[len-1]!=='L'){ + return res; + } + let states=[]; + for (let i = 0; i < len; i++) { + states[i]=1; + } + function move(){ + let before,current; + before = states[0]; + states[0]=0; + for (let i = 1; i < len; i++) { + current = states[i]; + let temp = before || 0; + if(str[i]==='R'){ + states[i]=0; + before=current; + } + if(str[i]==='L'){ + states[i-1]+=current; + states[i]=0; + before=0; + } + states[i]+=temp; + } + return states.join('#'); + } + let stores=[]; + + let count=1; + let data=move(); + stores.push(data); + console.log(states); + while(stores.indexOf(data)===-1 || count%2!==0){ + data=move(); + count++; + stores.push(data); + console.log(states); + } + // move(); + // console.log(states); + // move(); + // console.log(states); + return states; +} + +let str="RRLRL"; +// let str="RRRRRLRLRL"; +console.log(updateNums(str)); \ No newline at end of file From 9ad68f585ed5cac22effc8b6a31cf5423f68ed10 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 18 Nov 2019 09:50:49 +0800 Subject: [PATCH 273/274] add decodeString --- TestProjects/2.js | 31 +++++++++++++++++++++++++++++++ TestProjects/3.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 TestProjects/2.js create mode 100644 TestProjects/3.js diff --git a/TestProjects/2.js b/TestProjects/2.js new file mode 100644 index 0000000..72b2017 --- /dev/null +++ b/TestProjects/2.js @@ -0,0 +1,31 @@ +function rgb (r, g, b) { + let ostr="#"; + function initNumber(num){ + if(num>=0&&num<=255){ + return num; + }else if(num>255){ + return 255; + }else{ + return 0; + } + } + r = initNumber(r); + g = initNumber(g); + b = initNumber(b); + function processStr(str){ + if(str.length==1){ + return "0"+str + }else{ + return str; + } + } + ostr+=processStr(r.toString(16).toUpperCase()); + ostr+=processStr(g.toString(16).toUpperCase()); + ostr+=processStr(b.toString(16).toUpperCase()); + return ostr; +} +let r=255; +// 23,123,55 + + +console.log(rgb(0,0,0)); \ No newline at end of file diff --git a/TestProjects/3.js b/TestProjects/3.js new file mode 100644 index 0000000..7449877 --- /dev/null +++ b/TestProjects/3.js @@ -0,0 +1,42 @@ +function decodeString(str){ + // your code here + let outsideStr = ""; + let lastNum = []; + let tempNum = ""; + let start = 0; + tempStr = ""; + for (let i = 0; i < str.length; i++) { + if(str[i]>="0"&&str[i]<="9"){ + tempNum+=str[i]; + }else if(str[i]==="["){ + tempStr = ""; + start=i; + lastNum.push(parseInt(tempNum)); + }else if(str[i]==="]"){ + let ts = tempStr; + outsideStr = outsideStr.substring(0,start-1)+ts.repeat(lastNum.pop()); + }else{ + tempStr+=str[i]; + } + outsideStr+=str[i]; + } + let state = true; + for (let i = 0; i < outsideStr.length; i++) { + if(outsideStr[i]=="["){ + state=false; + } + } + if(state){ + if(outsideStr[outsideStr.length-1]==="]"){ + return outsideStr.substring(0,outsideStr.length-1); + } + return outsideStr; + }else{ + return decodeString(outsideStr); + } +} + +// decodeString('2[a2[b]]') +// let str="2[a2[b]]"; +let str="3[ab]"; +console.log(decodeString(str)); From 3eb535dd047b85d263b0d5db95e592dde9fe4878 Mon Sep 17 00:00:00 2001 From: SkylineBin Date: Mon, 20 Jan 2020 15:59:24 +0800 Subject: [PATCH 274/274] leetcode Swap Nodes in Pairs --- Leetcode/24.SwapNodesinPairs.js | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Leetcode/24.SwapNodesinPairs.js diff --git a/Leetcode/24.SwapNodesinPairs.js b/Leetcode/24.SwapNodesinPairs.js new file mode 100644 index 0000000..bb2a168 --- /dev/null +++ b/Leetcode/24.SwapNodesinPairs.js @@ -0,0 +1,48 @@ +/* + * @Author: SkylineBin + * @Date: 2020-01-20 15:05:07 + * @Last Modified by: SkylineBin + * @Last Modified time: 2020-01-20 15:25:07 + */ + +/** + * + * @param {*} head + * LeetCode 24 Swap Nodes in Pairs + * 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 + * 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 + * + * + * + */ + + + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ + + +var swapPairs = function(head) { + if(head === null){ + return head; + } + var fastL = head.next; + var slowL = head; + if(fastL === null){ + return slowL; + } + var lastHead = fastL; + + slowL.next=swapPairs(fastL.next); + fastL.next=slowL; + return lastHead; +}; \ No newline at end of file