From c9eee2f5ca8cd835b0057f2c0a28ca4f0361bb5d Mon Sep 17 00:00:00 2001 From: zongyanqi Date: Tue, 19 Dec 2017 20:32:28 +0800 Subject: [PATCH 1/6] add 006 007 009 016 017 018 022 023 024 027 --- 006-ZigZag-Conversion.js | 47 +++++++++++ 007-Reverse-Integer.js | 49 ++++++++++++ 009-Palindrome-Number.js | 31 ++++++++ 016-3Sum-Closest.js | 42 ++++++++++ 017-Letter-Combinations-of-a-Phone-Number.js | 44 ++++++++++ 018-4Sum.js | 51 ++++++++++++ 022-Generate-Parentheses.js | 37 +++++++++ 023-Merge-k-Sorted-Lists.js | 84 ++++++++++++++++++++ 024-Swap-Nodes-in-Pairs.js | 56 +++++++++++++ 027-Remove-Element.js | 31 ++++++++ 10 files changed, 472 insertions(+) create mode 100644 006-ZigZag-Conversion.js create mode 100644 007-Reverse-Integer.js create mode 100644 009-Palindrome-Number.js create mode 100644 016-3Sum-Closest.js create mode 100644 017-Letter-Combinations-of-a-Phone-Number.js create mode 100644 018-4Sum.js create mode 100644 022-Generate-Parentheses.js create mode 100644 023-Merge-k-Sorted-Lists.js create mode 100644 024-Swap-Nodes-in-Pairs.js create mode 100644 027-Remove-Element.js diff --git a/006-ZigZag-Conversion.js b/006-ZigZag-Conversion.js new file mode 100644 index 0000000..58f30cd --- /dev/null +++ b/006-ZigZag-Conversion.js @@ -0,0 +1,47 @@ +/** + * + * https://leetcode.com/problems/zigzag-conversion/description/ + * Difficulty:Medium + * + * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: + * (you may want to display this pattern in a fixed font for better legibility) + * + * P A H N + * A P L S I I G + * Y I R + * And then read line by line: "PAHNAPLSIIGYIR" + * Write the code that will take a string and make this conversion given a number of rows: + * string convert(string text, int nRows); + * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". + * + */ + +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function (s, numRows) { + + var arr = []; + for (var i = 0; i < numRows; i++) { + arr[i] = []; + } + + var cnt = 0; + var len = s.length; + + while (cnt < len) { + for (var i = 0; i < arr.length && cnt < len; i++) { + arr[i].push(s[cnt++]); + } + for (var i = numRows - 2; i >= 1 && cnt < len; i--) { + arr[i].push(s[cnt++]); + } + } + // console.log(arr); + + return arr.map(arr => arr.join('')).join('') +}; + +console.log(convert('PAYPALISHIRING', 3)); \ No newline at end of file diff --git a/007-Reverse-Integer.js b/007-Reverse-Integer.js new file mode 100644 index 0000000..a7195e6 --- /dev/null +++ b/007-Reverse-Integer.js @@ -0,0 +1,49 @@ +/** + * https://leetcode.com/problems/reverse-integer/description/ + * Difficulty:Easy + * + * Given a 32-bit signed integer, reverse digits of an integer. + * + * Example 1: + * Input: 123 + * Output: 321 + * Example 2: + * Input: -123 + * Output: -321 + * Example 3: + * Input: 120 + * Output: 21 + * Note: + * Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. + * For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. + */ + +/** + * @param {number} x + * @return {number} + */ +var reverse = function (x) { + + var sign = x >= 0 ? -1 : 1; + x = Math.abs(x); + + var sum = 0; + while (x) { + sum = sum * 10 + x % 10; + x = Math.floor(x / 10); + } + var ret = sign * -1 * sum; + var max = Math.pow(2, 31) - 1; + var min = -Math.pow(2, 31); + if (ret > max) return 0; + if (ret < min) return 0; + return ret; +}; + +console.log(reverse(123) === 321); +console.log(reverse(-123) === -321); +console.log(reverse(120) === 21); +console.log(reverse(1534236469) === 0); +console.log(reverse(-2147483412), reverse(-2147483412) === -2143847412); +console.log(reverse(-2147483648), reverse(-2147483648) === 0); + diff --git a/009-Palindrome-Number.js b/009-Palindrome-Number.js new file mode 100644 index 0000000..fdad5ef --- /dev/null +++ b/009-Palindrome-Number.js @@ -0,0 +1,31 @@ +/** + * https://leetcode.com/problems/palindrome-number/description/ + * Difficulty:Easy + * + * Determine whether an integer is a palindrome. Do this without extra space. + */ + +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function (x) { + if (x < 0) return false; + var t = x; + x = Math.abs(x); + var p = 0; + while (x) { + p = p * 10 + x % 10; + x = Math.floor(x / 10); + } + // console.log(x, p); + return t === p; +}; + +console.log(isPalindrome(-1) === false); +console.log(isPalindrome(0) === true); +console.log(isPalindrome(123) === false); +console.log(isPalindrome(12321) === true); +console.log(isPalindrome(1221) === true); +console.log(isPalindrome(2222) === true); + diff --git a/016-3Sum-Closest.js b/016-3Sum-Closest.js new file mode 100644 index 0000000..1466b99 --- /dev/null +++ b/016-3Sum-Closest.js @@ -0,0 +1,42 @@ +/** + * https://leetcode.com/problems/3sum-closest/description/ + * Difficulty:Medium + * + * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. + * Return the sum of the three integers. You may assume that each input would have exactly one solution. + * For example, given array S = {-1 2 1 -4}, and target = 1. + * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). + * + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumClosest = function (nums, target) { + + var ans = nums[0] + nums[1] + nums[2]; + var len = nums.length; + + nums.sort((a, b) => a < b ? -1 : (a > b) ? 1 : 0); + + for (var i = 0; i < len - 2; i++) { + var j = i + 1; + var k = len - 1; + + while (j < k) { + var sum = nums[i] + nums[j] + nums[k]; + if (sum === target) return sum; + if (sum > target) k--; + if (sum < target) j++; + if (Math.abs(target - sum) < Math.abs(target - ans)) { + ans = sum; + } + } + } + return ans; + +}; + +console.log(threeSumClosest([-1, 2, 1, -4], 1)); \ No newline at end of file diff --git a/017-Letter-Combinations-of-a-Phone-Number.js b/017-Letter-Combinations-of-a-Phone-Number.js new file mode 100644 index 0000000..5a27c61 --- /dev/null +++ b/017-Letter-Combinations-of-a-Phone-Number.js @@ -0,0 +1,44 @@ +/** + * + * https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ + * Difficulty:Medium + * + * Given a digit string, return all possible letter combinations that the number could represent. + * + * A mapping of digit to letters (just like on the telephone buttons) is given below. + * + * Input:Digit string "23" + * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. + * + * Note: + * Although the above answer is in lexicographical order, your answer could be in any order you want. + * + */ + +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function (digits) { + + if (!digits.length) return []; + + var ans = ['']; + var map = ['0', '1', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; + + for (var i = 0; i < digits.length; i++) { + var str = map[digits[i]]; + var tmp = []; + for (var j = 0; j < ans.length; j++) { + var t = ans[j]; + for (var k = 0; k < str.length; k++) { + tmp.push(t + str[k]); + } + } + ans = tmp; + } + + return ans; +}; + +console.log(letterCombinations('23')); \ No newline at end of file diff --git a/018-4Sum.js b/018-4Sum.js new file mode 100644 index 0000000..30143ad --- /dev/null +++ b/018-4Sum.js @@ -0,0 +1,51 @@ +/** + * https://leetcode.com/problems/4sum/description/ + * Difficulty:Medium + * + * Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. + * Note: The solution set must not contain duplicate quadruplets. + * For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. + * A solution set is: + * [ + * [-1, 0, 0, 1], + * [-2, -1, 1, 2], + * [-2, 0, 0, 2] + ] + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function (nums, target) { + var len = nums.length; + if (len < 4) return []; + nums.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + // console.log(nums); + var ans = []; + for (var i = 0; i < len - 3; i++) { + + for (var j = i + 1; j < len - 2; j++) { + var k = j + 1; + var l = len - 1; + + while (k < l) { + var sum = nums[i] + nums[j] + nums[k] + nums[l]; + if (sum === target) { + ans.push([nums[i], nums[j], nums[k], nums[l]]); + while (nums[l--] === nums[l] && nums[k++] === nums[k] && k < l); + } + else if (sum < target) while (nums[k++] === nums[k] && k < l); + else while (nums[l--] === nums[l] && k < l); + } + while (nums[j] === nums[j + 1]) j++; + } + while (nums[i] === nums[i + 1]) i++; + + } + return ans; + +}; + +console.log(fourSum([-5, -4, -2, -2, -2, -1, 0, 0, 1], -9)); diff --git a/022-Generate-Parentheses.js b/022-Generate-Parentheses.js new file mode 100644 index 0000000..d8310d7 --- /dev/null +++ b/022-Generate-Parentheses.js @@ -0,0 +1,37 @@ +/** + * https://leetcode.com/problems/generate-parentheses/description/ + * Difficulty:Medium + * + * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + * For example, given n = 3, a solution set is: + * [ + * "((()))", + * "(()())", + * "(())()", + * "()(())", + * "()()()" + * ] + */ + +/** + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = function (n) { + + var ans = []; + helper(ans, '', 0, 0, n); + return ans; +}; + +function helper(ans, str, left, right, n) { + if (right === n) ans.push(str); + if (left < n) { + helper(ans, str + '(', left + 1, right, n); + } + if (right < left) { + helper(ans, str + ')', left, right + 1, n); + } +} + +console.log(generateParenthesis(3)); \ No newline at end of file diff --git a/023-Merge-k-Sorted-Lists.js b/023-Merge-k-Sorted-Lists.js new file mode 100644 index 0000000..b0e79e6 --- /dev/null +++ b/023-Merge-k-Sorted-Lists.js @@ -0,0 +1,84 @@ +/** + * https://leetcode.com/problems/merge-k-sorted-lists/description/ + * Difficulty:Hard + * + * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. + */ + + +//Definition for singly-linked list. +function ListNode(val) { + this.val = val; + this.next = null; +} + +/** + * @param {ListNode[]} lists + * @return {ListNode} + */ +var mergeKLists = function (lists) { + return lists.reduce((a, b) => merge2lists(a, b), null) +}; + +function merge2lists(a, b) { + if (!a && !b) return null; + if (!a) return b; + if (!b) return a; + var h; + if (a.val < b.val) { + h = a; + a = a.next; + } else { + h = b; + b = b.next; + } + var t = h; + + while (a && b) { + if (a.val < b.val) { + t.next = a; + t = t.next; + a = a.next; + } else { + t.next = b; + t = t.next; + b = b.next; + } + } + if (a) t.next = a; + if (b) t.next = b; + return h; + +} + +var a = { + val: 1, + next: { + val: 4, + next: { + val: 7, + next: null + } + } +} +var b = { + val: 2, + next: { + val: 8, + next: { + val: 9, + next: null + } + } +} + +var c = { + val: 3, + next: { + val: 10, + next: null + } +} + +// console.log(merge2lists(a, b)); +console.log(mergeKLists([a, b, c])) \ No newline at end of file diff --git a/024-Swap-Nodes-in-Pairs.js b/024-Swap-Nodes-in-Pairs.js new file mode 100644 index 0000000..f6a3104 --- /dev/null +++ b/024-Swap-Nodes-in-Pairs.js @@ -0,0 +1,56 @@ +/** + * https://leetcode.com/problems/swap-nodes-in-pairs/description/ + * Difficulty:Medium + * + * Given a linked list, swap every two adjacent nodes and return its head. + * + * For example, + * Given 1->2->3->4, you should return the list as 2->1->4->3. + * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. + * + */ + +// Definition for singly-linked list. +function ListNode(val) { + this.val = val; + this.next = null; +} + +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function (head) { + var t = new ListNode(0); + t.next = head; + + var a = t; + + while (true) { + if (!a) break; + var b = a.next; + if (!b) break; + var c = b.next; + if (!c) break; + + b.next = c.next; + c.next = b; + a.next = c; + a = b; + + } + return t.next; +}; + +console.log(swapPairs({ + val: 1, + next: { + val: 2, + next: { + val: 3, + next: { + val: 4 + } + } + } +})) \ No newline at end of file diff --git a/027-Remove-Element.js b/027-Remove-Element.js new file mode 100644 index 0000000..8e14f7f --- /dev/null +++ b/027-Remove-Element.js @@ -0,0 +1,31 @@ +/** + * https://leetcode.com/problems/remove-element/description/ + * Difficulty:Easy + * + * Given an array and a value, remove all instances of that value in-place and return the new length. + * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. + * The order of elements can be changed. It doesn't matter what you leave beyond the new length. + * Example: + * Given nums = [3,2,2,3], val = 3, + * Your function should return length = 2, with the first two elements of nums being 2. + */ + +/** + * @param {number[]} nums + * @param {number} val + * @return {number} + */ +var removeElement = function (nums, val) { + + var len = nums.length; + for (var i = 0; i < len; i++) { + if (nums[i] === val) { + nums.splice(i, 1); + i--; + len--; + } + } + return len; +}; + +console.log(removeElement([3, 2, 2, 3], 3)); \ No newline at end of file From 2e0f4e0e92df7b3291f9c6f434473c27e0dc15a4 Mon Sep 17 00:00:00 2001 From: zongyanqi Date: Wed, 20 Dec 2017 17:27:29 +0800 Subject: [PATCH 2/6] add 013-Roman-to-Integer.js --- 013-Roman-to-Integer.js | 50 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 013-Roman-to-Integer.js diff --git a/013-Roman-to-Integer.js b/013-Roman-to-Integer.js new file mode 100644 index 0000000..1b8293c --- /dev/null +++ b/013-Roman-to-Integer.js @@ -0,0 +1,50 @@ +/** + * https://leetcode.com/problems/roman-to-integer/description/ + * Difficulty:Easy + * + * Given a roman numeral, convert it to an integer. + * Input is guaranteed to be within the range from 1 to 3999. + */ + +/** + * @see https://baike.baidu.com/item/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97 + * + * 基本字符 + * I V X L C D M + * 1 5 10 50 100 500 1000 + * 相应的阿拉伯数字表示 + * + * 计数方法 + * 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3; + * 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12; + * 小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9; + * 正常使用时、连写的数字重复不得超过三次; + * + * @param {string} s + * @return {number} + */ +var romanToInt = function (s) { + + if (!s) return 0; + + var map = { + 'I': 1, + 'V': 5, + 'X': 10, + 'L': 50, + 'C': 100, + 'D': 500, + 'M': 1000 + }; + + var sum = map[s[s.length - 1]]; + for (var i = s.length - 2; i >= 0; i--) { + if (map[s[i]] < map[s[i + 1]]) sum -= map[s[i]]; + else sum += map[s[i]]; + } + return sum; +}; + +console.log(romanToInt('III'), 3); +console.log(romanToInt('VI'), 6); +console.log(romanToInt('IV'), 4); \ No newline at end of file From 4965c831a38f622c5a29ccf16e1edeeab849405f Mon Sep 17 00:00:00 2001 From: zongyanqi Date: Wed, 20 Dec 2017 17:28:54 +0800 Subject: [PATCH 3/6] update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7cfdb5e..616a43a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ # LeetCode in Javascript -一起来刷 [LeetCode](https://leetcode.com/) :D \ No newline at end of file +一起来刷 [LeetCode](https://leetcode.com/) :D + +如果你有感兴趣的题目或者需要更加详细的解释, 可以创建 [issue](https://github.com/xiaoyu2er/leetcode-js/issues) \ No newline at end of file From b0505f9ae11d4838bcce608f9097ae8e9baaa8ac Mon Sep 17 00:00:00 2001 From: zongyanqi Date: Fri, 29 Dec 2017 09:33:20 +0800 Subject: [PATCH 4/6] add 025 030 031 032 033 034 036 038 067 101 --- 025-Reverse-Nodes-in-k-Group.js | 128 ++++++++++++++++++ ...bstring-with-Concatenation-of-All-Words.js | 49 +++++++ 031-Next-Permutation.js | 87 ++++++++++++ 032-Longest-Valid-Parentheses.js | 50 +++++++ 033-Search-in-Rotated-Sorted-Array.js | 46 +++++++ 034-Search-for-a-Range.js | 43 ++++++ 036-Valid-Sudoku.js | 67 +++++++++ 038-Count-and-Say.js | 58 ++++++++ 067-Add-Binary.js | 44 ++++++ 101-Symmetric-Tree.js | 66 +++++++++ 10 files changed, 638 insertions(+) create mode 100644 025-Reverse-Nodes-in-k-Group.js create mode 100644 030-Substring-with-Concatenation-of-All-Words.js create mode 100644 031-Next-Permutation.js create mode 100644 032-Longest-Valid-Parentheses.js create mode 100644 033-Search-in-Rotated-Sorted-Array.js create mode 100644 034-Search-for-a-Range.js create mode 100644 036-Valid-Sudoku.js create mode 100644 038-Count-and-Say.js create mode 100644 067-Add-Binary.js create mode 100644 101-Symmetric-Tree.js diff --git a/025-Reverse-Nodes-in-k-Group.js b/025-Reverse-Nodes-in-k-Group.js new file mode 100644 index 0000000..17caedb --- /dev/null +++ b/025-Reverse-Nodes-in-k-Group.js @@ -0,0 +1,128 @@ +/** + * https://leetcode.com/problems/reverse-nodes-in-k-group/description/ + * Difficulty:Hard + * + * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. + * k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. + * You may not alter the values in the nodes, only nodes itself may be changed. + * Only constant memory is allowed. + * For example, + * Given this linked list: 1->2->3->4->5 + * For k = 2, you should return: 2->1->4->3->5 + * For k = 3, you should return: 3->2->1->4->5 + * + */ + +// Definition for singly-linked list. +function ListNode(val) { + this.val = val; + this.next = null; +} + +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ +var reverseKGroup = function (head, k) { + // if (k === 1) + // return head; + var t = new ListNode(0); + t.next = head; + var s = t; + + while (true) { + var cnt = 0; + var f = t; + while (cnt++ < k && f) { + f = f.next; + } + // console.log(p(t), p(f)); + + if (!f || cnt !== k + 1) break; + cnt = 0; + var a = t.next; + + while (++cnt < k) { + var b = a.next; + a.next = b.next; + b.next = t.next; + t.next = b; + // console.log(p(t), p(a), p(b)); + } + t = a; + } + + return s.next; +}; + +function p(n) { + var t = n; + var s = ''; + while (t) { + s = s + t.val + '->'; + t = t.next; + } + s += 'null'; + return s; +} +// +console.log(p(reverseKGroup({ + val: 1, + next: { + val: 2, + next: { + val: 3, + next: { + val: 4 + } + } + } +}, 2))) + +console.log(p(reverseKGroup({val: 1}, 2))); + +console.log(p(reverseKGroup({ + val: 1, + next: { + val: 2 + } +}, 2))) + +console.log(p(reverseKGroup({ + val: 1, + next: { + val: 2, + next: { + val: 3, + next: { + val: 4, + next: { + val: 5, + next: { + val: 6, + next: { + val: 7 + } + } + } + } + } + } +}, 3))) +// + +console.log(p(reverseKGroup({ + val: 1, + next: { + val: 2, + next: { + val: 3, + next: { + val: 4, + next: null + } + } + } +}, 2))); + diff --git a/030-Substring-with-Concatenation-of-All-Words.js b/030-Substring-with-Concatenation-of-All-Words.js new file mode 100644 index 0000000..007da2c --- /dev/null +++ b/030-Substring-with-Concatenation-of-All-Words.js @@ -0,0 +1,49 @@ +/** + * + * https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/ + * Difficulty:Hard + * + * You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) + * in s that is a concatenation of each word in words exactly once and without any intervening characters. + * For example, given: + * s: "barfoothefoobarman" + * words: ["foo", "bar"] + * You should return the indices: [0,9]. + * (order does not matter). + * + */ +/** + * @param {string} s + * @param {string[]} words + * @return {number[]} + */ +var findSubstring = function (s, words) { + if (!s.length || !words.length) return []; + var ans = []; + var toFind = {}; + + var m = words.length; + var n = words[0].length; + + for (var i = 0; i < m; i++) { + toFind[words[i]] = (toFind[words[i]] || 0) + 1; + } + + for (i = 0; i <= s.length - m * n; i++) { + var found = {}; + + for (var j = 0; j < m; j++) { + var k = i + n * j; + var w = s.substr(k, n); + if (!toFind[w]) break; + found[w] = (found[w] || 0) + 1; + if (found[w] > toFind[w]) break; + } + if (j === m) ans.push(i); + } + + return ans; + +}; + +console.log(findSubstring('barfoothefoobarman', ['foo', 'bar'])); \ No newline at end of file diff --git a/031-Next-Permutation.js b/031-Next-Permutation.js new file mode 100644 index 0000000..0ed21cf --- /dev/null +++ b/031-Next-Permutation.js @@ -0,0 +1,87 @@ +/** + * https://leetcode.com/problems/next-permutation/description/ + * Difficulty:Medium + * + * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. + * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). + * The replacement must be in-place, do not allocate extra memory. + * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. + * 1,2,3 → 1,3,2 + * 3,2,1 → 1,2,3 + * 1,1,5 → 1,5,1 + */ +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var nextPermutation = function (nums) { + + if (nums.length < 2) return; + var peak = nums.length - 1; + for (var i = peak - 1; nums[i] >= nums[peak]; peak = i--); + + if (peak !== 0) { + var swapIndex = findSwap(nums, peak, nums.length - 1, peak - 1); + if (swapIndex !== -1) { + swap(nums, peak - 1, swapIndex); + } + } + + reverse(nums, peak, nums.length - 1); + +}; + +function findSwap(nums, s, e, target) { + for (var i = e; i >= s; i--) { + if (nums[i] > nums[target]) return i; + } + return -1; +} + +function swap(nums, s, e) { + var t = nums[s]; + nums[s] = nums[e]; + nums[e] = t; +} +function reverse(nums, s, e) { + // var len = e - s; + for (var i = 0; i < Math.ceil((e - s ) / 2); i++) { + + swap(nums, s + i, e - i); + } + // return nums; +} + +// console.log(reverse([1, 2, 3, 4, 5], 0, 4)); +// console.log(reverse([1, 2, 3, 4, 5], 3, 4)); +// console.log(reverse([1, 2, 3, 4, 5], 2, 3)); +// console.log(reverse([1, 2, 3, 4, 5], 1, 1)); +// console.log(reverse([1, 2, 3, 4, 5], 1, 4)); + +// var nums = [1, 2, 5, 4, 3]; +// console.log(nums); +// nextPermutation(nums); +// console.log(nums); +// +console.log('===='); + +var nums = [2, 3, 1]; +console.log(nums); +nextPermutation(nums); +console.log(nums); + +console.log('===='); + +var nums = [1, 1]; +console.log(nums); +nextPermutation(nums); +console.log(nums); + +console.log('===='); + +var nums = [3, 2, 1]; +console.log(nums); +nextPermutation(nums); +console.log(nums); + + diff --git a/032-Longest-Valid-Parentheses.js b/032-Longest-Valid-Parentheses.js new file mode 100644 index 0000000..03d6ae7 --- /dev/null +++ b/032-Longest-Valid-Parentheses.js @@ -0,0 +1,50 @@ +/** + * https://leetcode.com/problems/longest-valid-parentheses/description/ + * Difficulty:Hard + * + * Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. + * For "(()", the longest valid parentheses substring is "()", which has length = 2. + * Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. + */ + +/** + * 使用栈解决 + * @param {string} s + * @return {number} + */ +var longestValidParentheses = function (s) { + var stack = []; + for (var i = 0; i < s.length; i++) { + if (s[i] === '(') stack.push(i); + else { + if (stack.length && s[stack[stack.length - 1]] === '(') stack.length--; + else stack.push(i); + } + } + + if (!stack.length) return s.length; + var longest = 0; + var end = s.length; + var start = 0; + while (stack.length) { + start = stack[stack.length - 1]; + stack.length--; + longest = Math.max(longest, end - start - 1); + end = start; + } + longest = Math.max(longest, end); + return longest; +}; + + +console.log(longestValidParentheses('()'), 2); +console.log(longestValidParentheses('())'), 2); +console.log(longestValidParentheses('(()'), 2); +console.log(longestValidParentheses('))()())((())))'), 6); +console.log(longestValidParentheses('()'), 2); +console.log(longestValidParentheses('('), 0); +console.log(longestValidParentheses(')()()))()()())'), 6); +console.log(longestValidParentheses('()(()'), 2); +console.log(longestValidParentheses('()(()'), 2); +console.log(longestValidParentheses('(()'), 2); + diff --git a/033-Search-in-Rotated-Sorted-Array.js b/033-Search-in-Rotated-Sorted-Array.js new file mode 100644 index 0000000..a39390f --- /dev/null +++ b/033-Search-in-Rotated-Sorted-Array.js @@ -0,0 +1,46 @@ +/** + * https://leetcode.com/problems/search-in-rotated-sorted-array/description/ + * Difficulty:Medium + * + * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. + * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). + * You are given a target value to search. If found in the array return its index, otherwise return -1. + * You may assume no duplicate exists in the array. + */ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { + + + var lo = 0; + var hi = nums.length - 1; + while (lo < hi) { + var mid = Math.floor((lo + hi) / 2); + if (nums[mid] < nums[hi]) hi = mid; + else lo = mid + 1; + } + var i = lo; + + lo = target < nums[0] ? i : 0; + hi = target <= nums[nums.length - 1] ? nums.length - 1 : i; + + // console.log(nums, lo, hi); + while (lo <= hi) { + mid = Math.floor((lo + hi) / 2); + // console.log(lo, mid, hi) + if (nums[mid] < target) lo = mid + 1; + else if (nums[mid] === target) return mid; + else hi = mid - 1; + } + + return -1; + +}; + +console.log(search([], 5)) +console.log(search([1], 0)) +console.log(search([4, 5, 6, 7, 0, 1, 2], 2)) +console.log(search([3, 1], 1)) \ No newline at end of file diff --git a/034-Search-for-a-Range.js b/034-Search-for-a-Range.js new file mode 100644 index 0000000..eea7917 --- /dev/null +++ b/034-Search-for-a-Range.js @@ -0,0 +1,43 @@ +/** + * + * https://leetcode.com/problems/search-for-a-range/description/ + * Difficulty:Medium + * + * Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. + * Your algorithm's runtime complexity must be in the order of O(log n). + * If the target is not found in the array, return [-1, -1]. + * For example, + * Given [5, 7, 7, 8, 8, 10] and target value 8, + * return [3, 4]. + * + */ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var searchRange = function (nums, target) { + + var i = 0; + var j = nums.length - 1; + var ret = [-1, -1]; + while (i < j) { + var mid = Math.floor((i + j) / 2); + // console.log(i, mid, j); + if (nums[mid] < target) i = mid + 1; + else j = mid; + } + if (nums[i] !== target) return ret; + ret[0] = i; + j = nums.length - 1; + while (i < j) { + mid = Math.ceil((i + j) / 2); + // console.log(i, mid, j); + if (nums[mid] > target) j = mid - 1; + else i = mid; + } + ret[1] = j; + return ret; +}; + +console.log(searchRange([5, 7, 7, 8, 8, 10], 8)); \ No newline at end of file diff --git a/036-Valid-Sudoku.js b/036-Valid-Sudoku.js new file mode 100644 index 0000000..8b35f51 --- /dev/null +++ b/036-Valid-Sudoku.js @@ -0,0 +1,67 @@ +/** + * https://leetcode.com/problems/valid-sudoku/description/ + * Difficulty:Medium + * + * Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. + * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. + * A partially filled sudoku which is valid. + * Note: + * A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. + * + */ +/** + * @param {character[][]} board + * @return {boolean} + */ +var isValidSudoku = function (board) { + for (var i = 0; i < 9; i++) { + var rowNums = []; + var colNums = []; + var cubeNums = []; + + for (var j = 0; j < 9; j++) { + var ch = board[i][j]; + if (ch !== '.') { + if (rowNums.indexOf(ch) > -1) return false; + rowNums.push(ch); + } + + ch = board[j][i]; + if (ch !== '.') { + if (colNums.indexOf(ch) > -1) return false; + colNums.push(ch); + } + + var row = Math.floor(i / 3) * 3 + Math.floor(j / 3); + var col = i % 3 * 3 + j % 3; + // console.log(i, j, row, col); + ch = board[row][col]; + if (ch !== '.') { + if (cubeNums.indexOf(ch) > -1) return false; + cubeNums.push(ch); + } + } + } + return true; +}; + +// console.log(isValidSudoku([ +// [".", "8", "7", "6", "5", "4", "3", "2", "1"], +// ["2", ".", ".", ".", ".", ".", ".", ".", "."], +// ["3", ".", ".", ".", ".", ".", ".", ".", "."], +// ["4", ".", ".", ".", ".", ".", ".", ".", "."], +// ["5", ".", ".", ".", ".", ".", ".", ".", "."], +// ["6", ".", ".", ".", ".", ".", ".", ".", "."], +// ["7", ".", ".", ".", ".", ".", ".", ".", "."], +// ["8", ".", ".", ".", ".", ".", ".", ".", "."], +// ["9", ".", ".", ".", ".", ".", ".", ".", "."]])); +console.log(isValidSudoku([ + [".", ".", "4", ".", ".", ".", "6", "3", "."], + [".", ".", ".", ".", ".", ".", ".", ".", "."], + ["5", ".", ".", ".", ".", ".", ".", "9", "."], + [".", ".", ".", "5", "6", ".", ".", ".", "."], + ["4", ".", "3", ".", ".", ".", ".", ".", "1"], + [".", ".", ".", "7", ".", ".", ".", ".", "."], + [".", ".", ".", "5", ".", ".", ".", ".", "."], + [".", ".", ".", ".", ".", ".", ".", ".", "."], + [".", ".", ".", ".", ".", ".", ".", ".", "."]])) diff --git a/038-Count-and-Say.js b/038-Count-and-Say.js new file mode 100644 index 0000000..5dbeb74 --- /dev/null +++ b/038-Count-and-Say.js @@ -0,0 +1,58 @@ +/** + * https://leetcode.com/problems/count-and-say/description/ + * Difficulty:Easy + * + * The count-and-say sequence is the sequence of integers with the first five terms as following: + * 1. 1 + * 2. 11 + * 3. 21 + * 4. 1211 + * 5. 111221 + * + * 1 is read off as "one 1" or 11. + * + * 11 is read off as "two 1s" or 21. + * + * 21 is read off as "one 2, then one 1" or 1211. + * + * Given an integer n, generate the nth term of the count-and-say sequence. + * + * Note: Each term of the sequence of integers will be represented as a string. + * + * Example 1: + * Input: 1 + * Output: "1" + * + * Example 2: + * Input: 4 + * Output: "1211" + */ + +/** + * @param {number} n + * @return {string} + */ +var countAndSay = function (n) { + var ans = '1'; + for (var i = 1; i < n; i++) { + var tmp = ''; + var cnt = 1; + for (var j = 1; j < ans.length; j++) { + if (ans[j] === ans[j - 1]) cnt++; + else { + tmp += (cnt + ans[j - 1]); + cnt = 1; + } + } + ans = tmp + cnt + ans[j - 1]; + } + + return ans; +}; + +console.log(countAndSay(1)); +console.log(countAndSay(2)); +console.log(countAndSay(3)); +console.log(countAndSay(4)); +console.log(countAndSay(5)); +console.log(countAndSay(6)); \ No newline at end of file diff --git a/067-Add-Binary.js b/067-Add-Binary.js new file mode 100644 index 0000000..9fc2a79 --- /dev/null +++ b/067-Add-Binary.js @@ -0,0 +1,44 @@ +/** + * https://leetcode.com/problems/add-binary/description/ + * Difficulty:Easy + * Given two binary strings, return their sum (also a binary string). + * For example, + * a = "11" + * b = "1" + * Return "100". + */ + +/** + * @param {string} a + * @param {string} b + * @return {string} + */ +var addBinary = function (a, b) { + var c = 0; + var alen = a.length; + var blen = b.length; + var ans = ''; + for (var i = 0; i < Math.max(alen, blen); i++) { + var ai = i < alen ? parseInt(a[alen - i - 1]) : 0; + var bi = i < blen ? parseInt(b[blen - i - 1]) : 0; + + var sum = ai + bi + c; + // console.log(ai, bi, c); + if (sum < 2) { + ans = sum + ans; + c = 0; + } + else { + ans = (sum - 2) + ans; + c = 1; + } + } + if (c) { + ans = 1 + ans; + } + + return ans; + +}; + +console.log(addBinary('111', '1')); \ No newline at end of file diff --git a/101-Symmetric-Tree.js b/101-Symmetric-Tree.js new file mode 100644 index 0000000..b77f45a --- /dev/null +++ b/101-Symmetric-Tree.js @@ -0,0 +1,66 @@ +/** + * https://leetcode.com/problems/symmetric-tree/description/ + * Difficulty:Easy + * + * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). + * For example, this binary tree [1,2,2,3,4,4,3] is symmetric: + * 1 + * / \ + * 2 2 + * / \ / \ + * 3 4 4 3 + * But the following [1,2,2,null,3,null,3] is not: + * 1 + * / \ + * 2 2 + * \ \ + * 3 3 + * Note: + * Bonus points if you could solve it both recursively and iteratively. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isSymmetric = function (root) { + if (!root) return true; + return helper(root.left, root.right) +}; + +function helper(a, b) { + if (!a && !b) return true; + if (!a) return false; + if (!b) return false; + if (a.val !== b.val) return false; + return helper(a.left, b.right) && helper(a.right, b.left); +} + +console.log(isSymmetric({ + val: 1, + left: { + val: 2, + left: { + val: 3, + }, + right: { + val: 4 + } + }, + right: { + val: 2, + left: { + val: 4, + }, + right: { + val: 3 + } + } +})) \ No newline at end of file From 668958463c95dff61db48a04579c82a549ca306f Mon Sep 17 00:00:00 2001 From: zongyanqi Date: Wed, 3 Jan 2018 17:55:26 +0800 Subject: [PATCH 5/6] add 043-Multiply-Strings --- 043-Multiply-Strings.js | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 043-Multiply-Strings.js diff --git a/043-Multiply-Strings.js b/043-Multiply-Strings.js new file mode 100644 index 0000000..5726341 --- /dev/null +++ b/043-Multiply-Strings.js @@ -0,0 +1,46 @@ +/** + * https://leetcode.com/problems/multiply-strings/description/ + * Difficulty:Medium + * + * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. + * Note: + * The length of both num1 and num2 is < 110. + * Both num1 and num2 contains only digits 0-9. + * Both num1 and num2 does not contain any leading zero. + * You must not use any built-in BigInteger library or convert the inputs to integer directly. + */ + +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var multiply = function (num1, num2) { + var m = num1.length; + var n = num2.length; + var arr = new Array(m + n).fill(0); + for (var i = m - 1; i >= 0; i--) { + for (var j = n - 1; j >= 0; j--) { + var mul = (num1[i] - '0') * (num2[j] - '0'); + + var sum = mul + arr[i + j + 1]; + + arr[i + j] += Math.floor(sum / 10); + arr[i + j + 1] = sum % 10; + } + } + + var str = arr.reduce((a, b) => { + if (a === '' && b === 0) return a; + return a + b; + }, ''); + + return str ? str : '0'; + +}; + +console.log(multiply('89', '45')); +console.log(multiply('123', '123')); +console.log(multiply('123', '0')); + + From 3fd0aebc41b033266ea21250c382b4bac527eb5a Mon Sep 17 00:00:00 2001 From: zongyanqi Date: Fri, 5 Jan 2018 17:05:53 +0800 Subject: [PATCH 6/6] add 037 039 040 046 047 500 57 617 728 --- 037-Sudoku-Solver.js | 88 ++++++++++++++++++++++++++++ 039-Combination-Sum.js | 50 ++++++++++++++++ 040-Combination-Sum-II.js | 45 ++++++++++++++ 046-Permutations.js | 38 ++++++++++++ 047-Permutations-II.js | 47 +++++++++++++++ 500-Keyboard-Row.js | 40 +++++++++++++ 557-Reverse-Words-in-a-String-III.js | 20 +++++++ 617-Merge-Two-Binary-Trees.js | 73 +++++++++++++++++++++++ 728-Self-Dividing-Numbers.js | 44 ++++++++++++++ 9 files changed, 445 insertions(+) create mode 100644 037-Sudoku-Solver.js create mode 100644 039-Combination-Sum.js create mode 100644 040-Combination-Sum-II.js create mode 100644 046-Permutations.js create mode 100644 047-Permutations-II.js create mode 100644 500-Keyboard-Row.js create mode 100644 557-Reverse-Words-in-a-String-III.js create mode 100644 617-Merge-Two-Binary-Trees.js create mode 100644 728-Self-Dividing-Numbers.js diff --git a/037-Sudoku-Solver.js b/037-Sudoku-Solver.js new file mode 100644 index 0000000..31508ef --- /dev/null +++ b/037-Sudoku-Solver.js @@ -0,0 +1,88 @@ +/** + * https://leetcode.com/problems/sudoku-solver/description/ + * Difficulty:Hard + * + * Write a program to solve a Sudoku puzzle by filling the empty cells. + * Empty cells are indicated by the character '.'. + * You may assume that there will be only one unique solution. + */ + +/** + * @param {character[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ +var solveSudoku = function (board) { + solve(board); + console.log(board); +}; + +function solve(board) { + for (var i = 0; i < 9; i++) { + for (var j = 0; j < 9; j++) { + var ch = board[i][j]; + if (ch === '.') { + for (var k = 1; k <= 9; k++) { + + if (isValid(i, j, board, '' + k)) { + + board[i][j] = '' + k; + // console.log(board); + // console.log('-------------'); + if (solve(board)) { + // console.log(board); + // console.log('-------------'); + return true; + } else { + board[i][j] = '.'; + } + } + } + return false; + } + } + } + return true; +} + +function isValid(row, col, board, t) { + + for (var i = 0; i < 9; i++) { + var ch = board[row][i]; + if (ch === t) return false; + + ch = board[i][col]; + if (ch === t) return false; + + ch = board[Math.floor(row / 3) * 3 + Math.floor(i / 3)][Math.floor(col / 3) * 3 + i % 3]; + // if (row === 0 && col === 8) { + // console.log('~ ', Math.floor(row / 3) * 3 + Math.floor(i / 3), Math.floor(row / 3) * 3 + i % 3, ch); + // } + if (ch === t) return false; + } + return true; + +} + +console.log(solveSudoku([ + [".", ".", "9", "7", "4", "8", ".", ".", "."], + ["7", ".", ".", ".", ".", ".", ".", ".", "."], + [".", "2", ".", "1", ".", "9", ".", ".", "."], + [".", ".", "7", ".", ".", ".", "2", "4", "."], + [".", "6", "4", ".", "1", ".", "5", "9", "."], + [".", "9", "8", ".", ".", ".", "3", ".", "."], + [".", ".", ".", "8", ".", "3", ".", "2", "."], + [".", ".", ".", ".", ".", ".", ".", ".", "6"], + [".", ".", ".", "2", "7", "5", "9", ".", "."] +])); + +console.log([ + ["5", "1", "9", "7", "4", "8", "6", "3", "2"], + ["7", "8", "3", "6", "5", "2", "4", "1", "9"], + ["4", "2", "6", "1", "3", "9", "8", "7", "5"], + ["3", "5", "7", "9", "8", "6", "2", "4", "1"], + ["2", "6", "4", "3", "1", "7", "5", "9", "8"], + ["1", "9", "8", "5", "2", "4", "3", "6", "7"], + ["9", "7", "5", "8", "6", "3", "1", "2", "4"], + ["8", "3", "2", "4", "9", "1", "7", "5", "6"], + ["6", "4", "1", "2", "7", "5", "9", "8", "3"] +]) diff --git a/039-Combination-Sum.js b/039-Combination-Sum.js new file mode 100644 index 0000000..ef4976b --- /dev/null +++ b/039-Combination-Sum.js @@ -0,0 +1,50 @@ +/** + * https://leetcode.com/problems/combination-sum/description/ + * Difficulty:Medium + * + * Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. + * The same repeated number may be chosen from C unlimited number of times. + * Note: + * All numbers (including target) will be positive integers. + * The solution set must not contain duplicate combinations. + * For example, given candidate set [2, 3, 6, 7] and target 7, + * A solution set is: + * [ + * [7], + * [2, 2, 3] + * ] + */ + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum = function (candidates, target) { + + var res = []; + var temp = []; + helper(res, temp, candidates, target, 0); + return res; + +}; + +function helper(res, temp, candidates, target, start) { + + if (target === 0) { + res.push([...temp]); + return; + } + + for (var i = start; i < candidates.length; i++) { + if (candidates[i] <= target) { + temp.push(candidates[i]); + helper(res, temp, candidates, target - candidates[i], i); + temp.length -= 1; + } + + } +} + +console.log(combinationSum([1, 2, 3, 5, 6, 7], 7)); +console.log(combinationSum([7, 2, 3, 5, 6, 1], 7)); \ No newline at end of file diff --git a/040-Combination-Sum-II.js b/040-Combination-Sum-II.js new file mode 100644 index 0000000..43eed41 --- /dev/null +++ b/040-Combination-Sum-II.js @@ -0,0 +1,45 @@ +/** + * Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. + * Each number in C may only be used once in the combination. + * Note: + * All numbers (including target) will be positive integers. + * The solution set must not contain duplicate combinations. + * For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, + * A solution set is: + * [ + * [1, 7], + * [1, 2, 5], + * [2, 6], + * [1, 1, 6] + * ] + */ + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function (candidates, target) { + + var res = []; + var temp = []; + candidates.sort((b, a) => b - a); + helper(res, temp, candidates, target, 0); + return res; +}; + +function helper(res, temp, candidates, target, start) { + if (target === 0) { + return res.push([...temp]); + } + + for (var i = start; i < candidates.length && candidates[i] <= target; i++) { + if (i === start || candidates[i] !== candidates[i - 1]) { + temp.push(candidates[i]); + helper(res, temp, candidates, target - candidates[i], i + 1); + temp.length -= 1; + } + } +} + +console.log(combinationSum2([10, 1, 2, 7, 6, 1, 5], 8)); \ No newline at end of file diff --git a/046-Permutations.js b/046-Permutations.js new file mode 100644 index 0000000..db9349b --- /dev/null +++ b/046-Permutations.js @@ -0,0 +1,38 @@ +/** + * https://leetcode.com/problems/permutations/description/ + * Difficulty:Medium + * + * Given a collection of distinct numbers, return all possible permutations. + * For example, + * [1,2,3] have the following permutations: + * [ + * [1,2,3], + * [1,3,2], + * [2,1,3], + * [2,3,1], + * [3,1,2], + * [3,2,1] + * ] + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function (nums) { + if (!nums.length) return []; + var res = [[]]; + for (var i = 0; i < nums.length; i++) { + var len = res.length; + for (var j = 0; j < len; j++) { + var oldArr = res.shift(); + for (var k = 0; k <= oldArr.length; k++) { + var newArr = oldArr.slice(); + newArr.splice(k, 0, nums[i]); + res.push(newArr); + } + } + } + return res; +}; +console.log(permute([1, 2, 3])); \ No newline at end of file diff --git a/047-Permutations-II.js b/047-Permutations-II.js new file mode 100644 index 0000000..5618acf --- /dev/null +++ b/047-Permutations-II.js @@ -0,0 +1,47 @@ +/** + * https://leetcode.com/problems/permutations-ii/description/ + * Difficulty:Medium + * + * Given a collection of numbers that might contain duplicates, return all possible unique permutations. + * For example, + * [1,1,2] have the following unique permutations: + * [ + * [1,1,2], + * [1,2,1], + * [2,1,1] + * ] + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permuteUnique = function (nums) { + if (!nums.length) return []; + nums.sort((a, b) => a - b); + var res = [[]]; + for (var i = 0; i < nums.length; i++) { + var len = res.length; + for (var j = 0; j < len; j++) { + var oldArr = res.shift(); + if (i > 0 && nums[i] === nums[i - 1]) { + var k = oldArr.lastIndexOf(nums[i]); + } else { + k = 0; + } + for (; k <= oldArr.length; k++) { + + if (k === oldArr.length || nums[i] !== oldArr[k]) { + var newArr = oldArr.slice(); + newArr.splice(k, 0, nums[i]); + // console.log(oldArr, newArr); + res.push(newArr); + } + + } + } + } + return res; +}; + +console.log(permuteUnique([1, 2, 2, 1])); \ No newline at end of file diff --git a/500-Keyboard-Row.js b/500-Keyboard-Row.js new file mode 100644 index 0000000..458bec4 --- /dev/null +++ b/500-Keyboard-Row.js @@ -0,0 +1,40 @@ +/** + * https://leetcode.com/problems/keyboard-row/description/ + * Difficulty:Easy + * + * Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. + * + * Example 1: + * Input: ["Hello", "f", "Dad", "Peace"] + * Output: ["Alaska", "Dad"] + * Note: + * You may use one character in the keyboard more than once. + * You may assume the input string will only contain letters of alphabet. + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var findWords = function (words) { + + var s = 'qwertyuiopasdfghjklzxcvbnm'; + return words.filter(w => { + if (!w) return true; + w = w.toLowerCase(); + var t = row(w[0]); + for (var i = 1; i < w.length; i++) { + if (t !== row(w[i])) return false; + } + return true; + }); + + function row(ch) { + var i = s.indexOf(ch); + if (i < 10) return 0; + if (i < 19) return 1; + return 2; + } + +}; +console.log(findWords(["Hello", "Alaska", "Dad", "Peace"])) \ No newline at end of file diff --git a/557-Reverse-Words-in-a-String-III.js b/557-Reverse-Words-in-a-String-III.js new file mode 100644 index 0000000..51709e9 --- /dev/null +++ b/557-Reverse-Words-in-a-String-III.js @@ -0,0 +1,20 @@ +/** + * https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ + * Difficulty:Easy + * + * Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. + * Example 1: + * Input: "Let's take LeetCode contest" + * Output: "s'teL ekat edoCteeL tsetnoc" + * Note: In the string, each word is separated by single space and there will not be any extra space in the string. + */ + +/** + * @param {string} s + * @return {string} + */ +var reverseWords = function (s) { + return s.split(' ').map(w => w.split('').reverse().join('')).join(' '); +}; + +console.log(reverseWords(`Let's take LeetCode contest`)) \ No newline at end of file diff --git a/617-Merge-Two-Binary-Trees.js b/617-Merge-Two-Binary-Trees.js new file mode 100644 index 0000000..1cfa285 --- /dev/null +++ b/617-Merge-Two-Binary-Trees.js @@ -0,0 +1,73 @@ +/** + * https://leetcode.com/problems/merge-two-binary-trees/description/ + * Difficulty:Easy + * + * Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. + * You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. + * + * Example 1: + * Input: + * Tree 1 Tree 2 + * 1 2 + * / \ / \ + * 3 2 1 3 + * / \ \ + * 5 4 7 + * + * Output: + * Merged tree: + * 3 + * / \ + * 4 5 + * / \ \ + * 5 4 7 + * Note: The merging process must start from the root nodes of both trees. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} t1 + * @param {TreeNode} t2 + * @return {TreeNode} + */ +var mergeTrees = function (t1, t2) { + if (!t1) return t2; + if (!t2) return t1; + t1.val += t2.val; + t1.left = mergeTrees(t1.left, t2.left); + t1.right = mergeTrees(t1.right, t2.right); + return t1; +}; + +console.log(mergeTrees({ + val: 1, + left: { + val: 3, + left: { + val: 5 + } + }, + right: { + val: 2 + } +}, { + val: 2, + left: { + val: 1, + right: { + val: 4 + } + }, + right: { + val: 3, + right: { + val: 7 + } + } +})) \ No newline at end of file diff --git a/728-Self-Dividing-Numbers.js b/728-Self-Dividing-Numbers.js new file mode 100644 index 0000000..f649687 --- /dev/null +++ b/728-Self-Dividing-Numbers.js @@ -0,0 +1,44 @@ +/** + * https://leetcode.com/problems/self-dividing-numbers/description/ + * Difficulty:Easy + * + * A self-dividing number is a number that is divisible by every digit it contains. + * + * For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. + * Also, a self-dividing number is not allowed to contain the digit zero. + * Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. + * + * Example 1: + * Input: + * left = 1, right = 22 + * Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] + * Note: + * The boundaries of each input argument are 1 <= left <= right <= 10000. + */ + +/** + * @param {number} left + * @param {number} right + * @return {number[]} + */ +var selfDividingNumbers = function (left, right) { + var res = []; + for (var i = left; i <= right; i++) { + if (isSelfDividingNumber(i)) res.push(i); + } + return res; +}; + +function isSelfDividingNumber(n) { + var t = n; + if (!t) return false; + while (t) { + var r = t % 10; + t = Math.floor(t / 10); + if (!r) return false; + if (n % r) return false; + } + return true; +} + +console.log(selfDividingNumbers(1, 22)); \ No newline at end of file