├── README.md └── algorithms ├── 3Sum.js ├── 3Sum_Closest.js ├── 4Sum.js ├── Add_Two_Numbers.js ├── Combination_Sum.js ├── Combination_Sum_II.js ├── Container_With_Most_Water.js ├── Count_and_Say.js ├── Divide_Two_Integers.js ├── Generate_Parentheses.js ├── Implement_strStr().js ├── Integer_to_Roman.js ├── JumpGame.js ├── Letter_Combinations_of_a_Phone_Number.js ├── Longest_Common_Prefix.js ├── Longest_Palindromic.js ├── Longest_Substring.js ├── MaximumSubarray.js ├── MergeIntervals.js ├── Merge_Two_Sorted_Lists.js ├── Multiply_Strings.js ├── N-Queens.js ├── Next_Permutation.js ├── Palindrome_Number.js ├── Permutations.js ├── PermutationsII.js ├── Pow(x, n).js ├── Remove_Duplicates_from_Sorted_Array.js ├── Remove_Element.js ├── Remove_Nth_Node_From_End_of_List.js ├── Reverse_Integer.js ├── Roman_to_Integer.js ├── RotateImage.js ├── Search_Insert_Position.js ├── Search_for_a_Range.js ├── SpiralMatrix.js ├── Sqrt(x).js ├── String_to_Integer(atoi).js ├── Sum_of_Two_Integers.js ├── SuperPow.js ├── Swap_Nodes_in_Pairs.js ├── TwoSum.js ├── Valid_Parentheses.js ├── Valid_Sudoku.js ├── ZigZag_Conversion.js └── groupAnagrams.js /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | (Notes: "♥" means you need buy a book from Leetcode) 4 | 5 | | # | Title | Solution | Difficulty | 6 | |---| ----- | -------- | ---------- | 7 | |1|[Two Sum](https://leetcode.com/problems/two-sum/)| [JavaScript](./algorithms/TwoSum.js)|Easy| 8 | |2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [JavaScript](./algorithms/Add_Two_Numbers.js)|Medium| 9 | |3|[Longest Substring](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [JavaScript](./algorithms/Longest_Substring.js)|Medium| 10 | |5|[Longest Palindromic](https://leetcode.com/problems/longest-palindromic-substring/)| [JavaScript](./algorithms/Longest_Palindromic.js)|Medium| 11 | |6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)| [JavaScript](./algorithms/ZigZag_Conversion.js)|Easy| 12 | |7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [JavaScript](./algorithms/Reverse_Integer.js)|Easy| 13 | |8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)| [JavaScript](./algorithms/String_to_Integer(atoi).js)|Easy| 14 | |9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)| [JavaScript](./algorithms/Palindrome_Number.js)|Easy| 15 | |11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [JavaScript](./algorithms/Container_With_Most_Water.js)|Medium| 16 | |12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [JavaScript](./algorithms/Integer_to_Roman.js)|Medium| 17 | |13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [JavaScript](./algorithms/Roman_to_Integer.js)|Easy| 18 | |14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [JavaScript](./algorithms/Longest_Common_Prefix.js)|Easy| 19 | |15|[3Sum](https://leetcode.com/problems/3sum/)| [JavaScript](./algorithms/3Sum.js)|Medium| 20 | |16|[3Sum_Closest](https://leetcode.com/problems/3sum-closest/)| [JavaScript](./algorithms/3Sum_Closest.js)|Medium| 21 | |17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [JavaScript](./algorithms/Letter_Combinations_of_a_Phone_Number.js)|Medium| 22 | |18|[4Sum](https://leetcode.com/problems/4sum/)| [JavaScript](./algorithms/4Sum.js)|Medium| 23 | |19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [JavaScript](./algorithms/Remove_Nth_Node_From_End_of_List.js)|Easy| 24 | |20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [JavaScript](./algorithms/Valid_Parentheses.js)|Easy| 25 | |21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [JavaScript](./algorithms/Merge_Two_Sorted_Lists.js)|Easy| 26 | |22|[Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [JavaScript](./algorithms/Generate_Parentheses.js)|Medium| 27 | |24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [JavaScript](./algorithms/Swap_Nodes_in_Pairs.js)|Easy| 28 | |26|[Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [JavaScript](./algorithms/Remove_Duplicates_from_Sorted_Array.js)|Easy| 29 | |27|[Remove Element](https://leetcode.com/problems/remove-element/)| [JavaScript](./algorithms/Remove_Element.js)|Easy| 30 | |28|[Implement strStr()](https://leetcode.com/problems/implement-strstr/)| [JavaScript](./algorithms/Implement_strStr().js)|Easy| 31 | |29|[Divide Two Integers](https://leetcode.com/problems/divide-two-integers/)| [JavaScript](./algorithms/Divide_Two_Integers.js)|Medium| 32 | |31|[Next Permutation](https://leetcode.com/problems/next-permutation/)| [JavaScript](./algorithms/Next_Permutation.js)|Medium| 33 | |34|[Search for a Range](https://leetcode.com/problems/search-for-a-range/)| [JavaScript](./algorithms/Search_for_a_Range.js)|Medium| 34 | |35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)| [JavaScript](./algorithms/Search_Insert_Position.js)|Medium| 35 | |36|[Valid Sudoku](https://leetcode.com/problems/valid-sudoku/)| [JavaScript](./algorithms/Valid_Sudoku.js)|Easy| 36 | |38|[Count and Say](https://leetcode.com/problems/count-and-say/)| [JavaScript](./algorithms/Count_and_Say.js)|Easy| 37 | |39|[Combination Sum](https://leetcode.com/problems/combination-sum/)| [JavaScript](./algorithms/Combination_Sum.js)|Medium| 38 | |40|[Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [JavaScript](./algorithms/Combination_Sum_II.js)|Medium| 39 | |43|[Multiply Strings](https://leetcode.com/problems/multiply-strings/)| [JavaScript](./algorithms/Multiply_Strings.js)|Medium| 40 | |46|[Permutations](https://leetcode.com/problems/permutations/)| [JavaScript](./algorithms/Permutations.js)|Medium| 41 | |47|[Permutations II](https://leetcode.com/problems/permutations-ii/)| [JavaScript](./algorithms/PermutationsII.js)|Medium| 42 | |48|[Rotate Image](https://leetcode.com/problems/rotate-image/)| [JavaScript](./algorithms/RotateImage.js)|Medium| 43 | |49|[Group Anagrams](https://leetcode.com/problems/group-anagrams/)| [JavaScript](./algorithms/groupAnagrams.js)|Medium| 44 | |50|[Pow(x, n)](https://leetcode.com/problems/powx-n/)| [JavaScript](./algorithms/Pow(x%2C%20n).js)|Medium| 45 | |51|[N-Queens](https://leetcode.com/problems/n-queens/)| [JavaScript](./algorithms/N-Queens.js)|Hard| 46 | |53|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)| [JavaScript](./algorithms/MaximumSubarray.js)|Easy| 47 | |54|[Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)| [JavaScript](./algorithms/SpiralMatrix.js)|Medium| 48 | |55|[Jump Game](https://leetcode.com/problems/jump-game/)| [JavaScript](./algorithms/JumpGame.js)|Medium| 49 | |56|[Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [JavaScript](./algorithms/MergeIntervals.js)|Medium| 50 | |69|[Sqrt(x)](https://leetcode.com/problems/sqrtx/)| [JavaScript](./algorithms/Sqrt(x).js)|Easy| 51 | |371|[Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/)| [JavaScript](./algorithms/Sum_of_Two_Integers.js)|Easy| 52 | |372|[Super Pow](https://leetcode.com/problems/super-pow/)| [JavaScript](./algorithms/SuperPow.js)|Medium| -------------------------------------------------------------------------------- /algorithms/3Sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | var threeSum = function(nums) { 6 | nums.sort(function(a,b){ 7 | return a-b; 8 | }); 9 | var target,result=[],len=nums.length; 10 | for(var i=0;i9){ 23 | cur.val-=10; 24 | cur.next=new ListNode(1); 25 | } 26 | result=cur; 27 | l1=l1&&l1.next; 28 | l2=l2&&l2.next; 29 | } 30 | result=list.next; 31 | return result; 32 | }; -------------------------------------------------------------------------------- /algorithms/Combination_Sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} candidates 3 | * @param {number} target 4 | * @return {number[][]} 5 | */ 6 | var combinationSum = function(candidates, target) { 7 | var result = [], 8 | temp = []; 9 | var find = function(target, temp, index) { 10 | for (var i = index; i >= 0; i--) { 11 | if (candidates[i] > target) { 12 | continue; 13 | } else if (candidates[i] === target) { 14 | result.push(temp.concat([candidates[i]])); 15 | } else { 16 | find(target - candidates[i], temp.concat([candidates[i]]), i); 17 | } 18 | } 19 | }; 20 | find(target, temp, candidates.length - 1); 21 | return result; 22 | }; 23 | -------------------------------------------------------------------------------- /algorithms/Combination_Sum_II.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} candidates 3 | * @param {number} target 4 | * @return {number[][]} 5 | */ 6 | var combinationSum2 = function(candidates, target) { 7 | candidates.sort(function(a,b){ 8 | return a-b; 9 | }); 10 | var result = [], 11 | tempSave = []; 12 | var find = function(target, temp, index,temp2) { 13 | for (var i = index; i target) { 15 | break; 16 | } else if (candidates[i] === target) { 17 | if(tempSave[temp2+candidates[i]]){ 18 | break; 19 | } 20 | result.push(temp.concat([candidates[i]])); 21 | tempSave[temp2+candidates[i]]=true; 22 | } else { 23 | find(target - candidates[i], temp.concat([candidates[i]]), i+1,temp2+candidates[i]); 24 | } 25 | } 26 | }; 27 | find(target, [], 0,""); 28 | return result; 29 | }; -------------------------------------------------------------------------------- /algorithms/Container_With_Most_Water.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} height 3 | * @return {number} 4 | */ 5 | var maxArea = function(height) { 6 | var max = 0, 7 | temp = 0, 8 | h = 0, 9 | l = 0, 10 | start = 0, 11 | end = height.length - 1; 12 | for (var i = 0; i < height.length - 1; i++) { 13 | l = end - start; 14 | if (height[start] > height[end]) { 15 | h = height[end]; 16 | end--; 17 | } else { 18 | h = height[start]; 19 | start++; 20 | } 21 | if (max < h * l) { 22 | max = h * l; 23 | } 24 | } 25 | return max; 26 | }; 27 | -------------------------------------------------------------------------------- /algorithms/Count_and_Say.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {string} 4 | */ 5 | /** 6 | * @param {number} n 7 | * @return {string} 8 | */ 9 | var updateSeq = function(str) { 10 | var s = "", 11 | temp = 1; 12 | for (var i = 0; i < str.length; i++) { 13 | if (str[i + 1] === str[i]) { 14 | temp += 1; 15 | continue; 16 | } 17 | s = s += (temp + str[i]); 18 | temp = 1; 19 | } 20 | return s; 21 | }; 22 | var countAndSay = function(n) { 23 | var s = "1"; 24 | for (var i = 1; i < n; i++) { 25 | s = updateSeq(s); 26 | } 27 | return s; 28 | }; 29 | -------------------------------------------------------------------------------- /algorithms/Divide_Two_Integers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} dividend 3 | * @param {number} divisor 4 | * @return {number} 5 | */ 6 | var divide = function(dividend, divisor) { 7 | var MAX_INT = Math.pow(2, 31) - 1, 8 | MIN_INT = -Math.pow(2, 31), 9 | result = 0, 10 | newDividend = Math.abs(dividend), 11 | newDivisor = Math.abs(divisor), 12 | flag; 13 | if (newDividend < newDivisor) { 14 | return 0; 15 | } 16 | if (dividend >= 0 && divisor > 0 || dividend <= 0 && divisor < 0) { 17 | flag = 1; 18 | } else { 19 | flag = -1; 20 | } 21 | while (newDividend >= newDivisor) { 22 | var temp = newDivisor, 23 | i = 0; 24 | while (newDividend >= temp << 1) { 25 | if ((temp << 1) <= 0) { 26 | break; 27 | } 28 | temp = temp << 1; 29 | i++; 30 | if (flag > 0 && i > 29) { 31 | return MAX_INT; 32 | } 33 | if (flag < 0 && i > 30) { 34 | return MIN_INT; 35 | } 36 | } 37 | newDividend -= temp; 38 | result += Math.pow(2, i); 39 | } 40 | if (flag > 0) { 41 | return result; 42 | } else { 43 | return -result; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /algorithms/Generate_Parentheses.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {string[]} 4 | */ 5 | var add = function(left, right, stack, s) { 6 | if (left === 0 && right === 0) { 7 | stack.push(s); 8 | return; 9 | } 10 | if (left === right) { 11 | add(left - 1, right, stack, s + "("); 12 | } else if (left === 0) { 13 | add(left, right - 1, stack, s + ")"); 14 | } else { 15 | add(left - 1, right, stack, s + "("); 16 | add(left, right - 1, stack, s + ")"); 17 | } 18 | }; 19 | 20 | var generateParenthesis = function(n) { 21 | var stack = []; 22 | add(n, n, stack, ""); 23 | return stack; 24 | }; 25 | -------------------------------------------------------------------------------- /algorithms/Implement_strStr().js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} haystack 3 | * @param {string} needle 4 | * @return {number} 5 | */ 6 | var strStr = function(haystack, needle) { 7 | for(var i=0;;i++){ 8 | for(var j=0;;j++){ 9 | if(j===needle.length){ 10 | return i; 11 | } 12 | if(i+j===haystack.length){ 13 | return -1; 14 | } 15 | if(haystack.charAt(i+j)!==needle[j]){ 16 | break; 17 | } 18 | } 19 | } 20 | }; -------------------------------------------------------------------------------- /algorithms/Integer_to_Roman.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num 3 | * @return {string} 4 | */ 5 | var intToRoman = function(num) { 6 | var huns = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], 7 | tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], 8 | ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"], 9 | thNum=Math.floor(num/1000), 10 | hNum=Math.floor(num%1000/100), 11 | tNum=Math.floor(num%100/10), 12 | oNum=num%10, 13 | result=""; 14 | while(thNum>0){ 15 | result+="M"; 16 | thNum--; 17 | } 18 | result=result+huns[hNum]+tens[tNum]+ones[oNum]; 19 | return result; 20 | }; -------------------------------------------------------------------------------- /algorithms/JumpGame.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {boolean} 4 | */ 5 | var canJump = function(nums) { 6 | if (nums.length === 1) { 7 | return true; 8 | } 9 | let maxDis = 0; 10 | for (let i = 0; i < nums.length - 1 && i <= maxDis; i++) { 11 | if (nums[i] + i > maxDis) { 12 | maxDis = nums[i] + i; 13 | } 14 | } 15 | if (maxDis >= nums.length - 1) { 16 | return true; 17 | } 18 | return false 19 | }; -------------------------------------------------------------------------------- /algorithms/Letter_Combinations_of_a_Phone_Number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} digits 3 | * @return {string[]} 4 | */ 5 | var Arr=["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]; 6 | var add=function(result,curr,length,index,digits){ 7 | if(index===length){ 8 | if(curr!==""){ 9 | result.push(curr); 10 | } 11 | return; 12 | } 13 | var len=Arr[digits[index]].length; 14 | for(var i=0;i0){ 23 | prefix+=strs[0].substr(0,j); 24 | } 25 | return prefix; 26 | } 27 | } 28 | } 29 | return strs[0].substr(0,minlen); 30 | }; -------------------------------------------------------------------------------- /algorithms/Longest_Palindromic.js: -------------------------------------------------------------------------------- 1 | var Palindromic = function(s,begin,end){ 2 | while (begin < end && s[begin] === s[end]) { 3 | ++begin; --end; 4 | } 5 | return begin - end === 1 || 6 | begin === end; 7 | } 8 | /** 9 | * @param {string} s 10 | * @return {string} 11 | */ 12 | var longestPalindrome = function(s) { 13 | var result, 14 | begin=0, 15 | max=-1, 16 | newS="%"+s.split("").join("%")+"%"; 17 | for(var i=0;i max) { 12 | max = nums[i]; 13 | } 14 | } else { 15 | if (temp + nums[i] > max) { 16 | max = temp + nums[i]; 17 | } 18 | temp = temp + nums[i]; 19 | } 20 | } 21 | return max; 22 | }; -------------------------------------------------------------------------------- /algorithms/MergeIntervals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * function Interval(start, end) { 4 | * this.start = start; 5 | * this.end = end; 6 | * } 7 | */ 8 | /** 9 | * @param {Interval[]} intervals 10 | * @return {Interval[]} 11 | */ 12 | var merge = function(intervals) { 13 | if (intervals.length === 0) { 14 | return intervals; 15 | } 16 | let result = [intervals[0]]; 17 | for (let i = 1; i < intervals.length; i++) { 18 | let obj = []; // [{index: x, pos: 'right' or 'left'},{index: x, pos: 'right' or 'left'}] 19 | for (let j = 0; j < result.length; j++) { 20 | if (j === result.length -1 && intervals[i].start > result[j].end) { 21 | result.push(intervals[i]); 22 | break; 23 | } 24 | if (j === 0 && intervals[i].end < result[j].start) { 25 | result.unshift(intervals[i]); 26 | break; 27 | } 28 | if (intervals[i].start <= result[j].end && intervals[i].start >= result[j].start) { 29 | obj[0] = { index: j, pos: 'mid'}; 30 | } else if (intervals[i].start <= result[j].start && ( j ===0 || intervals[i].start > result[j - 1].end)) { 31 | obj[0] = { index: j, pos: 'left'}; 32 | } 33 | if (intervals[i].end >= result[j].end && (j === result.length -1 || intervals[i].end < result[j + 1].start)) { 34 | obj[1] = { index: j, pos: 'right'}; 35 | } else if (intervals[i].end >= result[j].start && intervals[i].end <= result[j].end) { 36 | obj[1] = { index: j, pos: 'mid'}; 37 | } 38 | if (obj[1] && obj[0]) { 39 | break; 40 | } 41 | } 42 | if(!obj[1] || !obj[0] ) { 43 | continue; 44 | } 45 | let start = obj[0].index, 46 | end = obj[1].index; 47 | if (obj[0].pos === 'mid') { 48 | if (obj[1].pos === 'mid') { 49 | if (obj[0].index === obj[1].index) { 50 | continue; 51 | } else { 52 | const newItv = new Interval(result[start].start, result[end].end); 53 | result.splice(start, end - start + 1, newItv); 54 | } 55 | } else if (obj[1].pos === 'right') { 56 | const newItv = new Interval(result[start].start, intervals[i].end); 57 | result.splice(start, end - start + 1, newItv); 58 | } 59 | } else if (obj[0].pos === 'left') { 60 | if (obj[1].pos === 'mid') { 61 | const newItv = new Interval(intervals[i].start, result[end].end); 62 | result.splice(start, end - start + 1, newItv); 63 | } else if(obj[1].pos === 'right') { 64 | const newItv = new Interval(intervals[i].start, intervals[i].end); 65 | if (obj[0].index > obj[1].index) { 66 | result.splice(start, 0, newItv); 67 | } else { 68 | result.splice(start, end - start + 1, newItv); 69 | } 70 | } 71 | } 72 | } 73 | return result; 74 | }; -------------------------------------------------------------------------------- /algorithms/Merge_Two_Sorted_Lists.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val) { 4 | * this.val = val; 5 | * this.next = null; 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} l1 10 | * @param {ListNode} l2 11 | * @return {ListNode} 12 | */ 13 | var mergeTwoLists = function(l1, l2) { 14 | var mergeList = new ListNode(0); 15 | var head = mergeList; 16 | while (l1 && l2) { 17 | if (l1.val > l2.val) { 18 | mergeList.next = l2; 19 | l2 = l2.next; 20 | } else { 21 | mergeList.next = l1; 22 | l1 = l1.next; 23 | } 24 | mergeList = mergeList.next; 25 | } 26 | if (l1 || l2) { 27 | mergeList.next = l1 ? l1 : l2; 28 | } 29 | return head.next; 30 | }; 31 | -------------------------------------------------------------------------------- /algorithms/Multiply_Strings.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} num1 3 | * @param {string} num2 4 | * @return {string} 5 | */ 6 | var multiply = function(num1, num2) { 7 | var result = [], 8 | temp, l1 = num1.length, 9 | l2 = num2.length, 10 | resultStr = ""; 11 | for (var i = l1 - 1; i >= 0; i--) { 12 | for (var j = l2 - 1; j >= 0; j--) { 13 | temp = num1[i] * num2[j]; 14 | var tenTemp = Math.floor(temp / 10), 15 | oneTemp = Math.floor(temp % 10); 16 | result[l1 + l2 - i - j - 1] = result[l1 + l2 - i - j - 1] + oneTemp || oneTemp; //个位储存 17 | result[l1 + l2 - i - j] = result[l1 + l2 - i - j] + tenTemp || tenTemp; //十位储存 18 | } 19 | } 20 | for (i = 1; i < result.length; i++) { 21 | if (result[i] >= 10) { //进位 22 | result[i + 1] += Math.floor(result[i] / 10); 23 | result[i] = Math.floor(result[i] % 10); 24 | } 25 | } 26 | for (j = result.length - 1; j > 0; j--) { //将数组转为字符串 27 | resultStr += result[j]; 28 | } 29 | var index = 0; 30 | while (resultStr[index] === "0") { 31 | index++; 32 | } 33 | return resultStr.substr(index) === "" ? "0" : resultStr.substr(index); 34 | }; 35 | -------------------------------------------------------------------------------- /algorithms/N-Queens.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {string[][]} 4 | */ 5 | var solveNQueens = function(n) { 6 | let result = [], 7 | i = 1, 8 | temp = [], 9 | // 检测是否符合要求的工具函数 10 | check = function(arr, num) { 11 | for (let k = 0; k < num; k++) { 12 | if (arr[k] === arr[num] || Math.abs(arr[k] - arr[num]) === num - k) { 13 | return false; 14 | } 15 | } 16 | return true; 17 | }, 18 | queens = '.'.repeat(n).split(''); 19 | temp[0] = 0; 20 | // 回溯法求解 21 | while (i > 0) { 22 | temp[i - 1] += 1; 23 | while (temp[i - 1] <= n){ 24 | if(check(temp, i - 1)) { 25 | if (i === n) { 26 | result.push(temp.slice(0, n)); 27 | } 28 | temp[i] = 0; 29 | i += 2; 30 | break; 31 | } else { 32 | temp[i - 1] += 1; 33 | } 34 | } 35 | i--; 36 | } 37 | // 得到的实际上是数字解,比如[2,4,1,3]这种,所以需要转换一下 38 | return result.map((val) => { 39 | return val.map((item) => { 40 | let q = [...queens]; 41 | q.splice(item - 1, 1, 'Q'); 42 | return q.join(''); 43 | }) 44 | }) 45 | }; -------------------------------------------------------------------------------- /algorithms/Next_Permutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {void} Do not return anything, modify nums in-place instead. 4 | */ 5 | var nextPermutation = function(nums) { 6 | if (nums.length <= 1) { 7 | return; 8 | } 9 | var len = nums.length, 10 | i = len - 1; 11 | while (i > 0) { 12 | if (nums[i - 1] < nums[i]) { 13 | break; 14 | } 15 | i--; 16 | } 17 | var j = len - 1, 18 | temp; 19 | if (i > 0) { 20 | while (j > i - 1) { 21 | if (nums[j] > nums[i - 1]) { 22 | temp = nums[i - 1]; 23 | nums[i - 1] = nums[j]; 24 | nums[j] = temp; 25 | break; 26 | } 27 | j--; 28 | } 29 | } 30 | j = 0; 31 | while (j + i < Math.ceil((i + len - 1) / 2)) { 32 | temp = nums[len - 1 - j]; 33 | nums[len - 1 - j] = nums[j + i]; 34 | nums[j + i] = temp; 35 | j++; 36 | } 37 | return; 38 | }; 39 | -------------------------------------------------------------------------------- /algorithms/Palindrome_Number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {boolean} 4 | */ 5 | var isPalindrome = function(x) { 6 | var xString=""+x; 7 | if(StringReverse(xString)===xString){ 8 | return true; 9 | } 10 | else{ 11 | return false; 12 | } 13 | }; 14 | 15 | function StringReverse(s){ 16 | var result=""; 17 | for (var i=s.length-1;i>=0;i--){ 18 | result+=s[i]; 19 | } 20 | return result; 21 | } -------------------------------------------------------------------------------- /algorithms/Permutations.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | var permute = function(nums) { 6 | var result = [], 7 | len = nums.length; 8 | var addNum = function(used, arr) { 9 | var temp = arr.slice(0); 10 | for (var i = 0; i < len; i++) { 11 | if (used[i] === true) { 12 | continue; 13 | } 14 | temp.push(nums[i]); 15 | if (temp.length === len) { 16 | result.push(temp); 17 | return 18 | } 19 | used[i] = true; 20 | addNum(used, temp); 21 | used[i] = false; 22 | temp.pop(); 23 | } 24 | } 25 | addNum([], []); 26 | return result; 27 | }; -------------------------------------------------------------------------------- /algorithms/PermutationsII.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | var permuteUnique = function(nums) { 6 | var result = [], 7 | len = nums.length; 8 | nums.sort(function(a, b) { 9 | return a - b; 10 | }) 11 | var addNum = function(used, arr) { 12 | var temp = arr.slice(0); 13 | for (var i = 0; i < len; i++) { 14 | if (used[i] === true || (i !== 0 && nums[i] === nums[i-1] && used[i-1] !== true)) { 15 | continue; 16 | } 17 | temp.push(nums[i]); 18 | if (temp.length === len) { 19 | result.push(temp); 20 | return 21 | } 22 | used[i] = true; 23 | addNum(used, temp); 24 | used[i] = false; 25 | temp.pop(); 26 | } 27 | } 28 | addNum([], []); 29 | return result; 30 | }; -------------------------------------------------------------------------------- /algorithms/Pow(x, n).js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @param {number} n 4 | * @return {number} 5 | */ 6 | var myPow = function(x, n) { 7 | var flag = false, 8 | p = x, 9 | res = 1 10 | if (n < 0) { 11 | flag = true; 12 | } 13 | for (var i = Math.abs(n); i > 0 ; i = Math.floor(i/2)) { 14 | if (i % 2 !== 0) { 15 | res = res * p; 16 | } 17 | p = p * p; 18 | } 19 | result = flag ? 1 / res : res; 20 | return result 21 | }; -------------------------------------------------------------------------------- /algorithms/Remove_Duplicates_from_Sorted_Array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var removeDuplicates = function(nums) { 6 | var i=0; 7 | while(nums[i]!==undefined){ 8 | if(nums[i]===nums[i-1]){ 9 | nums.splice(i,1); 10 | } 11 | else{ 12 | i++; 13 | } 14 | } 15 | return nums.length; 16 | }; -------------------------------------------------------------------------------- /algorithms/Remove_Element.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} val 4 | * @return {number} 5 | */ 6 | var removeElement = function(nums, val) { 7 | var i=0; 8 | while(nums[i]!==undefined){ 9 | if(nums[i]===val){ 10 | nums.splice(i,1); 11 | } 12 | else{ 13 | i++; 14 | } 15 | } 16 | return nums.length; 17 | }; -------------------------------------------------------------------------------- /algorithms/Remove_Nth_Node_From_End_of_List.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val) { 4 | * this.val = val; 5 | * this.next = null; 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @param {number} n 11 | * @return {ListNode} 12 | */ 13 | var removeNthFromEnd = function(head, n) { 14 | var headBefore=new ListNode(0); 15 | headBefore.next=head; 16 | var current=headBefore, 17 | ended=head; 18 | while(n>1){ 19 | ended=ended.next; 20 | n--; 21 | } 22 | while(ended.next){ 23 | current=current.next; 24 | ended=ended.next; 25 | } 26 | current.next=current.next.next; 27 | return headBefore.next; 28 | }; -------------------------------------------------------------------------------- /algorithms/Reverse_Integer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {number} 4 | */ 5 | var reverse = function(x) { 6 | var xString= ""+x, 7 | result=""; 8 | if (xString[0]==="-"){ 9 | xString=xString.substr(1); 10 | result="-"+StringReverse(xString)-0; 11 | } 12 | else{ 13 | result=StringReverse(xString)-0; 14 | } 15 | if(result<=Math.pow(2,31)-1&&result>=-Math.pow(2,31)){ 16 | return result; 17 | } 18 | else{ 19 | return 0; 20 | } 21 | }; 22 | 23 | function StringReverse(s){ 24 | var result=""; 25 | for (var i=s.length-1;i>=0;i--){ 26 | result+=s[i]; 27 | } 28 | return result; 29 | } -------------------------------------------------------------------------------- /algorithms/Roman_to_Integer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var romanToInt = function(s) { 6 | var huns = ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], 7 | tens = ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], 8 | ones = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"], 9 | result=0,hNum=0,tNum=0,oNum=0,count=0,Num=[0,0,0], 10 | sSub=s, 11 | Arr=[ones,tens,huns]; 12 | while(sSub[0]==="M"){ 13 | sSub=sSub.substring(1); 14 | } 15 | var thNum=s.length-sSub.length; 16 | for(var j=0;j<3;j++){ 17 | for(var i=0;i<9;i++){ 18 | if(sSub.indexOf(Arr[j][i])!==-1){ 19 | Num[j]=i+1; 20 | if(Num[j]==4){ 21 | break; 22 | } 23 | } 24 | } 25 | sSub=sSub.replace(Arr[j][Num[j]-1],""); 26 | } 27 | result=thNum*1000+Num[2]*100+Num[1]*10+Num[0]; 28 | return result; 29 | }; -------------------------------------------------------------------------------- /algorithms/RotateImage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {void} Do not return anything, modify matrix in-place instead. 4 | */ 5 | var rotate = function(matrix) { 6 | var l = matrix.length, 7 | temp = []; 8 | for (var i = 0; i < Math.floor(l / 2); i++){ 9 | for(var j = i; j < l - i - 1; j++) { 10 | temp = [matrix[i][j], matrix[j][l - i - 1], matrix[l - i - 1][l - j - 1], matrix[l - j - 1][i]]; 11 | matrix[i][j] = temp[3]; 12 | matrix[j][l - i - 1] = temp[0]; 13 | matrix[l - i - 1][l - j - 1] = temp[1]; 14 | matrix[l - j -1][i] = temp[2]; 15 | } 16 | } 17 | }; -------------------------------------------------------------------------------- /algorithms/Search_Insert_Position.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | var searchInsert = function(nums, target) { 7 | var i=0; 8 | while(nums[i] right) { 8 | return; 9 | } 10 | var pos = Math.floor((right + left) / 2); 11 | if (nums[pos] === target) { 12 | if (result[0] === -1 && result[1] === -1) { 13 | result[0] = result[1] = pos; 14 | } else { 15 | result[0] = pos < result[0] ? pos : result[0]; 16 | result[1] = pos > result[1] ? pos : result[1]; 17 | } 18 | search(left, pos - 1, result, nums, target); 19 | search(pos + 1, right, result, nums, target); 20 | } else if (nums[pos] > target) { 21 | search(left, pos - 1, result, nums, target); 22 | } else { 23 | search(pos + 1, right, result, nums, target); 24 | } 25 | }; 26 | var searchRange = function(nums, target) { 27 | var result = [-1, -1]; 28 | search(0, nums.length - 1, result, nums, target); 29 | return result; 30 | }; 31 | -------------------------------------------------------------------------------- /algorithms/SpiralMatrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {number[]} 4 | */ 5 | var spiralOrder = function(matrix) { 6 | if (matrix.length === 0) { 7 | return matrix; 8 | } 9 | let m = matrix.length, 10 | n = matrix[0].length, 11 | result =[], 12 | res = []; 13 | if (m === 1) { 14 | return matrix[0]; 15 | } else if (n === 1) { 16 | return matrix.map(val => { 17 | return val[0]; 18 | }) 19 | } 20 | let min = Math.min(m, n); 21 | let count = Math.ceil(min / 2) 22 | for (let i = 0; i < count; i++) { 23 | let top = matrix[i].slice(i, n - i), 24 | bottom = [], 25 | right = [], 26 | left = []; 27 | if(i !== m - i - 1) { 28 | bottom = matrix[m - i - 1].slice(i, n - i).reverse(); 29 | } 30 | for (let j = i + 1; j < m - i - 1; j++) { 31 | right.push(matrix[j][n - i - 1]); 32 | if (i !== n - i - 1) { 33 | left.push(matrix[j][i]); 34 | } 35 | } 36 | result.push(...[...top, ...right, ...bottom, ...left.reverse()]); 37 | } 38 | return result; 39 | }; -------------------------------------------------------------------------------- /algorithms/Sqrt(x).js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {number} 4 | */ 5 | var mySqrt = function(x) { 6 | if (x === 0) { 7 | return 0; 8 | } 9 | var init = 1; 10 | while (Math.abs(init * init - x) > 0.1) { 11 | init = (x + init * init) / (2 * init); 12 | } 13 | return Math.floor(init); 14 | }; 15 | -------------------------------------------------------------------------------- /algorithms/String_to_Integer(atoi).js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} str 3 | * @return {number} 4 | */ 5 | var myAtoi = function(str) { 6 | var result = parseInt(str); 7 | if(str===""|| isNaN(result)){ 8 | return 0; 9 | } 10 | else if(result> Math.pow(2,31)-1) 11 | { 12 | return Math.pow(2,31)-1; 13 | } 14 | else if(result< -Math.pow(2,31)) 15 | { 16 | return -Math.pow(2,31); 17 | } 18 | else{ 19 | return result; 20 | } 21 | }; -------------------------------------------------------------------------------- /algorithms/Sum_of_Two_Integers.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} a 3 | * @param {number} b 4 | * @return {number} 5 | */ 6 | var getSum = function(a, b) { 7 | var c, d, e = 0; 8 | while ((a & b) !== 0) { 9 | d = a ^ b; 10 | e = (a & b) << 1; 11 | a = d; 12 | b = e; 13 | console.log(a,b); 14 | } 15 | c = a | b; 16 | return c; 17 | } -------------------------------------------------------------------------------- /algorithms/SuperPow.js: -------------------------------------------------------------------------------- 1 | //取模运算的性质:(1)(a+b)%c=(a%c+b%c)%c,(2)(ab)%c=(a%c)(b%c)%c;(3) (a^b)%c=a%c^(b%c) 2 | /** 3 | * @param {number} a 4 | * @param {number[]} b 5 | * @return {number} 6 | */ 7 | var superPow = function(a, b) { 8 | var l = b.length, 9 | result = 1; 10 | for (var i = 0; i < l; i++) { 11 | result = lowPow(result, 10) * lowPow(a, b[i]) % 1337; 12 | } 13 | return result; 14 | }; 15 | 16 | var lowPow = function(val, n) { 17 | var temp; 18 | if (n === 0) { 19 | temp = 1; 20 | } else if (n === 1) { 21 | temp = val % 1337; 22 | } else { 23 | temp = lowPow(val, Math.floor(n / 2)) * lowPow(val, n - Math.floor(n / 2)) % 1337; 24 | } 25 | return temp; 26 | }; 27 | -------------------------------------------------------------------------------- /algorithms/Swap_Nodes_in_Pairs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val) { 4 | * this.val = val; 5 | * this.next = null; 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @return {ListNode} 11 | */ 12 | var swapPairs = function(head) { 13 | if (!head || !head.next) { 14 | return head; 15 | } 16 | var curr = new ListNode(0), 17 | result = head.next; 18 | while (head && head.next) { 19 | var temp = head.next; 20 | curr.next = temp.next; 21 | temp.next = head; 22 | head.next = curr.next; 23 | curr.next = temp; 24 | curr = head; 25 | head = head.next; 26 | } 27 | return result; 28 | }; 29 | -------------------------------------------------------------------------------- /algorithms/TwoSum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number[]} 5 | */ 6 | var twoSum = function(nums, target) { 7 | var temp = []; 8 | for (var i = 0; i < nums.length; i++) { 9 | if (temp[target - nums[i]] !== undefined) { 10 | return [temp[target - nums[i]], i]; 11 | } 12 | if (temp[nums[i]] === undefined) { 13 | temp[nums[i]] = i; 14 | } 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /algorithms/Valid_Parentheses.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {boolean} 4 | */ 5 | var isValid = function(s) { 6 | if (s.length % 2 === 1 || /[\}\]\)]/.test(s[0])) { 7 | return false; 8 | } 9 | var stack = []; 10 | for (var i = 0; i < s.length; i++) { 11 | if (/[\{\[\(]/.test(s[i])) { 12 | stack.push(s[i]); 13 | } else { 14 | var len = stack.length; 15 | if (Math.abs(stack[len - 1].charCodeAt(0) - s[i].charCodeAt(0)) <= 2) { 16 | stack.pop(); 17 | } else { 18 | return false; 19 | } 20 | } 21 | } 22 | if (stack.length === 0) { 23 | return true; 24 | } else { 25 | return false; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /algorithms/Valid_Sudoku.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {character[][]} board 3 | * @return {boolean} 4 | */ 5 | var isValidSudoku = function(board) { 6 | var a = new Array(9), 7 | b = new Array(9), 8 | c = new Array(9); 9 | for (var k = 0; k < 9; k++) { 10 | a[k] = new Array(9); 11 | b[k] = new Array(9); 12 | c[k] = new Array(9); 13 | } 14 | 15 | for (var i = 0; i < 9; i++) { 16 | for (var j = 0; j < 9; j++) { 17 | var temp = board[i][j]; 18 | if (temp === ".") { 19 | continue; 20 | } 21 | if (a[i][temp - 1] || b[temp - 1][j] || c[Math.floor(i / 3) * 3 + Math.floor(j / 3)][temp - 1]) { 22 | return false; 23 | } 24 | a[i][temp - 1] = b[temp - 1][j] = c[Math.floor(i / 3) * 3 + Math.floor(j / 3)][temp - 1] = true; 25 | } 26 | } 27 | return true; 28 | }; 29 | -------------------------------------------------------------------------------- /algorithms/ZigZag_Conversion.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {number} numRows 4 | * @return {string} 5 | */ 6 | var convert = function(s, numRows) { 7 | if (s.length <= numRows) { 8 | return s; 9 | } 10 | if(numRows<=1){ 11 | return s; 12 | } 13 | var count = 0, 14 | temp = [], 15 | result = ""; 16 | while ((count % (numRows-1) === 0 && s.length > numRows) || (count % (numRows-1) !== 0 && s.length > 1)) { 17 | if (count % (numRows-1) === 0) { 18 | temp[count] = s.substr(0, numRows); 19 | s = s.substr(numRows); 20 | ++count; 21 | } else{ 22 | temp[count] = s.substr(0, 1); 23 | s = s.substr(1); 24 | ++count; 25 | } 26 | } 27 | temp[count] = s; 28 | var tlength = temp.length; 29 | for (var i = 0; i < numRows; i++) { 30 | var flag = 0; 31 | for (var j = 0; j < tlength; j++) { 32 | if (flag % (numRows-1) === 0) { 33 | if(temp[j][i]){ 34 | result += temp[j][i]; 35 | flag++; 36 | } 37 | } else{ 38 | if (i == ((numRows-1)-flag % (numRows-1))) { 39 | result += temp[j]; 40 | } 41 | flag++; 42 | } 43 | } 44 | } 45 | return result; 46 | 47 | }; -------------------------------------------------------------------------------- /algorithms/groupAnagrams.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} strs 3 | * @return {string[][]} 4 | */ 5 | var groupAnagrams = function(strs) { 6 | var result = [], 7 | obj = {}, 8 | pipe = function(str) { 9 | return str.split('').sort().join(''); 10 | } 11 | for (var i = 0; i < strs.length; i++ ) { 12 | if (obj[pipe(strs[i])] === undefined) { 13 | obj[pipe(strs[i])] = result.length; 14 | result.push([].concat(strs[i])); 15 | } else { 16 | result[obj[pipe(strs[i])]].push(strs[i]); 17 | } 18 | } 19 | return result; 20 | }; --------------------------------------------------------------------------------