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 diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..7c202e3 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,32 @@ +{ + "configurations": [ + { + "type": "java", + "name": "CodeLens (Launch) - QuickSort", + "request": "launch", + "mainClass": "basic_algorithm.QuickSort" + }, + { + "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", + "request": "launch", + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "stopOnEntry": false, + "mainClass": "basic_algorithm.BubbleSort", + "args": "" + } + ] +} \ No newline at end of file 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/Algorithms/Disk Scheduling Algorithm/CscanAlgo.java b/Algorithms/Disk Scheduling Algorithm/CscanAlgo.java new file mode 100644 index 0000000..caff64e --- /dev/null +++ b/Algorithms/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/Algorithms/Disk Scheduling Algorithm/FcfsAlgo.java b/Algorithms/Disk Scheduling Algorithm/FcfsAlgo.java new file mode 100644 index 0000000..f809039 --- /dev/null +++ b/Algorithms/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/Algorithms/Disk Scheduling Algorithm/ScanAlgo.java b/Algorithms/Disk Scheduling Algorithm/ScanAlgo.java new file mode 100644 index 0000000..033e33b --- /dev/null +++ b/Algorithms/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/Algorithms/Disk Scheduling Algorithm/SstfAlgo.java b/Algorithms/Disk Scheduling Algorithm/SstfAlgo.java new file mode 100644 index 0000000..d22a3a3 --- /dev/null +++ b/Algorithms/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("-------------------------"); + } + +} diff --git a/Algorithms/Disk Scheduling Algorithm/readme.md b/Algorithms/Disk Scheduling Algorithm/readme.md new file mode 100644 index 0000000..a3b76aa --- /dev/null +++ b/Algorithms/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](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](https://store.skylinebin.com/image/system/cscanAlgo.png) 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 new file mode 100644 index 0000000..3f8f6e1 --- /dev/null +++ b/Algorithms/README.md @@ -0,0 +1,21 @@ +## Algorithms + +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/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)); + } + +} 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)); + + } + +} diff --git a/Algorithms/basic_algorithm/InversionbyJavaScript.js b/Algorithms/basic_algorithm/InversionbyJavaScript.js new file mode 100644 index 0000000..407ee3d --- /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 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; + + } +} diff --git a/Algorithms/basic_algorithm/SmallSumbyJavaScript.js b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js new file mode 100644 index 0000000..25ec57d --- /dev/null +++ b/Algorithms/basic_algorithm/SmallSumbyJavaScript.js @@ -0,0 +1,55 @@ +/***** + * + * @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 diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/BubbleSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/BubbleSort.java new file mode 100644 index 0000000..6864d88 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/BubbleSort.java @@ -0,0 +1,144 @@ +package basic_algorithm; + +import java.util.Arrays; + +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); + } + } + } + + } + + 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]); + 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); + + } + + + + + + + + + +} diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java new file mode 100644 index 0000000..ccbcfae --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/DutchFlagArray.java @@ -0,0 +1,127 @@ +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/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/SortAlgorithmsbyJava/InsertionSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/InsertionSort.java new file mode 100644 index 0000000..e699ac0 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/InsertionSort.java @@ -0,0 +1,137 @@ +package basic_algorithm; + +import java.util.Arrays; + +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 个数的初始值 + for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) { +// 从 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]; + 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); + 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/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/SortAlgorithmsbyJava/MergeSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/MergeSort.java new file mode 100644 index 0000000..7e2b7e7 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/MergeSort.java @@ -0,0 +1,177 @@ +package basic_algorithm; + +import java.util.Arrays; + +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) { + 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); + + } + +} diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java new file mode 100644 index 0000000..4d4b729 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/QuickSort.java @@ -0,0 +1,155 @@ +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) { + 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); + } + } + + 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/SortAlgorithmsbyJava/SelectionSort.java b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/SelectionSort.java new file mode 100644 index 0000000..a673bbe --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJava/SelectionSort.java @@ -0,0 +1,136 @@ +package basic_algorithm; + +import java.util.Arrays; + +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 保存从 i 往后的最小值索引 + 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; + } + + + +// 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); + + } + + + +} 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/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js new file mode 100644 index 0000000..c74c1ea --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/BubbleSort.js @@ -0,0 +1,31 @@ +/** + * @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 + * + */ + +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/DultFlagArray.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js new file mode 100644 index 0000000..c13f401 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/DultFlagArray.js @@ -0,0 +1,68 @@ +/** + * @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; + return [less+1, more-1]; +} + + +/** + * @function 用于交互数组中的指定位置的两个数 + * @param {*} arrays + * @param {*} si + * @param {*} sj + */ +function swap(arrays, si, sj) { + let tempdata = arrays[si]; + arrays[si] = arrays[sj]; + arrays[sj] = tempdata; +} + +/** + * @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/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/InsertionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/InsertionSort.js new file mode 100644 index 0000000..ccdb212 --- /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/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/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/MergeSort.js new file mode 100644 index 0000000..8856a0f --- /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/QuickSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js new file mode 100644 index 0000000..653bca1 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/QuickSort.js @@ -0,0 +1,69 @@ +/** + * @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) { + // 添加随机快排的代码 + 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); + } +} + +/** + * @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] 交换 + // console.log(arrays); + 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/SelectionSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js new file mode 100644 index 0000000..8870b39 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/SelectionSort.js @@ -0,0 +1,29 @@ +/** + * @author SkylineBin + * @time 2018-10-6 + * @function use javascript to create SelectionSort + * 选择排序 + * @Algorithm_bigO O(N ^ 2) + * N is the length of arrays + * + */ + +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/bigdataTest.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js new file mode 100644 index 0000000..fee69ae --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/bigdataTest.js @@ -0,0 +1,123 @@ +/** + * @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'); +const QuickSort = require('./QuickSort'); +const HeapSort = require('./HeapSort'); + +// 生成指定长度和取值范围的数组 +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; +} + +// 大样本测试 +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); + HeapSort(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; +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); +QuickSort(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)); + +moreDataTest(); + + + diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js new file mode 100644 index 0000000..bb8be16 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/mainSort.js @@ -0,0 +1,64 @@ +/** + * @author SkylineBin + * @time 2018-10-6 + * @function test BubbleSort + * + * + */ + +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 = [3,6,5,2,4,0,5,3,9]; + +console.log(arrone); + +// console.log('--------start BubbleSort-----------'); + +// BubbleSort(arrone); + +// console.log('--------end BubbleSort-----------'); + + +// console.log('--------start SelectionSort-----------'); + +// SelectionSort(arrone); + +// console.log('--------end SelectionSort-----------'); + +// console.log('--------start InsertionSort-----------'); + +// InsertionSort(arrone); + +// console.log('--------end InsertionSort-----------'); + + // console.log('--------start MergeSort-----------'); + + // MergeSort(arrone); + + // console.log('--------end MergeSort-----------'); + + // console.log('--------start DutchFlagArray-----------'); + + // DutchFlagArray(arrone, 0, 6 , 4); + + // console.log('--------end DutchFlagArray-----------'); + + // console.log('--------start QuickSort-----------'); + + // QuickSort(arrone); + + // console.log('--------end QuickSort-----------'); + + console.log('--------start HeapSort-----------'); + + HeapSort(arrone); + + console.log('--------end HeapSort-----------'); + +console.log(arrone); \ No newline at end of file diff --git a/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js new file mode 100644 index 0000000..875de68 --- /dev/null +++ b/Algorithms/basic_algorithm/SortAlgorithmsbyJavaScript/sortTesting.js @@ -0,0 +1,64 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-03 20:33:20 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-14 14:18:02 + */ + + +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); + + + +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/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js b/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js new file mode 100644 index 0000000..65f5fa9 --- /dev/null +++ b/Algorithms/basic_algorithm/applicationAlgorithms/printMatrixbyZhiZi.js @@ -0,0 +1,119 @@ +/****** + * + * 之字形打印矩阵 + * + * + * + */ + +// ! 解题思路:从宏观来看,可转换成已知矩阵右上与左下两点,打印对角线上的数 +// 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 (a[0] !== rr) { + 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)); + + +// 简洁版本的写法 +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 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/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] && jb) ? 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 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/UseDictionary.js b/DataStructures/Dictionary/UseDictionary.js new file mode 100644 index 0000000..026858d --- /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 diff --git a/DataStructures/Dictionary/UseHashTable.js b/DataStructures/Dictionary/UseHashTable.js new file mode 100644 index 0000000..c2cfbc5 --- /dev/null +++ b/DataStructures/Dictionary/UseHashTable.js @@ -0,0 +1,73 @@ +/***** + * + * @author SkylineBin + * @time 2018-10-16 + * @function Create HashTable Structure by JavaScript + * 散列算法的作用是尽可能快地在数据结构中找到一个值 + * 散列函数的作用是给定一个键值,然后返回值在表中的地址 + * + */ + +const djb2HashCode = require('./betterHashFuction'); + +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); + // var position = djb2HashCode(key); + console.log(position + '-' + key); + table[position] = value; + } + + // 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 + 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('John')); +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..45e39c9 --- /dev/null +++ b/DataStructures/Dictionary/UseHashTableApart.js @@ -0,0 +1,121 @@ +/***** + * + * @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 = []; + + // 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 diff --git a/DataStructures/Dictionary/UseHashTableLinerCheck.js b/DataStructures/Dictionary/UseHashTableLinerCheck.js new file mode 100644 index 0000000..7849985 --- /dev/null +++ b/DataStructures/Dictionary/UseHashTableLinerCheck.js @@ -0,0 +1,115 @@ +/***** + * + * @author SkylineBin + * @time 2018-10-17 + * @function Create HashTable Structure (Liner Check) by JavaScript + * @function 使用线性探查的方法解决冲突 + * + */ + +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 + // 每一个有效值都是 ValuePair 的实例 + 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[position] = 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 diff --git a/DataStructures/Dictionary/betterHashFuction.js b/DataStructures/Dictionary/betterHashFuction.js new file mode 100644 index 0000000..e260598 --- /dev/null +++ b/DataStructures/Dictionary/betterHashFuction.js @@ -0,0 +1,65 @@ +/**** + * + * @function 更好的散列函数实例 + * 比之前使用的loseloseHashCode 好一些的散列函数 + * + */ + +// const Dictionary = require('./CreateDictionary'); + +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; + +// 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/Graph/UseGraph.js b/DataStructures/Graph/UseGraph.js new file mode 100644 index 0000000..0a5c1ea --- /dev/null +++ b/DataStructures/Graph/UseGraph.js @@ -0,0 +1,187 @@ +/***** + * + * @function 使用 JavaScript 创建 图数据结构 + * @date 2019-3-25 + * + */ + +const Dictionary = require('../Dictionary/CreateDictionary'); +const Queue = require('../Queue/CreateQueue'); +const Stack = require('../Stack/CreateStack'); + +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 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 + }; + } + + // 深度优先遍历搜索过程 + 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) { + 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++) { + 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()); +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/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/DataStructures/LinkedList/CreateLinkedList.js b/DataStructures/LinkedList/CreateLinkedList.js new file mode 100644 index 0000000..208d5eb --- /dev/null +++ b/DataStructures/LinkedList/CreateLinkedList.js @@ -0,0 +1,159 @@ +/** + * @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.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/UseDoublyLinkedList.js b/DataStructures/LinkedList/UseDoublyLinkedList.js new file mode 100644 index 0000000..c5b0d97 --- /dev/null +++ b/DataStructures/LinkedList/UseDoublyLinkedList.js @@ -0,0 +1,100 @@ +/**** + * + * @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) { + 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 diff --git a/DataStructures/LinkedList/UseLinkedList.js b/DataStructures/LinkedList/UseLinkedList.js new file mode 100644 index 0000000..2cd01c9 --- /dev/null +++ b/DataStructures/LinkedList/UseLinkedList.js @@ -0,0 +1,162 @@ +/** + * @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(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 + 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, + index = 0; + + if(position === 0){ + head = current.next; + } else { + while(index++ < position){ + previous = current; + current = current.next; + } + // current element will be recyclied by JavaScript GC + previous.next = current.next; + } + length--; + + return current.element; + }else { + return null; + } + }; + + // 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 + this.toString = function() { + let current = head; + string = ''; + while (current) { + string += current.element + (current.next ? '_': ''); + current = current.next; + } + return string; + + + } + + // 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); +list.append(4); +list.append(16); +list.append(13); + +list.print(); \ 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/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 diff --git a/DataStructures/Queue/CreateQueue.js b/DataStructures/Queue/CreateQueue.js new file mode 100644 index 0000000..ef5206e --- /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/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(); 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 new file mode 100644 index 0000000..7a35d3b --- /dev/null +++ b/DataStructures/README.md @@ -0,0 +1,30 @@ +# DataStructures + +该目录主要是记录 JavaScript 中的数据结构实现方式,包括简单实现以及使用,以及ES6模块化封装的输出.... +主要是书籍 [《学习JavaScript数据结构与算法(第2版)》](http://www.ituring.com.cn/book/2029)的代码实现 + +## Stack + +Using JavaScript to create the Stack Structure + +## Queue + +Using JavaScript to create the Queue Structure + +## LinkedList + +Using JavaScript to create the LinkedList Structure + +## Set + +Using JavaScript to create the Set Structure + +## Dictionary + +Using JavaScript to create the Dictionary Structure and HashTable Structure + +## Graph + +Using JavaScript to create the Graph Structure + +## Sort diff --git a/DataStructures/Set/UseES6Set.js b/DataStructures/Set/UseES6Set.js new file mode 100644 index 0000000..6e34b5a --- /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 diff --git a/DataStructures/Set/UseSetbySelf.js b/DataStructures/Set/UseSetbySelf.js new file mode 100644 index 0000000..60eddfc --- /dev/null +++ b/DataStructures/Set/UseSetbySelf.js @@ -0,0 +1,181 @@ +/**** + * + * @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; + }; + + // 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; + } + } + +} + + +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); +set.add(7); +console.log('------------------------------------'); +console.log(set.values()); +console.log('------------------------------------'); +set.remove(2); +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('------------------------------------'); 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 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/DataStructures/Stack/CreateStack.js b/DataStructures/Stack/CreateStack.js new file mode 100644 index 0000000..0fe721c --- /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/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..515a702 --- /dev/null +++ b/DataStructures/Stack/ES6Pros/UseSymbolStack.js @@ -0,0 +1,37 @@ +/** + * @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()); +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 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 + } + }) + 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 diff --git a/DataStructures/Stack/SolveProblem/SymbolsBalance.js b/DataStructures/Stack/SolveProblem/SymbolsBalance.js new file mode 100644 index 0000000..cc832dd --- /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 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(); + diff --git a/DataStructures/Tree/BinarySearchTree.js b/DataStructures/Tree/BinarySearchTree.js new file mode 100644 index 0000000..a5759ea --- /dev/null +++ b/DataStructures/Tree/BinarySearchTree.js @@ -0,0 +1,212 @@ +/***** + * + * @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) { + 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; + } + } + + // 通过中序遍历方式遍历所有节点 + 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; + } + 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; + } +} + +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); + +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'); diff --git a/HuaWeiOJ Algorithms/EasyPractice/BeEncryptedtoOthers.py b/HuaWeiOJ Algorithms/EasyPractice/BeEncryptedtoOthers.py new file mode 100644 index 0000000..cf5aa69 --- /dev/null +++ b/HuaWeiOJ Algorithms/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() diff --git a/HuaWeiOJ Algorithms/EasyPractice/LengthOfLastString.py b/HuaWeiOJ Algorithms/EasyPractice/LengthOfLastString.py new file mode 100644 index 0000000..a79c693 --- /dev/null +++ b/HuaWeiOJ Algorithms/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() diff --git a/HuaWeiOJ Algorithms/EasyPractice/ReverseString.py b/HuaWeiOJ Algorithms/EasyPractice/ReverseString.py new file mode 100644 index 0000000..aaa684d --- /dev/null +++ b/HuaWeiOJ Algorithms/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() 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 diff --git a/HuaWeiOJ Algorithms/What-I-had/Findseven.py b/HuaWeiOJ Algorithms/What-I-had/Findseven.py new file mode 100644 index 0000000..fc29c12 --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/Judgesubnet.py b/HuaWeiOJ Algorithms/What-I-had/Judgesubnet.py new file mode 100644 index 0000000..8bb359c --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/LCM.py b/HuaWeiOJ Algorithms/What-I-had/LCM.py new file mode 100644 index 0000000..c81474a --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/ReoranginizePic.py b/HuaWeiOJ Algorithms/What-I-had/ReoranginizePic.py new file mode 100644 index 0000000..5ef9eb5 --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/bekeyed-readme.txt b/HuaWeiOJ Algorithms/What-I-had/bekeyed-readme.txt new file mode 100644 index 0000000..ceb4f9b --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/bekeyed.py b/HuaWeiOJ Algorithms/What-I-had/bekeyed.py new file mode 100644 index 0000000..e41281f --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/cornumpy.py b/HuaWeiOJ Algorithms/What-I-had/cornumpy.py new file mode 100644 index 0000000..3f492e2 --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/countmang.py b/HuaWeiOJ Algorithms/What-I-had/countmang.py new file mode 100644 index 0000000..863faaa --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/countstr.py b/HuaWeiOJ Algorithms/What-I-had/countstr.py new file mode 100644 index 0000000..2c8f9cd --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/cuberoot.py b/HuaWeiOJ Algorithms/What-I-had/cuberoot.py new file mode 100644 index 0000000..ffe060c --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/encryanddecry.py b/HuaWeiOJ Algorithms/What-I-had/encryanddecry.py new file mode 100644 index 0000000..91cb1c2 --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/framepy.py b/HuaWeiOJ Algorithms/What-I-had/framepy.py new file mode 100644 index 0000000..49f134e --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/getaverage.py b/HuaWeiOJ Algorithms/What-I-had/getaverage.py new file mode 100644 index 0000000..8bf740c --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/keybesort.py b/HuaWeiOJ Algorithms/What-I-had/keybesort.py new file mode 100644 index 0000000..ce34eb6 --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/legalip.py b/HuaWeiOJ Algorithms/What-I-had/legalip.py new file mode 100644 index 0000000..890e3ef --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/old.py b/HuaWeiOJ Algorithms/What-I-had/old.py new file mode 100644 index 0000000..0e3cc2a --- /dev/null +++ b/HuaWeiOJ Algorithms/What-I-had/old.py @@ -0,0 +1,3 @@ +''' +for tomorrow +''' diff --git a/HuaWeiOJ Algorithms/What-I-had/snakearry.py b/HuaWeiOJ Algorithms/What-I-had/snakearry.py new file mode 100644 index 0000000..aeea5e6 --- /dev/null +++ b/HuaWeiOJ Algorithms/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/HuaWeiOJ Algorithms/What-I-had/studyenglishtwo.py b/HuaWeiOJ Algorithms/What-I-had/studyenglishtwo.py new file mode 100644 index 0000000..0b0c181 --- /dev/null +++ b/HuaWeiOJ Algorithms/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/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" "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" new file mode 100644 index 0000000..7d70ed6 --- /dev/null +++ "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" @@ -0,0 +1,10 @@ +计算字符串最后一个单词的长度,单词以空格隔开。 +知识点 字符串,循环 +运行时间限制 0M +内存限制 0 +输入 +一行字符串,长度小于128。 +输出 +整数N,最后一个单词的长度。 +样例输入 hello world +样例输出 5 \ No newline at end of file diff --git "a/HuaWeiOJ Algorithms/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" new file mode 100644 index 0000000..ceab91c --- /dev/null +++ "b/HuaWeiOJ Algorithms/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/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" "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" new file mode 100644 index 0000000..c891c86 --- /dev/null +++ "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" @@ -0,0 +1,10 @@ +计算两个字符串的最大公共字串的长度,字符不区分大小写 +详细描述: +接口说明 +原型: +int getCommonStrLength(char * pFirstStr, char * pSecondStr); +输入参数: + + char * pFirstStr //第一个字符串 + + char * pSecondStr//第二个字符串 \ No newline at end of file diff --git a/HuaWeiOJ Algorithms/hsd/one.py b/HuaWeiOJ Algorithms/hsd/one.py new file mode 100644 index 0000000..82f4272 --- /dev/null +++ b/HuaWeiOJ Algorithms/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 0: + carnum=carnum-1 + else: + carnum=0 + + +if __name__=="__main__": + main() 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. diff --git a/Leetcode/1.twoSum.js b/Leetcode/1.twoSum.js new file mode 100644 index 0000000..b260620 --- /dev/null +++ b/Leetcode/1.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 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 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]; +// } +// } + +// 需要注意的是 JavaScript 中可能需要取整操作 +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 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 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 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/Leetcode/15.3sum.js b/Leetcode/15.3sum.js new file mode 100644 index 0000000..3129cc2 --- /dev/null +++ b/Leetcode/15.3sum.js @@ -0,0 +1,101 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-25 15:53:51 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-20 21:59:21 + */ + + +/***** + * + * 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)); + +// 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 a-b); + for(let i=0;i 4 -> 3) + (5 -> 6 -> 4) + * Output: 7 -> 0 -> 8 + * Explanation: 342 + 465 = 807. + * + * + * + */ +// ! 本质涉及: + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ + +const arrayToLinkNode = require('./tools/LinkNode'); + +function ListNode(val) { + this.val = val; + this.next = null; +} + +// ! 思路错误,不是先算完求和再转换成链表 +var addTwoNumbersold = 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; + 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; + } + } + + return linkNode; +}; + +// Test Algorithm +// var testNum = 5; +// 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]); + + +let addTwoNumbers = function (l1, l2) { + // 定义进位 + let carry = 0; + let p = l1,q=l2; + let numStack = []; + 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]); + +console.log(addTwoNumbers(node1, node2)); \ 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 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 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 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 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{ + 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/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 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 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 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); +}; + + 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 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 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 diff --git a/Leetcode/7.reverseInteger.js b/Leetcode/7.reverseInteger.js new file mode 100644 index 0000000..d5270e8 --- /dev/null +++ b/Leetcode/7.reverseInteger.js @@ -0,0 +1,98 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-23 16:27:45 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-14 20:57:03 + */ + +/***** + * + * 逆序一个整数 + * 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; +}; + + + +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) ]) + }, []) + } +} 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 diff --git a/Leetcode/binaryTesing.js b/Leetcode/binaryTesing.js new file mode 100644 index 0000000..65c86ba --- /dev/null +++ b/Leetcode/binaryTesing.js @@ -0,0 +1,64 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-17 11:05:01 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-17 14:37:43 + */ + + +const arraytoBinaryTree = require('./tools/arrayToBinaryTree'); + + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} + +function Serialize(pRoot) { + // 使用前序遍历的形式访问整个二叉树 + let nodeStr = ''; + if (pRoot === null) { + return '#!'; + } + nodeStr += pRoot.val + '!'; + nodeStr += Serialize(pRoot.left); + nodeStr += Serialize(pRoot.right); + return nodeStr; +} + + +function Deserialize(s) { + + let nodeArr = s.split('!'); + + this.reConnectTree = function (arrays){ + let tempNode = arrays.shift(); + if (tempNode === '#' || tempNode === '') { + return null; + } + console.log(arrays); + let head = new TreeNode(parseInt(tempNode)); + head.left = this.reConnectTree(arrays); + head.right = this.reConnectTree(arrays); + return head; + } + + return this.reConnectTree(nodeArr); + + +} + +let arr1 = [8, 6, 10, 5, 7, 9, 11]; + +let result = arraytoBinaryTree(arr1); +console.log(result); + +console.log("------------------------------------------"); + +let treeStr = Serialize(result); +console.log(treeStr); + + +let reTree = Deserialize(treeStr); +console.log(reTree); \ No newline at end of file diff --git a/Leetcode/testAlg.js b/Leetcode/testAlg.js new file mode 100644 index 0000000..af00cf4 --- /dev/null +++ b/Leetcode/testAlg.js @@ -0,0 +1,381 @@ +/**** + * + * 此方法用于函数测试 + * + * + */ + +const arrayToTreeNode = require('./tools/treeNode'); +// const arrayToLinkNode = require('./tools/LinkNode'); +// const linkToArray = require('./tools/LinkNodetoArray'); + +// 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++; +// 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 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 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 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 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 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 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) { +// 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 = 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 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); + } + + pathArr.sort((a, b) => { + return b.length - a.length; + }) + + return pathArr; +} + + +// let arr1 = [1, 1, 2, 3, 3, 4, 5]; +let arr1 = [5,6,7,8,7,6,5]; +let arr2 = [5, 4, "#", 3, "#", 2]; + +// var tempLink1 = arrayToLinkNode(arr1); +// var tempLink2 = arrayToTreeNode(arr2); +var tempTree = arrayToTreeNode(arr1); +console.log(tempTree); + +let result = FindPath(tempTree, ); +console.log(result); + +console.log(Deserialize(result)); +// console.log(tempLink2); +// var list1 = linkToArray(tempLink1); +// console.log(list1); +// var list2 = PrintFromTopToBottom(tempLink2); +// console.log(list2); + + + +// console.log('递归版本是否平衡二叉树:', IsBalanced_Solution(tempTree)); +// console.log('非递归版本深度:', treeDep(tempTree)); \ No newline at end of file diff --git a/Leetcode/tools/LinkNode.js b/Leetcode/tools/LinkNode.js new file mode 100644 index 0000000..997b08f --- /dev/null +++ b/Leetcode/tools/LinkNode.js @@ -0,0 +1,38 @@ + +/** + * + * 封装将数组转换成链表的方法 + * @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 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/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 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 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/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/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/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 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 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 maxLength) { + maxLength = k; + startPosition = i; + } + } + } + } + if (maxLength > 0) { + 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 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 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 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 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 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;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/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 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/2019SchoolInterview/kuaishou/stringNormalization-kuaishou.js b/NowCoder/2019SchoolInterview/kuaishou/stringNormalization-kuaishou.js new file mode 100644 index 0000000..eb1f839 --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/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 diff --git a/NowCoder/2019SchoolInterview/kuaishou/zipStr.js b/NowCoder/2019SchoolInterview/kuaishou/zipStr.js new file mode 100644 index 0000000..9590ee0 --- /dev/null +++ b/NowCoder/2019SchoolInterview/kuaishou/zipStr.js @@ -0,0 +1,43 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-07 17:08:53 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-07 17:10:23 + */ + +/***** + * + * 对字符串进行RLE压缩,将相邻的相同字符,用计数值和字符值来代替。 + * 例如:aaabccccccddeee,则可用3a1b6c2d3e来代替。 + * + * 输入描述: + * 输入为a-z,A-Z的字符串,且字符串不为空,如aaabccccccddeee + * + * 输出描述: + * + * 压缩后的字符串,如3a1b6c2d3e + * + * + * + */ + + +function zipStr(str){ + let backStr = ''; + let count=1; + for(let i=0;i=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 diff --git a/NowCoder/2019SchoolInterview/mogujie/processStr.js b/NowCoder/2019SchoolInterview/mogujie/processStr.js new file mode 100644 index 0000000..193b1d5 --- /dev/null +++ b/NowCoder/2019SchoolInterview/mogujie/processStr.js @@ -0,0 +1,59 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-07 10:39:50 + * @Last Modified by: SkylineBin + * @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 storeB=[]; + let left,right; + + for (let i = 0; i < len; i++) { + right = len-resStr.indexOf(str[i])-1; + storeB.push([i,right]); + } + storeB.sort((a,b)=>a[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; +} + + +let str = "ababbacadefgdehijhklij"; +console.log(processStr(str)); \ No newline at end of file diff --git a/NowCoder/2019SchoolInterview/momenta/1.js b/NowCoder/2019SchoolInterview/momenta/1.js new file mode 100644 index 0000000..65c4214 --- /dev/null +++ b/NowCoder/2019SchoolInterview/momenta/1.js @@ -0,0 +1,54 @@ +function leastAddNum(numN,numX,datas){ + let current = datas.indexOf(numX); + datas.sort((a,b)=>a-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; 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/findMaxWorkMoney.js b/NowCoder/2019SchoolInterview/neteasy/findMaxWorkMoney.js new file mode 100644 index 0000000..bc1720b --- /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:24:15 + */ + +/*** + * + * 为了找到自己满意的工作,牛牛收集了每种工作的难度和报酬。牛牛选工作的标准是在难度不超过自身能力值的情况下,牛牛选择报酬最高的工作。 + * 在牛牛选定了自己的工作后,牛牛的小伙伴们来找牛牛帮忙选工作,牛牛依然使用自己的标准来帮助小伙伴们。牛牛的小伙伴太多了,于是他只好把这个任务交给了你。 + * + * + * 输入: + * 每个输入包含一个测试用例。 + * 每个测试用例的第一行包含两个正整数,分别表示工作的数量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;jmax){ + 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;i= 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 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 diff --git a/NowCoder/2019SchoolInterview/neteasy/packageKindsOf.js b/NowCoder/2019SchoolInterview/neteasy/packageKindsOf.js new file mode 100644 index 0000000..ffb3c09 --- /dev/null +++ b/NowCoder/2019SchoolInterview/neteasy/packageKindsOf.js @@ -0,0 +1,69 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-25 09:56:58 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-25 10:15:21 + */ + + +/****** + * + * 牛牛准备参加学校组织的春游, 出发前牛牛准备往背包里装入一些零食, 牛牛的背包容量为w。 + * 牛牛家里一共有n袋零食, 第i袋零食体积为v[i]。 + * 牛牛想知道在总体积不超过背包容量的情况下,他一共有多少种零食放法(总体积为0也算一种放法)。 + * + * + * 输入描述: + * + * 输入包括两行 + * 第一行为两个正整数n和w(1 <= n <= 30, 1 <= w <= 2 * 10^9),表示零食的数量和背包的容量。 + * 第二行n个正整数v[i](0 <= v[i] <= 10^9),表示每袋零食的体积。 + * + * 输出描述: + * 输出一个正整数, 表示牛牛一共有多少种零食放法。 + * + * 输入示例: + * + * 3 10 + * 1 2 4 + * + * 输出示例: + * 8 + * + */ + +function findMethods(numN,numW,vols){ + let sum = 0; + let outside = 0; + vols.sort((a,b)=>a-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/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/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;ja-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 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 numX || 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 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(countCCCDC->CCCCD这样就能使之前的两处鸡鸭相邻变为一处鸡鸭相邻,需要调整队形两次。 + * + * 输入描述: + * 输入一个长度为N,且只包含C和D的非空字符串。 + * + * 输出描述: + * 使得最后仅有一对鸡鸭相邻,最少的交换次数 + * + * 输入: + * CCDCC + * + * 输出: + * 2 + * + * 类似快慢指针的思想 + * + * 测试用例里面全是 C在左D在右的 + * + * + * + */ + + +// 第一个简单版本 + +function minChangeTime(data){ + let times = 0,count=0; + for(let i=0;i= 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 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/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(count480?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..460ea54 --- /dev/null +++ b/NowCoder/2020RealTime/DJI/2.js @@ -0,0 +1,150 @@ + +/***** + * + * 零食问题,最大满意度 + * + * + * + */ + + +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 zeroOnePackage(datas,values,maxValue){ + let len = values.length; + let dps = []; + for (let i = 0; i <=len; i++) { + dps[i]=[]; + dps[i][0]=0; + } + let a,b; + for (let j = 0; j <=len; j++) { + for (let k = 0; k <=maxValue; k++) { + if (j===0 || k===0) { + dps[j][k]=0; + }else if(datas[j-1]b?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)); + + +// 多重背包问题 + + + + + +// 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/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/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(indexa-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(sumLeftmax){ + 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/byteDance/0705-1.js b/NowCoder/2020RealTime/byteDance/0705-1.js new file mode 100644 index 0000000..cebcad0 --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/0705-1.js @@ -0,0 +1,71 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-05 20:45:34 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 16:43:38 + */ + + +/****** + * + * 两人随机平分 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 diff --git a/NowCoder/2020RealTime/byteDance/0705-2.js b/NowCoder/2020RealTime/byteDance/0705-2.js new file mode 100644 index 0000000..f4e5882 --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/0705-2.js @@ -0,0 +1,32 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-05 21:26:33 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 16:40:27 + */ + + +/***** + * + * 计算日期到 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('-'))); + // 以毫秒计数,要除以1000来计算间隔的天数 + 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 diff --git a/NowCoder/2020RealTime/byteDance/0705-3.js b/NowCoder/2020RealTime/byteDance/0705-3.js new file mode 100644 index 0000000..5c20f77 --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/0705-3.js @@ -0,0 +1,51 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-05 21:42:07 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 16:39:42 + */ + +/**** + * + * 最少班级问题 + * + * 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; + // 求n个数的最大公约数 + 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 diff --git a/NowCoder/2020RealTime/byteDance/0705-4.js b/NowCoder/2020RealTime/byteDance/0705-4.js new file mode 100644 index 0000000..76f7649 --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/0705-4.js @@ -0,0 +1,68 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-06 12:58:14 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 16:38:19 + */ + + +/***** + * + * + * 道路规划问题 + * + * + * + */ + +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; + } + } + 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 diff --git a/NowCoder/2020RealTime/byteDance/0705-5.js b/NowCoder/2020RealTime/byteDance/0705-5.js new file mode 100644 index 0000000..f1ae8d8 --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/0705-5.js @@ -0,0 +1,78 @@ +/* + * @Author: SkylineBin + * @Date: 2019-07-06 15:47:41 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-06 16:35:47 + */ + + +/**** + * + * 网络节点之间的最大时延问题 + * + * + * + */ + + +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]); + } + // 将m,n位置填满 + 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 diff --git a/NowCoder/2020RealTime/byteDance/0707-1.js b/NowCoder/2020RealTime/byteDance/0707-1.js new file mode 100644 index 0000000..7c788f8 --- /dev/null +++ b/NowCoder/2020RealTime/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/2020RealTime/byteDance/0707-4.js b/NowCoder/2020RealTime/byteDance/0707-4.js new file mode 100644 index 0000000..c8bb8e2 --- /dev/null +++ b/NowCoder/2020RealTime/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)); 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(counta-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/crazyCowProblem-byteDance.js b/NowCoder/2020RealTime/byteDance/crazyCowProblem-byteDance.js new file mode 100644 index 0000000..e5f4edb --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/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/2020RealTime/byteDance/exam b/NowCoder/2020RealTime/byteDance/exam new file mode 100644 index 0000000..e69de29 diff --git a/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js b/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js new file mode 100644 index 0000000..0ce752b --- /dev/null +++ b/NowCoder/2020RealTime/byteDance/findPrime-byteDance.js @@ -0,0 +1,128 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-30 21:53:06 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-23 16:41:27 + */ + + + +/** + * + * + * 找出小于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 diff --git a/NowCoder/2020RealTime/byteDance/test.js b/NowCoder/2020RealTime/byteDance/test.js new file mode 100644 index 0000000..20808a5 --- /dev/null +++ b/NowCoder/2020RealTime/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 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/htmltime-oneWallet.html b/NowCoder/2020RealTime/htmltime-oneWallet.html new file mode 100644 index 0000000..af06851 --- /dev/null +++ b/NowCoder/2020RealTime/htmltime-oneWallet.html @@ -0,0 +1,21 @@ + + + + + time + + +

+ Current Time: +
+

+ + + \ No newline at end of file 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/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=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/jd/1.js b/NowCoder/2020RealTime/jd/1.js new file mode 100644 index 0000000..a7e0d48 --- /dev/null +++ b/NowCoder/2020RealTime/jd/1.js @@ -0,0 +1,115 @@ +function countMinTimes(n,str){ + let count=0; + function isLittle(s){ + if(s>="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/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;ia-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;j0) { + 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)); + + + +// 按次数,并非按层 +// 此时是按照层展开 +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 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..b86c137 --- /dev/null +++ b/NowCoder/2020RealTime/pufa/xiangThree.js @@ -0,0 +1,70 @@ +// 大数相加 +// big datas add function + +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/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 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 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 +#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/vivo/vivo1.js b/NowCoder/2020RealTime/vivo/vivo1.js new file mode 100644 index 0000000..f75830b --- /dev/null +++ b/NowCoder/2020RealTime/vivo/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/2020RealTime/vivo/vivo2.js b/NowCoder/2020RealTime/vivo/vivo2.js new file mode 100644 index 0000000..a9ee5bf --- /dev/null +++ b/NowCoder/2020RealTime/vivo/vivo2.js @@ -0,0 +1 @@ +// 链表指定位置逆序 \ No newline at end of file diff --git a/NowCoder/2020RealTime/vivo/vivo3.js b/NowCoder/2020RealTime/vivo/vivo3.js new file mode 100644 index 0000000..48ca1dd --- /dev/null +++ b/NowCoder/2020RealTime/vivo/vivo3.js @@ -0,0 +1,60 @@ +/**** + * + * 使用 动态规划的思想 实现 背包问题 + * 背包问题实质是 组合优化问题 + * + * + */ + + + + +//请把代码实现写在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]; + +let arr1 = [20]; +let arr2 = [5,3,2,10,4,8]; +let arr3 = [4,8,15,1,6,3]; + + +console.log(solution(arr1, arr2, arr3)); \ No newline at end of file diff --git a/NowCoder/2020RealTime/xiaohongshu/1.js b/NowCoder/2020RealTime/xiaohongshu/1.js new file mode 100644 index 0000000..c6ea231 --- /dev/null +++ b/NowCoder/2020RealTime/xiaohongshu/1.js @@ -0,0 +1,39 @@ +function processStr(str){ + var output=[]; + var state=true; + var count=0; + for(var i=0;i0){ + 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 "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{ + + 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 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(k=0 && j<= lenc-1) { + if (array[i][j] < target) { + j++; + } else if (array[i][j] > target) { + i--; + } else { + return true; + } + } + return false; +} diff --git a/NowCoder/CodingInterviews/10.recCover.js b/NowCoder/CodingInterviews/10.recCover.js new file mode 100644 index 0000000..167c1c7 --- /dev/null +++ b/NowCoder/CodingInterviews/10.recCover.js @@ -0,0 +1,92 @@ +/*** + * + * 我们可以用2 * 1 的小矩形横着或者竖着去覆盖更大的矩形。 + * 请问用 n个2 * 1 的小矩形无重叠地覆盖一个2 * n的大矩形, + * 总共有多少种方法? + * + * +*/ + +// ! 本质:斐波拉契数列 + +// 最简单版本 暴力递归 算法复杂度 O(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); + } +} + +// 中级版本 算法复杂度 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 +var testNum = 3; +console.log(rectCover(testNum)); // 0 +console.log(rectCover2(testNum)); // 0 +console.log(rectCover3(testNum)); // 0 \ No newline at end of file diff --git a/NowCoder/CodingInterviews/11.numberOf1.js b/NowCoder/CodingInterviews/11.numberOf1.js new file mode 100644 index 0000000..112a20c --- /dev/null +++ b/NowCoder/CodingInterviews/11.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/CodingInterviews/12.doublePower.js b/NowCoder/CodingInterviews/12.doublePower.js new file mode 100644 index 0000000..99930b2 --- /dev/null +++ b/NowCoder/CodingInterviews/12.doublePower.js @@ -0,0 +1,77 @@ +/**** + * + * 给定一个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 + + /* + * 涉及理论: 递归、边界 + * 普通解法: 判断+遍历 + * 改进方向: + * + * + */ + +// 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/CodingInterviews/13.reOrderArray.js b/NowCoder/CodingInterviews/13.reOrderArray.js new file mode 100644 index 0000000..9309cc6 --- /dev/null +++ b/NowCoder/CodingInterviews/13.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 diff --git a/NowCoder/CodingInterviews/14.findKthToTail.js b/NowCoder/CodingInterviews/14.findKthToTail.js new file mode 100644 index 0000000..7a48d3d --- /dev/null +++ b/NowCoder/CodingInterviews/14.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/CodingInterviews/15.ReverseList.js b/NowCoder/CodingInterviews/15.ReverseList.js new file mode 100644 index 0000000..5ce0e55 --- /dev/null +++ b/NowCoder/CodingInterviews/15.ReverseList.js @@ -0,0 +1,36 @@ +/*** + * + * @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 diff --git a/NowCoder/CodingInterviews/16.mergeTwosortedLink.js b/NowCoder/CodingInterviews/16.mergeTwosortedLink.js new file mode 100644 index 0000000..d4f6a40 --- /dev/null +++ b/NowCoder/CodingInterviews/16.mergeTwosortedLink.js @@ -0,0 +1,77 @@ +/******* + * + * 合并两有序的链表 + * + * 输入两个单调递增的链表,输出两个链表合成后的链表, + * 当然我们需要合成后的链表满足单调不减规则。 + * + */ + +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; +} + + +// 递归版本的做法 +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/CodingInterviews/17.hasSubtree.js b/NowCoder/CodingInterviews/17.hasSubtree.js new file mode 100644 index 0000000..125480c --- /dev/null +++ b/NowCoder/CodingInterviews/17.hasSubtree.js @@ -0,0 +1,46 @@ +/**** + * + * 输入两棵二叉树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; + } + 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; +} \ No newline at end of file diff --git a/NowCoder/CodingInterviews/18.mirrorTree.js b/NowCoder/CodingInterviews/18.mirrorTree.js new file mode 100644 index 0000000..4c44c1f --- /dev/null +++ b/NowCoder/CodingInterviews/18.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 diff --git a/NowCoder/CodingInterviews/19.printMatrixbyClockwise.js b/NowCoder/CodingInterviews/19.printMatrixbyClockwise.js new file mode 100644 index 0000000..0ceb732 --- /dev/null +++ b/NowCoder/CodingInterviews/19.printMatrixbyClockwise.js @@ -0,0 +1,109 @@ +/****** + * + * 顺时针打印矩阵 + * + * 输入一个矩阵, 按照从外向里以顺时针的顺序依次打印出每一个数字, + * 例如, 如果输入如下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; +} + + +// 使用经典思路解答矩阵打印问题 +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]; +// 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)); +console.log(printMatrix2(matrix)); \ No newline at end of file diff --git a/NowCoder/CodingInterviews/2.replaceSpaceinString.js b/NowCoder/CodingInterviews/2.replaceSpaceinString.js new file mode 100644 index 0000000..bae9a10 --- /dev/null +++ b/NowCoder/CodingInterviews/2.replaceSpaceinString.js @@ -0,0 +1,23 @@ +/**** + * + * 请实现一个函数, 将一个字符串中的每个空格替换成“ % 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; +} + +/* + * 涉及理论: 字符串处理 + * 普通解法: 替换 + * 改进方向: + * + * + */ diff --git a/NowCoder/CodingInterviews/20.createMinStackStructure.js b/NowCoder/CodingInterviews/20.createMinStackStructure.js new file mode 100644 index 0000000..f77f82c --- /dev/null +++ b/NowCoder/CodingInterviews/20.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 diff --git a/NowCoder/CodingInterviews/21.isPopOrder.js b/NowCoder/CodingInterviews/21.isPopOrder.js new file mode 100644 index 0000000..9f745a1 --- /dev/null +++ b/NowCoder/CodingInterviews/21.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 diff --git a/NowCoder/CodingInterviews/22.printTreeFromTopToBottom.js b/NowCoder/CodingInterviews/22.printTreeFromTopToBottom.js new file mode 100644 index 0000000..6f43712 --- /dev/null +++ b/NowCoder/CodingInterviews/22.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 diff --git a/NowCoder/CodingInterviews/23.verifySquenceOfBST.js b/NowCoder/CodingInterviews/23.verifySquenceOfBST.js new file mode 100644 index 0000000..31bed97 --- /dev/null +++ b/NowCoder/CodingInterviews/23.verifySquenceOfBST.js @@ -0,0 +1,38 @@ +/****** + * + * + * 输入一个整数数组, 判断该数组是不是某二叉搜索树的后序遍历的结果。 + * 如果是则输出Yes, 否则输出No。 假设输入的数组的任意两个数字都互不相同。 + * + * + */ + +function VerifySquenceOfBST(sequence) { + 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 diff --git a/NowCoder/CodingInterviews/24.findPathofBinary.js b/NowCoder/CodingInterviews/24.findPathofBinary.js new file mode 100644 index 0000000..a323b44 --- /dev/null +++ b/NowCoder/CodingInterviews/24.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; +} diff --git a/NowCoder/CodingInterviews/25.cloneComplexLinkList.js b/NowCoder/CodingInterviews/25.cloneComplexLinkList.js new file mode 100644 index 0000000..c5fea4c --- /dev/null +++ b/NowCoder/CodingInterviews/25.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 diff --git a/NowCoder/CodingInterviews/26.convertBinaryTreetoDoubleLinkList.js b/NowCoder/CodingInterviews/26.convertBinaryTreetoDoubleLinkList.js new file mode 100644 index 0000000..46aab74 --- /dev/null +++ b/NowCoder/CodingInterviews/26.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 diff --git a/NowCoder/CodingInterviews/27.permutationString.js b/NowCoder/CodingInterviews/27.permutationString.js new file mode 100644 index 0000000..4f527f9 --- /dev/null +++ b/NowCoder/CodingInterviews/27.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 diff --git a/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js b/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js new file mode 100644 index 0000000..8ba99a4 --- /dev/null +++ b/NowCoder/CodingInterviews/28.moreThanHalfNum_Solution.js @@ -0,0 +1,35 @@ +/****** + * + * + * 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 + * 例如输入一个长度为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++) { + // 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) { + 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 diff --git a/NowCoder/CodingInterviews/29.getLeastNumbers_Solution.js b/NowCoder/CodingInterviews/29.getLeastNumbers_Solution.js new file mode 100644 index 0000000..fa58ca9 --- /dev/null +++ b/NowCoder/CodingInterviews/29.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)); + +// 快速排序方法待补充 + + + +// 堆排序方法可以尝试 diff --git a/NowCoder/CodingInterviews/3.shiftListNode.js b/NowCoder/CodingInterviews/3.shiftListNode.js new file mode 100644 index 0000000..1b63a20 --- /dev/null +++ b/NowCoder/CodingInterviews/3.shiftListNode.js @@ -0,0 +1,26 @@ +/**** + * + * 输入一个链表, 按链表值从尾到头的顺序返回一个ArrayList。 + * + * + */ + +// first version + +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/CodingInterviews/30.findGreatestSumOfSubArray.js b/NowCoder/CodingInterviews/30.findGreatestSumOfSubArray.js new file mode 100644 index 0000000..36c3886 --- /dev/null +++ b/NowCoder/CodingInterviews/30.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 diff --git a/NowCoder/CodingInterviews/31.numberOf1Between1AndN_Solution.js b/NowCoder/CodingInterviews/31.numberOf1Between1AndN_Solution.js new file mode 100644 index 0000000..881f437 --- /dev/null +++ b/NowCoder/CodingInterviews/31.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 diff --git a/NowCoder/CodingInterviews/32.PrintConnectMinNumberofArray.js b/NowCoder/CodingInterviews/32.PrintConnectMinNumberofArray.js new file mode 100644 index 0000000..801ad50 --- /dev/null +++ b/NowCoder/CodingInterviews/32.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 diff --git a/NowCoder/CodingInterviews/33.getUglyNumber_Solution.js b/NowCoder/CodingInterviews/33.getUglyNumber_Solution.js new file mode 100644 index 0000000..d1a525e --- /dev/null +++ b/NowCoder/CodingInterviews/33.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 diff --git a/NowCoder/CodingInterviews/34.firstNotRepeatingChar.js b/NowCoder/CodingInterviews/34.firstNotRepeatingChar.js new file mode 100644 index 0000000..ebbb73f --- /dev/null +++ b/NowCoder/CodingInterviews/34.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 diff --git a/NowCoder/CodingInterviews/35.inversePairsNum.js b/NowCoder/CodingInterviews/35.inversePairsNum.js new file mode 100644 index 0000000..f6c653c --- /dev/null +++ b/NowCoder/CodingInterviews/35.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)); diff --git a/NowCoder/CodingInterviews/36.findFirstCommonNodeofLinkNode.js b/NowCoder/CodingInterviews/36.findFirstCommonNodeofLinkNode.js new file mode 100644 index 0000000..828f452 --- /dev/null +++ b/NowCoder/CodingInterviews/36.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 diff --git a/NowCoder/CodingInterviews/37.getNumberOfK.js b/NowCoder/CodingInterviews/37.getNumberOfK.js new file mode 100644 index 0000000..9d0f5a8 --- /dev/null +++ b/NowCoder/CodingInterviews/37.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 diff --git a/NowCoder/CodingInterviews/38.treeDepth.js b/NowCoder/CodingInterviews/38.treeDepth.js new file mode 100644 index 0000000..497285c --- /dev/null +++ b/NowCoder/CodingInterviews/38.treeDepth.js @@ -0,0 +1,50 @@ +/**** + * + * 已知一个二叉树,求二叉树的深度 + * 输入一棵二叉树, 求该树的深度。 从根结点到叶结点依次经过的结点( 含根、 叶结点) 形成树的一条路径, 最长路径的长度为树的深度。 + * + */ + + +// 递归解法 + +/* 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++; + let tempLen = treearr.length; // 这一层是两个结点还是有一个结点 + for (let i = 0; i < tempLen; i++) { + let tempNode = treearr[0]; + treearr = treearr.slice(1); // 以上两步实现的是队列的 pop 操作 + if (tempNode.left !== null) { + treearr.push(tempNode.left); + } + if (tempNode.right !== null) { + treearr.push(tempNode.right); + } + } + } + return depth; +} \ No newline at end of file diff --git a/NowCoder/CodingInterviews/39.isBalancedTree.js b/NowCoder/CodingInterviews/39.isBalancedTree.js new file mode 100644 index 0000000..3f7ba03 --- /dev/null +++ b/NowCoder/CodingInterviews/39.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/CodingInterviews/4.reConstructBinaryTree.js b/NowCoder/CodingInterviews/4.reConstructBinaryTree.js new file mode 100644 index 0000000..01be862 --- /dev/null +++ b/NowCoder/CodingInterviews/4.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 diff --git a/NowCoder/CodingInterviews/40.findNumsAppearOnce.js b/NowCoder/CodingInterviews/40.findNumsAppearOnce.js new file mode 100644 index 0000000..ba8c927 --- /dev/null +++ b/NowCoder/CodingInterviews/40.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 diff --git a/NowCoder/CodingInterviews/41.findContinuousSequence.js b/NowCoder/CodingInterviews/41.findContinuousSequence.js new file mode 100644 index 0000000..7050b9f --- /dev/null +++ b/NowCoder/CodingInterviews/41.findContinuousSequence.js @@ -0,0 +1,76 @@ +/****** + * + * 小明很喜欢数学, 有一天他在做数学作业时, 要求计算出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)); + +// 双指针思路解法,算法复杂度较低 + +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 diff --git a/NowCoder/CodingInterviews/42.findNumbersWithSum.js b/NowCoder/CodingInterviews/42.findNumbersWithSum.js new file mode 100644 index 0000000..d86d20d --- /dev/null +++ b/NowCoder/CodingInterviews/42.findNumbersWithSum.js @@ -0,0 +1,37 @@ +/*** +* +* 输入一个递增排序的数组和一个数字S, 在数组中查找两个数, +* 使得他们的和正好是S, 如果有多对数字的和等于S, +* 输出两个数的乘积最小的。 +* +* +***/ +// ! 本质涉及: 排序算法 + +// ! 和均为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 +var testNum = [1,2,3,4,5,6,7,8,9,10]; +console.log(FindNumbersWithSum(testNum, 9)); \ No newline at end of file diff --git a/NowCoder/CodingInterviews/43.loopLeftRotateStr.js b/NowCoder/CodingInterviews/43.loopLeftRotateStr.js new file mode 100644 index 0000000..6bd7447 --- /dev/null +++ b/NowCoder/CodingInterviews/43.loopLeftRotateStr.js @@ -0,0 +1,54 @@ +/** + * + * 汇编语言中有一种移位指令叫做循环左移( 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('------------------------------------'); + +/* + * 涉及理论: 字符串处理 + * 普通解法: 拼接 + * 改进方向: + * + * + */ diff --git a/NowCoder/CodingInterviews/44.reverseWords.js b/NowCoder/CodingInterviews/44.reverseWords.js new file mode 100644 index 0000000..0d3fc54 --- /dev/null +++ b/NowCoder/CodingInterviews/44.reverseWords.js @@ -0,0 +1,29 @@ +/*** + * 牛客最近来了一个新员工Fish, 每天早晨总是会拿着一本英文杂志, 写些句子在本子上。 + * 同事Cat对Fish写的内容颇感兴趣, 有一天他向Fish借来翻看, 但却读不懂它的意思。 + * 例如,“ student.a am I”。 后来才意识到, 这家伙原来把句子单词的顺序翻转了, + * 正确的句子应该是“ I am a student.”。 + * + * + */ + +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('------------------------------------'); + +/* + * 涉及理论: 字符串处理 + * 普通解法: 使用 reverse 函数 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/CodingInterviews/45.isContinuous.js b/NowCoder/CodingInterviews/45.isContinuous.js new file mode 100644 index 0000000..e504be8 --- /dev/null +++ b/NowCoder/CodingInterviews/45.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 diff --git a/NowCoder/CodingInterviews/46.lastRemaining_Solution.js b/NowCoder/CodingInterviews/46.lastRemaining_Solution.js new file mode 100644 index 0000000..3fb048d --- /dev/null +++ b/NowCoder/CodingInterviews/46.lastRemaining_Solution.js @@ -0,0 +1,65 @@ +/****** + * + * 圆圈中最后一个数 + * + * 每年六一儿童节, 牛客都会准备一些小礼物去看望孤儿院的小朋友, 今年亦是如此。 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)); + +// 约瑟夫环问题 解决方案 + diff --git a/NowCoder/CodingInterviews/47.sum_Solution.js b/NowCoder/CodingInterviews/47.sum_Solution.js new file mode 100644 index 0000000..51b2224 --- /dev/null +++ b/NowCoder/CodingInterviews/47.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 diff --git a/NowCoder/CodingInterviews/48.addTwoNum.js b/NowCoder/CodingInterviews/48.addTwoNum.js new file mode 100644 index 0000000..64d245a --- /dev/null +++ b/NowCoder/CodingInterviews/48.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 diff --git a/NowCoder/CodingInterviews/49.strToInt.js b/NowCoder/CodingInterviews/49.strToInt.js new file mode 100644 index 0000000..9590836 --- /dev/null +++ b/NowCoder/CodingInterviews/49.strToInt.js @@ -0,0 +1,45 @@ +/****** + * + * 将一个字符串转换成一个整数(实现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; // 用于判断该数是正是负 + 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; +} + +let str = '+2147483647'; +let str1 = '1a33'; +console.log(StrToInt(str1)); \ No newline at end of file diff --git a/NowCoder/CodingInterviews/5.useTwoStackCreatQueue.js b/NowCoder/CodingInterviews/5.useTwoStackCreatQueue.js new file mode 100644 index 0000000..b882e69 --- /dev/null +++ b/NowCoder/CodingInterviews/5.useTwoStackCreatQueue.js @@ -0,0 +1,42 @@ +/**** + * + * 用两个栈来实现一个队列, 完成队列的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(); + } +} + +function isEmpty(){ + if(stack2.length===0 && stack1.length===0){ + return true; + }else{ + return false; + } +} + +/* + * 涉及理论: 队列 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/CodingInterviews/50.duplicate.js b/NowCoder/CodingInterviews/50.duplicate.js new file mode 100644 index 0000000..e1dc32d --- /dev/null +++ b/NowCoder/CodingInterviews/50.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 diff --git a/NowCoder/CodingInterviews/51.multiply.js b/NowCoder/CodingInterviews/51.multiply.js new file mode 100644 index 0000000..4dd8b04 --- /dev/null +++ b/NowCoder/CodingInterviews/51.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 diff --git a/NowCoder/CodingInterviews/52.matchParren.js b/NowCoder/CodingInterviews/52.matchParren.js new file mode 100644 index 0000000..35e2e35 --- /dev/null +++ b/NowCoder/CodingInterviews/52.matchParren.js @@ -0,0 +1,106 @@ +/******* + * + * 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 + * 在本题中,匹配是指字符串的所有字符匹配整个模式。 + * 例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配, + * 但是与"aa.a"和"ab*a"均不匹配 + * + * + * + */ + +function matchOld(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 matchOld(s.slice(1), pattern.slice(1)); + } else { + return false; + } + } else { + // 当 pattern 的下一个字符是 * + if (s[i] === pattern[i] || (s[i] !== '' && pattern[i] === '.')) { // 都表示当前的这个字符是相同的 + if (pattern[i] === '.') { + return matchOld(String(s[s.length - 1]), String(pattern[pattern.length - 1])); + } + return matchOld(s, pattern.slice(2)) || matchOld(s.slice(1), pattern); + } else { + // 当前字符不相同,下一个是*,*前面的字符可能出现 0 次 + return matchOld(s, pattern.slice(2)); + } + } +} + +// 上述代码未通过 + + +// "bcbbabab",".*a*a" +// var arr1 = 'a'; +// var arr2 = '.'; +// 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/NowCoder/CodingInterviews/53.isNumeric.js b/NowCoder/CodingInterviews/53.isNumeric.js new file mode 100644 index 0000000..c7330cc --- /dev/null +++ b/NowCoder/CodingInterviews/53.isNumeric.js @@ -0,0 +1,69 @@ +/***** + * + * 判断一个字符串是否表示数值 + * + * + * 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 + * 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 + * 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。 + * + * + * + */ + + +// 考虑可能性的解法 +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)); + + +// 使用正则表达式简写 + +function isNumeric2(s) { + let numreg = /^[\+\-]?\d*(\.\d+)?([eE][\+\-]?\d+)?$/; + let result = numreg.test(s); + return result; +} + +// 奇怪的测试用例 +// "-.123" 是对的? + + +console.log(isNumeric2(s)); \ No newline at end of file diff --git a/NowCoder/CodingInterviews/54.firstAppearingOnce.js b/NowCoder/CodingInterviews/54.firstAppearingOnce.js new file mode 100644 index 0000000..bc6d9e4 --- /dev/null +++ b/NowCoder/CodingInterviews/54.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 diff --git a/NowCoder/CodingInterviews/55.entryNodeOfLoop.js b/NowCoder/CodingInterviews/55.entryNodeOfLoop.js new file mode 100644 index 0000000..9f079cc --- /dev/null +++ b/NowCoder/CodingInterviews/55.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 diff --git a/NowCoder/CodingInterviews/56.deleteDuplicationLinkNode.js b/NowCoder/CodingInterviews/56.deleteDuplicationLinkNode.js new file mode 100644 index 0000000..abcad44 --- /dev/null +++ b/NowCoder/CodingInterviews/56.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 diff --git a/NowCoder/CodingInterviews/57.getNextNode.js b/NowCoder/CodingInterviews/57.getNextNode.js new file mode 100644 index 0000000..8c3efef --- /dev/null +++ b/NowCoder/CodingInterviews/57.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 diff --git a/NowCoder/CodingInterviews/58.isSymmetrical.js b/NowCoder/CodingInterviews/58.isSymmetrical.js new file mode 100644 index 0000000..dcb4a59 --- /dev/null +++ b/NowCoder/CodingInterviews/58.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 diff --git a/NowCoder/CodingInterviews/59.printTreewithZhizi.js b/NowCoder/CodingInterviews/59.printTreewithZhizi.js new file mode 100644 index 0000000..3566d77 --- /dev/null +++ b/NowCoder/CodingInterviews/59.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 diff --git a/NowCoder/CodingInterviews/6.minNumberInRotateArray.js b/NowCoder/CodingInterviews/6.minNumberInRotateArray.js new file mode 100644 index 0000000..d9aa320 --- /dev/null +++ b/NowCoder/CodingInterviews/6.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 diff --git a/NowCoder/CodingInterviews/60.printTreebyLayer.js b/NowCoder/CodingInterviews/60.printTreebyLayer.js new file mode 100644 index 0000000..3be740a --- /dev/null +++ b/NowCoder/CodingInterviews/60.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 diff --git a/NowCoder/CodingInterviews/61.serializeAndSerialize.js b/NowCoder/CodingInterviews/61.serializeAndSerialize.js new file mode 100644 index 0000000..a48c0a5 --- /dev/null +++ b/NowCoder/CodingInterviews/61.serializeAndSerialize.js @@ -0,0 +1,52 @@ +/****** + * + * 将二叉树序列化 和 反序列化 + * + * 请实现两个函数, 分别用来序列化和反序列化二叉树 + * + * + * + */ + + +// 根据前序遍历规则完成序列化与反序列化。 +// 所谓序列化指的是遍历二叉树为字符串; 所谓反序列化指的是依据字符串重新构造成二叉树。 +// 依据前序遍历序列来序列化二叉树, 因为前序遍历序列是从根结点开始的。 当在遍历二叉树时碰到Null指针时, 这些Null指针被序列化为一个特殊的字符“#”。 +// 另外, 结点之间的数值用逗号隔开。 + + +function TreeNode(x) { + this.val = x; + this.left = null; + this.right = null; +} +function Serialize(pRoot) { + // 使用前序遍历的形式访问整个二叉树 + let nodeStr = ''; + if (pRoot === null) { + return '#!'; + } + nodeStr += pRoot.val + '!'; + nodeStr += Serialize(pRoot.left); + nodeStr += Serialize(pRoot.right); + return nodeStr; +} + + +function 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 this.reConnectTree(nodeArr); +} diff --git a/NowCoder/CodingInterviews/62.kthSmallNode.js b/NowCoder/CodingInterviews/62.kthSmallNode.js new file mode 100644 index 0000000..63a5226 --- /dev/null +++ b/NowCoder/CodingInterviews/62.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 diff --git a/NowCoder/CodingInterviews/63.getMidim.js b/NowCoder/CodingInterviews/63.getMidim.js new file mode 100644 index 0000000..e995efd --- /dev/null +++ b/NowCoder/CodingInterviews/63.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); diff --git a/NowCoder/CodingInterviews/64.maxInWindows.js b/NowCoder/CodingInterviews/64.maxInWindows.js new file mode 100644 index 0000000..1f0c809 --- /dev/null +++ b/NowCoder/CodingInterviews/64.maxInWindows.js @@ -0,0 +1,41 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-09 20:20:53 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-05-09 20:42:08 + * + */ + +/**** + * + * 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。 + * 例如,如果输入数组{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 diff --git a/NowCoder/CodingInterviews/65.hasPath.js b/NowCoder/CodingInterviews/65.hasPath.js new file mode 100644 index 0000000..1585cf7 --- /dev/null +++ b/NowCoder/CodingInterviews/65.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/CodingInterviews/66.movingCountRobot.js b/NowCoder/CodingInterviews/66.movingCountRobot.js new file mode 100644 index 0000000..c7ab388 --- /dev/null +++ b/NowCoder/CodingInterviews/66.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 diff --git a/NowCoder/CodingInterviews/7.outputFibonacci.js b/NowCoder/CodingInterviews/7.outputFibonacci.js new file mode 100644 index 0000000..3f9f972 --- /dev/null +++ b/NowCoder/CodingInterviews/7.outputFibonacci.js @@ -0,0 +1,69 @@ +/**** + * + * 大家都知道斐波那契数列, 现在要求输入一个整数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; + } +} + +let n = 39; +console.log(Fibonacci(n)); + +/* + * 涉及理论: 循环 + * 普通解法: 遍历 + * 改进方向:尾递归 + * + * + */ + +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 diff --git a/NowCoder/CodingInterviews/8.jumpStep.js b/NowCoder/CodingInterviews/8.jumpStep.js new file mode 100644 index 0000000..16bedf4 --- /dev/null +++ b/NowCoder/CodingInterviews/8.jumpStep.js @@ -0,0 +1,55 @@ +/**** + * + * @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); + } + +} + + +/* + * 涉及理论: 递归 + * 普通解法: 遍历 + * 改进方向:将递归换成非递归 + * + * + */ + +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 diff --git a/NowCoder/CodingInterviews/9.jumpStepII.js b/NowCoder/CodingInterviews/9.jumpStepII.js new file mode 100644 index 0000000..2981908 --- /dev/null +++ b/NowCoder/CodingInterviews/9.jumpStepII.js @@ -0,0 +1,30 @@ +/**** + * + * @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 2*jumpFloorII(number - 1); + } +} + + +/* + * 涉及理论: 递归 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file diff --git a/NowCoder/CodingInterviews/findSumfromArray.js b/NowCoder/CodingInterviews/findSumfromArray.js new file mode 100644 index 0000000..85b109e --- /dev/null +++ b/NowCoder/CodingInterviews/findSumfromArray.js @@ -0,0 +1,56 @@ +/** +*输入一个递增排序的数组和一个数字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]; + } + } +} + + + /* + * 涉及理论: 搜索及排序 + * 普通解法: 遍历 + * 改进方向: + * + * + */ \ No newline at end of file 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 args.reduce((a,b)=>a+b); +console.log(useArgumentsES6(1,2,3,4,5,6)); \ No newline at end of file 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 diff --git a/NowCoder/JavaScriptAbility/executionEnvironmentContext.js b/NowCoder/JavaScriptAbility/executionEnvironmentContext.js new file mode 100644 index 0000000..085d93e --- /dev/null +++ b/NowCoder/JavaScriptAbility/executionEnvironmentContext.js @@ -0,0 +1,11 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-27 21:18:48 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-27 21:18:48 + */ + + +function speak(fn, obj) { + return fn.call(obj); +} \ No newline at end of file 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/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 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 diff --git a/NowCoder/JavaScriptAbility/returnFunction.js b/NowCoder/JavaScriptAbility/returnFunction.js new file mode 100644 index 0000000..216d07e --- /dev/null +++ b/NowCoder/JavaScriptAbility/returnFunction.js @@ -0,0 +1,15 @@ +/* + * @Author: SkylineBin + * @Date: 2019-06-27 21:23:33 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-06-27 21:24:47 + */ + + +function functionFunction(str) { + return function(str2){ + return str+', '+str2; + }; +} + +console.log(functionFunction('Hello')('world')); \ No newline at end of file diff --git a/NowCoder/RealInterviewExamination/MinimumReturnSubstring.js b/NowCoder/RealInterviewExamination/MinimumReturnSubstring.js new file mode 100644 index 0000000..f508807 --- /dev/null +++ b/NowCoder/RealInterviewExamination/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/RealInterviewExamination/checkIfLinkListPalindrome.js b/NowCoder/RealInterviewExamination/checkIfLinkListPalindrome.js new file mode 100644 index 0000000..a848887 --- /dev/null +++ b/NowCoder/RealInterviewExamination/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/RealInterviewExamination/commonPartOfTwoLinkList.js b/NowCoder/RealInterviewExamination/commonPartOfTwoLinkList.js new file mode 100644 index 0000000..7fef710 --- /dev/null +++ b/NowCoder/RealInterviewExamination/commonPartOfTwoLinkList.js @@ -0,0 +1,41 @@ +/* + * @Author: SkylineBin + * @Date: 2019-05-13 09:26:26 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-07-12 15:29:01 + */ + + +/****** + * + * 打印两个有序链表的公共部分 + * + * + */ + +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/RealInterviewExamination/findMaxEvenStrLength.js b/NowCoder/RealInterviewExamination/findMaxEvenStrLength.js new file mode 100644 index 0000000..8376359 --- /dev/null +++ b/NowCoder/RealInterviewExamination/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;iplugins.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 diff --git a/NowCoder/RealInterviewExamination/findMaxLengthDNA.js b/NowCoder/RealInterviewExamination/findMaxLengthDNA.js new file mode 100644 index 0000000..5b96b61 --- /dev/null +++ b/NowCoder/RealInterviewExamination/findMaxLengthDNA.js @@ -0,0 +1,39 @@ +/**** + * + * 查找最长DNA子字符串 + * + * 2019.06.19 + * + */ + + +function findMaxLengthDNA(str){ + let backLen = 0; + this.dfs = function(tempStr,num){ + let temp = tempStr[0]; + tempStr = tempStr.substring(1,tempStr.length); + let state = false; + if(temp === 'A' || temp === 'T' || temp === 'C' || temp === 'G'){ + num++; + state = true; + } + if (num > backLen){ + backLen = num; + } + if (tempStr.length > 0 && state){ + this.dfs(tempStr,num); + } + return; + } + for(let i=0;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; +} + +// 需要使用数组 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); + actionRecord[0] = currentAction; + return 1; + } + return 0; +} + +console.log(hanoiAdvanceProblemsWithoutRecursion(layerNum, left, middle, right)); \ No newline at end of file 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 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 diff --git a/NowCoder/RealInterviewExamination/reverseStackByRecursion.js b/NowCoder/RealInterviewExamination/reverseStackByRecursion.js new file mode 100644 index 0000000..89c43a2 --- /dev/null +++ b/NowCoder/RealInterviewExamination/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/RealInterviewExamination/sortStackByStack.js b/NowCoder/RealInterviewExamination/sortStackByStack.js new file mode 100644 index 0000000..45cc3e1 --- /dev/null +++ b/NowCoder/RealInterviewExamination/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 diff --git a/README.md b/README.md index 8518353..b8148f1 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,35 @@ -# HuaWeiOJAlgorithm -Some algorithms from learning HuaWeiOJ +# 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 + +## Algorithms +此项目还包括一些基础算法的实现思路记录,以及计算机原理里面的磁盘调度算法,群智能优化算法等等 + +Carrying out disk scheduling algorithm by Java. + + +## LeetCode + +`LeetCode` 与 `NowCoder\Leetcode` 目录中都是 LeetCode 算法题的实现 + +## HuaWeiOJ Algorithms +很久以前华为OJ平台的一些算法题实现 +Some algorithms solved by Python2.7 from HuaWeiOJ Projects + + + 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)); diff --git a/TestProjects/ACMOJ/checkArray.js b/TestProjects/ACMOJ/checkArray.js new file mode 100644 index 0000000..ab3f47b --- /dev/null +++ b/TestProjects/ACMOJ/checkArray.js @@ -0,0 +1,67 @@ +/* + * @Author: SkylineBin + * @Date: 2019-08-02 16:51:39 + * @Last Modified by: SkylineBin + * @Last Modified time: 2019-08-02 17:36:40 + */ + + +function checkArray(arr){ + let state = false; + let tempState = arr.slice(0); + tempState.sort((a,b)=>a-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 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 diff --git a/TestProjects/ACMOJ/qunaer/1.js b/TestProjects/ACMOJ/qunaer/1.js new file mode 100644 index 0000000..2c61605 --- /dev/null +++ b/TestProjects/ACMOJ/qunaer/1.js @@ -0,0 +1,83 @@ +function checkIfIn(point, edgePoints) { + var x = parseFloat(point[0]), + y = parseFloat(point[1]); + + var state = false; + var lens = edgePoints.length; + for (var i = 0, j = lens - 1; i < lens; j = i++) { + var xi = parseFloat(edgePoints[i][0]), + yi = parseFloat(edgePoints[i][1]); + var xj = parseFloat(edgePoints[j][0]), + yj = parseFloat(edgePoints[j][1]); + + var condition = ((yi > 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 diff --git a/TestProjects/Baidu/findminPro.js b/TestProjects/Baidu/findminPro.js new file mode 100644 index 0000000..4400d4e --- /dev/null +++ b/TestProjects/Baidu/findminPro.js @@ -0,0 +1,76 @@ +/**** + * 2019.04.02 + * 百度实习生笔试算法题第一题 + * N, P, Q, Array + * 输入包括四个参数 + * + * num 表示项目成员人数 N 的整数 + * projCmpt 成功完成项目的成员得分减少的值 + * restDec 错误分数大于零的团队成员的错误分数减少的值 + * errScore 初始错误分数列表 + * + * + */ + +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 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; 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..73dd04e --- /dev/null +++ b/TestProjects/ByteDance/20190427MaJiang.js @@ -0,0 +1,144 @@ +/***** + * + * 字节跳动 春招技术类实习生笔试第二题 + * + * 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; + } + // 统计每种数字的数量 + 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.slice(0); + tempArr.push(i); + // console.log(tempArr); + if (this.checkIfWin(tempArr)) { + effecArr.push(i); + } + } + return effecArr; +} + +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/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); diff --git a/TestProjects/HuaWei/decodePassword.js b/TestProjects/HuaWei/decodePassword.js new file mode 100644 index 0000000..53cac30 --- /dev/null +++ b/TestProjects/HuaWei/decodePassword.js @@ -0,0 +1,77 @@ +/****** + * + * 2019.04.24 + * 华为 实习生笔试题算法题第3题 + * + * 初始密码是一段升序的数字 + * 已有的加密算法会 将数字转换成英文拼接成字符串,并改变字符串的大小写以及顺序 + * + * ! 问题描述:现已知加密后的密码还原出原有的密码 + * + * + */ + +// 思路:应该就是转换小写后统计每个字母出现的次数,根据是个数字的英文进行匹配,最后调整成升序就好吧 + + +// 分析每个英文字母的特征 进行统计整理 + +// 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 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}" +``` + 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 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 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 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 new file mode 100644 index 0000000..327d94a --- /dev/null +++ b/TestProjects/scanStringfromTerminal.js @@ -0,0 +1,42 @@ +/****** + * + * 牛客网 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); +} + + +// 本题为考试多行输入输出规范示例,无需提交,不计分。 +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 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