diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..750e8ac8 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: https://raw.githubusercontent.com/Blankj/AndroidUtilCode/master/art/donate.png diff --git a/README.md b/README.md index 99999aad..7f7fa5da 100644 --- a/README.md +++ b/README.md @@ -23,152 +23,165 @@ > 非也非也, > 科举为国取士,LeetCode 为 Google 筛码工,各取所需也。 - ## Easy -| # | Title | Tag | -| :--- | :--------------------------------------- | :--------------------------------------- | -| 1 | [Two Sum][001] | Array, Hash Table | -| 7 | [Reverse Integer][007] | Math | -| 9 | [Palindrome Number][009] | Math | -| 13 | [Roman to Integer][013] | Math, String | -| 14 | [Longest Common Prefix][014] | String | -| 20 | [Valid Parentheses][020] | Stack, String | -| 21 | [Merge Two Sorted Lists][021] | Linked List | -| 26 | [Remove Duplicates from Sorted Array][026] | Array, Two Pointers | -| 27 | [Remove Element][027] | Array, Two Pointers | -| 28 | [Implement strStr()][028] | Two Pointers, String | -| 35 | [Search Insert Position][035] | String | -| 38 | [Count and Say][038] | String | -| 53 | [Maximum Subarray][053] | Array, Divide and Conquer, Dynamic Programming | -| 58 | [Length of Last Word][058] | String | -| 66 | [Plus One][066] | Array, Math | -| 67 | [Add Binary][067] | Math, String | -| 69 | [Sqrt(x)][069] | Binary Search, Math | -| 70 | [Climbing Stairs][070] | Dynamic Programming | -| 83 | [Remove Duplicates from Sorted List][083] | Linked List | -| 88 | [Merge Sorted Array][088] | Array, Two Pointers | -| 100 | [Same Tree][100] | Tree, Depth-first Search | -| 101 | [Symmetric Tree][101] | Tree, Depth-first Search, Breadth-first Search | -| 104 | [Maximum Depth of Binary Tree][104] | Tree, Depth-first Search | -| 107 | [Binary Tree Level Order Traversal II][107] | Tree, Breadth-first Search | -| 108 | [Convert Sorted Array to Binary Search Tree][108] | Tree, Depth-first Search | -| 110 | [Balanced Binary Tree][110] | Tree, Depth-first Search | -| 111 | [Minimum Depth of Binary Tree][111] | Tree, Depth-first Search, Breadth-first Search | -| 112 | [Path Sum][112] | Tree, Depth-first Search | -| 118 | [Pascal's Triangle][118] | Array | -| 119 | [Pascal's Triangle II][119] | Array | -| 121 | [Best Time to Buy and Sell Stock][121] | Array, Dynamic Programmin | -| 122 | [Best Time to Buy and Sell Stock II][122] | Array, Greedy | -| 543 | [Diameter of Binary Tree][543] | Tree | - +| # | Title | Tag | +| :--- | :---------------------------------------------------------------- | :------------------------------------------------ | +| 1 | [Two Sum][0001] | Array, Hash Table | +| 7 | [Reverse Integer][0007] | Math | +| 9 | [Palindrome Number][0009] | Math | +| 13 | [Roman to Integer][0013] | Math, String | +| 14 | [Longest Common Prefix][0014] | String | +| 16.11| [跳水板(Diving Board LCCI)][16_11] | 递归、记忆化 | +| 20 | [Valid Parentheses][0020] | Stack, String | +| 21 | [Merge Two Sorted Lists][0021] | Linked List | +| 26 | [Remove Duplicates from Sorted Array][0026] | Array, Two Pointers | +| 27 | [Remove Element][0027] | Array, Two Pointers | +| 28 | [Implement strStr()][0028] | Two Pointers, String | +| 35 | [Search Insert Position][0035] | String | +| 38 | [Count and Say][0038] | String | +| 53 | [Maximum Subarray][0053] | Array, Divide and Conquer, Dynamic Programming | +| 58 | [Length of Last Word][0058] | String | +| 66 | [Plus One][0066] | Array, Math | +| 67 | [Add Binary][0067] | Math, String | +| 69 | [Sqrt(x)][0069] | Binary Search, Math | +| 70 | [Climbing Stairs][0070] | Dynamic Programming | +| 83 | [Remove Duplicates from Sorted List][0083] | Linked List | +| 88 | [Merge Sorted Array][0088] | Array, Two Pointers | +| 100 | [Same Tree][0100] | Tree, Depth-first Search | +| 101 | [Symmetric Tree][0101] | Tree, Depth-first Search, Breadth-first Search | +| 104 | [Maximum Depth of Binary Tree][0104] | Tree, Depth-first Search | +| 107 | [Binary Tree Level Order Traversal II][107] | Tree, Breadth-first Search | +| 108 | [Convert Sorted Array to Binary Search Tree][0108] | Tree, Depth-first Search | +| 110 | [Balanced Binary Tree][0110] | Tree, Depth-first Search | +| 111 | [Minimum Depth of Binary Tree][0111] | Tree, Depth-first Search, Breadth-first Search | +| 112 | [Path Sum][0112] | Tree, Depth-first Search | +| 118 | [Pascal's Triangle][0118] | Array | +| 119 | [Pascal's Triangle II][0119] | Array | +| 121 | [Best Time to Buy and Sell Stock][0121] | Array, Dynamic Programmin | +| 122 | [Best Time to Buy and Sell Stock II][0122] | Array, Greedy | +| 543 | [Diameter of Binary Tree][0543] | Tree | ## Medium -| # | Title | Tag | -| :--- | :--------------------------------------- | :------------------------------- | -| 2 | [Add Two Numbers][002] | Linked List, Math | -| 3 | [Longest Substring Without Repeating Characters][003] | Hash Table, Two Pointers, String | -| 5 | [Longest Palindromic Substring][005] | String | -| 6 | [ZigZag Conversion][006] | String | -| 8 | [String to Integer (atoi)][008] | Math, String | -| 11 | [Container With Most Water][011] | Array, Two Pointers | -| 12 | [Integer to Roman][012] | Math, String | -| 15 | [3Sum][015] | Array, Two Pointers | -| 15 | [3Sum Closest][016] | Array, Two Pointers | -| 17 | [Letter Combinations of a Phone Number][017] | String, Backtracking | -| 18 | [4Sum][018] | Array, Hash Table, Two Pointers | -| 19 | [Remove Nth Node From End of List][019] | Linked List, Two Pointers | -| 22 | [Generate Parentheses][022] | String, Backtracking | -| 24 | [Swap Nodes in Pairs][024] | Linked List | -| 29 | [Divide Two Integers][029] | Math, Binary Search | -| 33 | [Search in Rotated Sorted Array][033] | Arrays, Binary Search | -| 43 | [Multiply Strings][043] | Math, String | -| 49 | [Group Anagrams][049] | Hash Table, String | -| 50 | [Pow(x, n)][050] | Math, Binary Search | -| 56 | [Merge Intervals][056] | Array, Sort | -| 554 | [Brick Wall][554] | Hash Table | - +| # | Title | Tag | +| :--- | :---------------------------------------------------------------- | :------------------------------------------------ | +| 2 | [Add Two Numbers][0002] | Linked List, Math | +| 3 | [Longest Substring Without Repeating Characters][0003] | Hash Table, Two Pointers, String | +| 5 | [Longest Palindromic Substring][0005] | String, Dynamic Programming | +| 6 | [ZigZag Conversion][0006] | String | +| 8 | [String to Integer (atoi)][0008] | Math, String | +| 11 | [Container With Most Water][0011] | Array, Two Pointers | +| 12 | [Integer to Roman][0012] | Math, String | +| 15 | [3Sum][0015] | Array, Two Pointers | +| 15 | [3Sum Closest][0016] | Array, Two Pointers | +| 17 | [Letter Combinations of a Phone Number][0017] | String, Backtracking | +| 18 | [4Sum][0018] | Array, Hash Table, Two Pointers | +| 19 | [Remove Nth Node From End of List][0019] | Linked List, Two Pointers | +| 22 | [Generate Parentheses][0022] | String, Backtracking | +| 24 | [Swap Nodes in Pairs][0024] | Linked List | +| 29 | [Divide Two Integers][0029] | Math, Binary Search | +| 33 | [Search in Rotated Sorted Array][0033] | Arrays, Binary Search | +| 43 | [Multiply Strings][0043] | Math, String | +| 49 | [Group Anagrams][0049] | Hash Table, String | +| 50 | [Pow(x, n)][0050] | Math, Binary Search | +| 56 | [Merge Intervals][0056] | Array, Sort | +| 63 | [不同路径 II(Unique Paths II)][0063] | 数组、动态规划 | +| 209 | [长度最小的子数组(Minimum Size Subarray Sum)][0209] | 数组、双指针、二分查找 | +| 215 | [数组中的第K个最大元素(Kth Largest Element in an Array)][0215] | 堆、分治算法 | +| 554 | [Brick Wall][0554] | Hash Table | +| 1014 | [最佳观光组合(Best Sightseeing Pair)][1014] | 数组 | ## Hard -| # | Title | Tag | -| :--- | :--------------------------------- | :--------------------------------------- | -| 4 | [Median of Two Sorted Arrays][004] | Array, Binary Search, Divide and Conquer | -| 10 | [Regular Expression Matching][010] | String, Dynamic Programming, Backtracking | -| 23 | [Merge k Sorted Lists][023] | Linked List, Divide and Conquer, Heap | -| 25 | [Reverse Nodes in k-Group][025] | Linked List | -| 44 | [Wildcard Matching][044] | String, Dynamic Programming, Backtracking, Greedy | -| 57 | [Insert Interval][057] | Array, Sort | -| 68 | [Text Justification][068] | String | +| # | Title | Tag | +| :--- | :---------------------------------------------------------------- | :------------------------------------------------ | +| 4 | [Median of Two Sorted Arrays][0004] | Array, Binary Search, Divide and Conquer | +| 10 | [Regular Expression Matching][0010] | String, Dynamic Programming, Backtracking | +| 23 | [Merge k Sorted Lists][0023] | Linked List, Divide and Conquer, Heap | +| 25 | [Reverse Nodes in k-Group][0025] | Linked List | +| 30 | [Substring with Concatenation of All Words][0030] | Hash Table, Two Pointers, String | +| 44 | [Wildcard Matching][0044] | String, Dynamic Programming, Backtracking, Greedy | +| 57 | [Insert Interval][0057] | Array, Sort | +| 68 | [Text Justification][0068] | String | +| 1028 | [从先序遍历还原二叉树(Recover a Tree From Preorder Traversal)][1028] | 树、深度优先搜索 | +## 打个小广告 +欢迎加入我的小专栏「**[基你太美](https://xiaozhuanlan.com/Blankj)**」一起学习。 [src]: https://github.com/Blankj/awesome-java-leetcode/tree/master/src [note]: https://github.com/Blankj/awesome-java-leetcode/tree/master/note [companies]: https://github.com/Blankj/awesome-java-leetcode/blob/master/Companies.md -[001]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/001/README.md -[007]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/007/README.md -[009]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/009/README.md -[013]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/013/README.md -[014]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/014/README.md -[020]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/020/README.md -[021]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/021/README.md -[026]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/026/README.md -[027]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/027/README.md -[028]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/028/README.md -[035]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/035/README.md -[038]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/038/README.md -[053]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/053/README.md -[058]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/058/README.md -[066]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/066/README.md -[067]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/067/README.md -[069]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/069/README.md -[070]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/070/README.md -[083]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/083/README.md -[088]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/088/README.md -[100]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/100/README.md -[101]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/101/README.md -[104]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/104/README.md -[107]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/107/README.md -[108]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/108/README.md -[110]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/110/README.md -[111]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/111/README.md -[112]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/112/README.md -[118]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/118/README.md -[119]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/119/README.md -[121]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/121/README.md -[122]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/122/README.md -[543]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/543/README.md - -[002]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/002/README.md -[003]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/003/README.md -[005]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/005/README.md -[006]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/006/README.md -[008]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/008/README.md -[011]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/011/README.md -[012]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/012/README.md -[015]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/015/README.md -[016]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/016/README.md -[017]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/017/README.md -[018]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/018/README.md -[019]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/019/README.md -[022]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/022/README.md -[024]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/024/README.md -[029]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/029/README.md -[033]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/033/README.md -[043]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/043/README.md -[049]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/049/README.md -[050]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/050/README.md -[056]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/056/README.md -[554]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/554/README.md - -[004]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/004/README.md -[010]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/010/README.md -[023]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/023/README.md -[025]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/025/README.md -[044]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/044/README.md -[057]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/057/README.md -[068]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/068/README.md +[0001]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0001/README.md +[0007]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0007/README.md +[0009]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0009/README.md +[0013]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0013/README.md +[0014]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0014/README.md +[16_11]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/16_11/README.md +[0020]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0020/README.md +[0021]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0021/README.md +[0026]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0026/README.md +[0027]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0027/README.md +[0028]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0028/README.md +[0035]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0035/README.md +[0038]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0038/README.md +[0053]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0053/README.md +[0058]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0058/README.md +[0066]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0066/README.md +[0067]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0067/README.md +[0069]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0069/README.md +[0070]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0070/README.md +[0083]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0083/README.md +[0088]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0088/README.md +[0100]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0100/README.md +[0101]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0101/README.md +[0104]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0104/README.md +[0107]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0107/README.md +[0108]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0108/README.md +[0110]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0110/README.md +[0111]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0111/README.md +[0112]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0112/README.md +[0118]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0118/README.md +[0119]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0119/README.md +[0121]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0121/README.md +[0122]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0122/README.md +[0543]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0543/README.md + +[0002]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0002/README.md +[0003]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0003/README.md +[0005]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0005/README.md +[0006]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0006/README.md +[0008]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0008/README.md +[0011]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0011/README.md +[0012]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0012/README.md +[0015]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0015/README.md +[0016]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0016/README.md +[0017]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0017/README.md +[0018]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0018/README.md +[0019]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0019/README.md +[0022]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0022/README.md +[0024]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0024/README.md +[0029]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0029/README.md +[0033]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0033/README.md +[0043]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0043/README.md +[0049]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0049/README.md +[0050]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0050/README.md +[0056]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0056/README.md +[0063]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0063/README.md +[0209]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0209/README.md +[0215]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0215/README.md +[0554]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0554/README.md +[1014]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/1014/README.md + +[0004]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0004/README.md +[0010]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0010/README.md +[0023]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0023/README.md +[0025]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0025/README.md +[0030]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0030/README.md +[0044]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0044/README.md +[0057]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0057/README.md +[0068]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/0068/README.md +[1028]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/1028/README.md diff --git a/note/001/README.md b/note/0001/README.md similarity index 93% rename from note/001/README.md rename to note/0001/README.md index f0224222..d7e9f7a8 100644 --- a/note/001/README.md +++ b/note/0001/README.md @@ -47,8 +47,9 @@ class Solution { int len = nums.length; HashMap map = new HashMap<>(); for (int i = 0; i < len; ++i) { - if (map.containsKey(nums[i])) { - return new int[]{map.get(nums[i]), i}; + final Integer value = map.get(nums[i]); + if (value != null) { + return new int[] { value, i }; } map.put(target - nums[i], i); } diff --git a/note/002/README.md b/note/0002/README.md similarity index 100% rename from note/002/README.md rename to note/0002/README.md diff --git a/note/003/README.md b/note/0003/README.md similarity index 100% rename from note/003/README.md rename to note/0003/README.md diff --git a/note/004/README.md b/note/0004/README.md similarity index 100% rename from note/004/README.md rename to note/0004/README.md diff --git a/note/004/my_draw.jpg b/note/0004/my_draw.jpg similarity index 100% rename from note/004/my_draw.jpg rename to note/0004/my_draw.jpg diff --git a/note/005/README.md b/note/0005/README.md similarity index 98% rename from note/005/README.md rename to note/0005/README.md index cd3bc6c3..fb74d65b 100644 --- a/note/005/README.md +++ b/note/0005/README.md @@ -4,7 +4,7 @@ Given a string **s**, find the longest palindromic substring in **s**. You may assume that the maximum length of **s** is 1000. -**Example:** +**Example 1:** ``` Input: "babad" @@ -14,7 +14,7 @@ Output: "bab" Note: "aba" is also a valid answer. ``` -**Example:** +**Example 2:** ``` Input: "cbbd" @@ -22,7 +22,7 @@ Input: "cbbd" Output: "bb" ``` -**Tags:** String +**Tags:** String, Dynamic Programming ## 思路 0 diff --git a/note/006/README.md b/note/0006/README.md similarity index 92% rename from note/006/README.md rename to note/0006/README.md index 28e382a7..a5ec493e 100644 --- a/note/006/README.md +++ b/note/0006/README.md @@ -15,10 +15,28 @@ 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); +string convert(string s, int numRows); ``` -`convert("PAYPALISHIRING", 3)` should return `"PAHNAPLSIIGYIR"`. +**Example 1:** + +``` +Input: s = "PAYPALISHIRING", numRows = 3 +Output: "PAHNAPLSIIGYIR" +``` + +**Example 2:** + +``` +Input: s = "PAYPALISHIRING", numRows = 4 +Output: "PINALSIGYAHRPI" +Explanation: + +P I N +A L S I G +Y A H R +P I +``` **Tags:** String diff --git a/note/007/README.md b/note/0007/README.md similarity index 100% rename from note/007/README.md rename to note/0007/README.md diff --git a/note/008/README.md b/note/0008/README.md similarity index 56% rename from note/008/README.md rename to note/0008/README.md index 4d0991f9..257e7df7 100644 --- a/note/008/README.md +++ b/note/0008/README.md @@ -2,23 +2,62 @@ ## Description -Implement atoi to convert a string to an integer. +Implement `atoi` which converts a string to an integer. -**Hint:** Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. +The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. -**Notes:** It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. +The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. -**Spoilers:** +If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. -**Requirements for atoi:** +If no valid conversion could be performed, a zero value is returned. -The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. +**Note:** -The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. +- Only the space character `' '` is considered as whitespace character. +- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. -If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. +**Example 1:** + +``` +Input: "42" +Output: 42 +``` + +**Example 2:** + +``` +Input: " -42" +Output: -42 +Explanation: The first non-whitespace character is '-', which is the minus sign. + Then take as many numerical digits as possible, which gets 42. +``` + +**Example 3:** + +``` +Input: "4193 with words" +Output: 4193 +Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. +``` + +**Example 4:** -If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. +``` +Input: "words and 987" +Output: 0 +Explanation: The first non-whitespace character is 'w', which is not a numerical + digit or a +/- sign. Therefore no valid conversion could be performed. +``` + +**Example 5:** + +``` +Input: "-91283472332" +Output: -2147483648 +Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. + Thefore INT_MIN (−2^31) is returned. +``` **Tags:** Math, String @@ -37,12 +76,13 @@ class Solution { } for (; i < len; ++i) { int tmp = str.charAt(i) - '0'; - if (tmp < 0 || tmp > 9) - break; - if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < tmp) + if (tmp < 0 || tmp > 9) break; + if (ans > Integer.MAX_VALUE / 10 + || (ans == Integer.MAX_VALUE / 10 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) { return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; - else + } else { ans = ans * 10 + tmp; + } } return sign * ans; } diff --git a/note/009/README.md b/note/0009/README.md similarity index 75% rename from note/009/README.md rename to note/0009/README.md index c549c911..9571fa0f 100644 --- a/note/009/README.md +++ b/note/0009/README.md @@ -2,19 +2,34 @@ ## Description -Determine whether an integer is a palindrome. Do this without extra space. +Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. -**Spoilers:** +**Example 1:** -**Some hints:** +``` +Input: 121 +Output: true +``` + +**Example 2:** + +``` +Input: -121 +Output: false +Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. +``` -Could negative integers be palindromes? (ie, -1) +**Example 3:** -If you are thinking of converting the integer to string, note the restriction of using extra space. +``` +Input: 10 +Output: false +Explanation: Reads 01 from right to left. Therefore it is not a palindrome. +``` -You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? +**Follow up:** -There is a more generic way of solving this problem. +Coud you solve it without converting the integer to a string? **Tags:** Math diff --git a/note/010/README.md b/note/0010/README.md similarity index 82% rename from note/010/README.md rename to note/0010/README.md index b52b6a5e..61421646 100644 --- a/note/010/README.md +++ b/note/0010/README.md @@ -2,25 +2,67 @@ ## Description -Implement regular expression matching with support for `'.'` and `'*'`. +Given an input string (`s`) and a pattern (`p`), implement regular expression matching with support for `'.'` and `'*'`. ``` '.' Matches any single character. '*' Matches zero or more of the preceding element. +``` + +The matching should cover the **entire** input string (not partial). + +**Note:** + +- `s` could be empty and contains only lowercase letters `a-z`. +- `p` could be empty and contains only lowercase letters `a-z`, and characters like `.` or `*`. + +**Example 1:** + +``` +Input: +s = "aa" +p = "a" +Output: false +Explanation: "a" does not match the entire string "aa". +``` + +**Example 2:** + +``` +Input: +s = "aa" +p = "a*" +Output: true +Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". +``` + +**Example 3:** + +``` +Input: +s = "ab" +p = ".*" +Output: true +Explanation: ".*" means "zero or more (*) of any character (.)". +``` -The matching should cover the entire input string (not partial). +**Example 4:** -The function prototype should be: -bool isMatch(const char *s, const char *p) +``` +Input: +s = "aab" +p = "c*a*b" +Output: true +Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". +``` -Some examples: -isMatch("aa", "a") → false -isMatch("aa", "aa") → true -isMatch("aaa", "aa") → false -isMatch("aa", "a*") → true -isMatch("aa", ".*") → true -isMatch("ab", ".*") → true -isMatch("aab", "c*a*b") → true +**Example 5:** + +``` +Input: +s = "mississippi" +p = "mis*is*p*." +Output: false ``` **Tags:** String, Dynamic Programming, Backtracking diff --git a/note/011/README.md b/note/0011/README.md similarity index 100% rename from note/011/README.md rename to note/0011/README.md diff --git a/note/011/water.png b/note/0011/water.png similarity index 100% rename from note/011/water.png rename to note/0011/water.png diff --git a/note/012/README.md b/note/0012/README.md similarity index 52% rename from note/012/README.md rename to note/0012/README.md index 002b22ec..b5f19663 100644 --- a/note/012/README.md +++ b/note/0012/README.md @@ -2,9 +2,65 @@ ## Description -Given an integer, convert it to a roman numeral. +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. -Input is guaranteed to be within the range from 1 to 3999. +``` +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 +``` + +For example, two is written as `II` in Roman numeral, just two one's added together. Twelve is written as, `XII`, which is simply `X` + `II`. The number twenty seven is written as `XXVII`, which is `XX` + `V` + `II`. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: + +- `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. +- `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. +- `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. + +Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. + +**Example 1:** + +``` +Input: 3 +Output: "III" +``` + +**Example 2:** + +``` +Input: 4 +Output: "IV" +``` + +**Example 3:** + +``` +Input: 9 +Output: "IX" +``` + +**Example 4:** + +``` +Input: 58 +Output: "LVIII" +Explanation: C = 100, L = 50, XXX = 30 and III = 3. +``` + +**Example 5:** + +``` +Input: 1994 +Output: "MCMXCIV" +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. +``` **Tags:** Math, String diff --git a/note/013/README.md b/note/0013/README.md similarity index 52% rename from note/013/README.md rename to note/0013/README.md index 5916ab9b..43c78400 100644 --- a/note/013/README.md +++ b/note/0013/README.md @@ -2,9 +2,65 @@ ## Description -Given a roman numeral, convert it to an integer. +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. -Input is guaranteed to be within the range from 1 to 3999. +``` +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 +``` + +For example, two is written as `II` in Roman numeral, just two one's added together. Twelve is written as, `XII`, which is simply `X` + `II`. The number twenty seven is written as `XXVII`, which is `XX` + `V` + `II`. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: + +- `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. +- `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. +- `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. + +Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. + +**Example 1:** + +``` +Input: "III" +Output: 3 +``` + +**Example 2:** + +``` +Input: "IV" +Output: 4 +``` + +**Example 3:** + +``` +Input: "IX" +Output: 9 +``` + +**Example 4:** + +``` +Input: "LVIII" +Output: 58 +Explanation: C = 100, L = 50, XXX = 30 and III = 3. +``` + +**Example 5:** + +``` +Input: "MCMXCIV" +Output: 1994 +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. +``` **Tags:** Math, String diff --git a/note/014/README.md b/note/0014/README.md similarity index 79% rename from note/014/README.md rename to note/0014/README.md index fa6617d6..03e70e4a 100644 --- a/note/014/README.md +++ b/note/0014/README.md @@ -4,6 +4,27 @@ Write a function to find the longest common prefix string amongst an array of strings. +If there is no common prefix, return an empty string `""`. + +**Example 1:** + +``` +Input: ["flower","flow","flight"] +Output: "fl" +``` + +**Example 2:** + +``` +Input: ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. +``` + +**Note:** + +All given inputs are in lowercase letters `a-z`. + **Tags:** String diff --git a/note/015/README.md b/note/0015/README.md similarity index 85% rename from note/015/README.md rename to note/0015/README.md index a5be6bf3..b127a623 100644 --- a/note/015/README.md +++ b/note/0015/README.md @@ -2,12 +2,16 @@ ## Description -Given an array *S* of *n* integers, are there elements *a*, *b*, *c* in *S* such that *a* + *b* + *c* = 0? Find all unique triplets in the array which gives the sum of zero. +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. -**Note:** The solution set must not contain duplicate triplets. +**Note:** + +The solution set must not contain duplicate triplets. + +**Example:** ``` -For example, given array S = [-1, 0, 1, 2, -1, -4], +Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ diff --git a/note/016/README.md b/note/0016/README.md similarity index 81% rename from note/016/README.md rename to note/0016/README.md index 6c6609e3..fb5a00d0 100644 --- a/note/016/README.md +++ b/note/0016/README.md @@ -2,12 +2,14 @@ ## Description -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. +Given an array `nums` of *n* integers and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return the sum of the three integers. You may assume that each input would have exactly one solution. + +**Example:** ``` - For example, given array S = {-1 2 1 -4}, and target = 1. +Given array nums = [-1, 2, 1, -4], and target = 1. - The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). +The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). ``` **Tags:** Array, Two Pointers diff --git a/note/017/README.md b/note/0017/README.md similarity index 99% rename from note/017/README.md rename to note/0017/README.md index ebf0bd5c..2849bfc6 100644 --- a/note/017/README.md +++ b/note/0017/README.md @@ -8,8 +8,10 @@ A mapping of digit to letters (just like on the telephone buttons) is given belo ![img](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png) +**Example:** + ``` -Input:Digit string "23" +Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. ``` diff --git a/note/018/README.md b/note/0018/README.md similarity index 92% rename from note/018/README.md rename to note/0018/README.md index 6b7c0834..4685eeb4 100644 --- a/note/018/README.md +++ b/note/0018/README.md @@ -2,12 +2,16 @@ ## Description -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. +Given an array `nums` of *n* integers and an integer `target`, are there elements *a*, *b*, *c*, and *d* in `nums` such that *a* + *b* + *c* + *d* = `target`? Find all unique quadruplets in the array which gives the sum of `target`. -**Note:** The solution set must not contain duplicate quadruplets. +**Note:** + +The solution set must not contain duplicate quadruplets. + +**Example:** ``` -For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. +Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ diff --git a/note/019/README.md b/note/0019/README.md similarity index 85% rename from note/019/README.md rename to note/0019/README.md index 1035c2a8..935113e4 100644 --- a/note/019/README.md +++ b/note/0019/README.md @@ -2,21 +2,23 @@ ## Description -Given a linked list, remove the *n*th node from the end of list and return its head. +Given a linked list, remove the *n*-th node from the end of list and return its head. -For example, +**Example:** ``` - Given linked list: 1->2->3->4->5, and n = 2. +Given linked list: 1->2->3->4->5, and n = 2. - After removing the second node from the end, the linked list becomes 1->2->3->5. +After removing the second node from the end, the linked list becomes 1->2->3->5. ``` **Note:** Given *n* will always be valid. -Try to do this in one pass. +**Follow up:** + +Could you do this in one pass? **Tags:** Linked List, Two Pointers diff --git a/note/020/README.md b/note/0020/README.md similarity index 76% rename from note/020/README.md rename to note/0020/README.md index 78837723..410d983a 100644 --- a/note/020/README.md +++ b/note/0020/README.md @@ -4,7 +4,47 @@ Given a string containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. -The brackets must close in the correct order, `"()"` and `"()[]{}"` are all valid but `"(]"` and `"([)]"` are not. +An input string is valid if: + +1. Open brackets must be closed by the same type of brackets. +2. Open brackets must be closed in the correct order. + +Note that an empty string is also considered valid. + +**Example 1:** + +``` +Input: "()" +Output: true +``` + +**Example 2:** + +``` +Input: "()[]{}" +Output: true +``` + +**Example 3:** + +``` +Input: "(]" +Output: false +``` + +**Example 4:** + +``` +Input: "([)]" +Output: false +``` + +**Example 5:** + +``` +Input: "{[]}" +Output: true +``` **Tags:** Stack, String diff --git a/note/021/README.md b/note/0021/README.md similarity index 100% rename from note/021/README.md rename to note/0021/README.md diff --git a/note/022/README.md b/note/0022/README.md similarity index 100% rename from note/022/README.md rename to note/0022/README.md diff --git a/note/023/README.md b/note/0023/README.md similarity index 96% rename from note/023/README.md rename to note/0023/README.md index 262a7d56..3de0690a 100644 --- a/note/023/README.md +++ b/note/0023/README.md @@ -4,6 +4,18 @@ Merge *k* sorted linked lists and return it as one sorted list. Analyze and describe its complexity. +**Example:** + +``` +Input: +[ + 1->4->5, + 1->3->4, + 2->6 +] +Output: 1->1->2->3->4->4->5->6 +``` + **Tags:** Linked List, Divide and Conquer, Heap diff --git a/note/024/README.md b/note/0024/README.md similarity index 89% rename from note/024/README.md rename to note/0024/README.md index 330f2276..8667b5c1 100644 --- a/note/024/README.md +++ b/note/0024/README.md @@ -4,10 +4,16 @@ 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`. +**Example:** -Your algorithm should use only constant space. You may **not** modify the values in the list, only nodes itself can be changed. +``` +Given 1->2->3->4, you should return the list as 2->1->4->3. +``` + +**Note:** + +- Your algorithm should use only constant extra space. +- You may **not** modify the values in the list's nodes, only nodes itself may be changed. **Tags:** Linked List diff --git a/note/025/README.md b/note/0025/README.md similarity index 94% rename from note/025/README.md rename to note/0025/README.md index 7bdeeab7..fd042a9e 100644 --- a/note/025/README.md +++ b/note/0025/README.md @@ -6,11 +6,8 @@ Given a linked list, reverse the nodes of a linked list *k* at a time and return *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, +**Example:** Given this linked list: `1->2->3->4->5` @@ -18,6 +15,11 @@ For *k* = 2, you should return: `2->1->4->3->5` For *k* = 3, you should return: `3->2->1->4->5` +**Note:** + +- Only constant extra memory is allowed. +- You may not alter the values in the list's nodes, only nodes itself may be changed. + **Tags:** Linked List diff --git a/note/026/README.md b/note/0026/README.md similarity index 51% rename from note/026/README.md rename to note/0026/README.md index 53daaf2a..58340c4b 100644 --- a/note/026/README.md +++ b/note/0026/README.md @@ -2,17 +2,47 @@ ## Description -Given a sorted array, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each element appear only *once* and return the new length. +Given a sorted array *nums*, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each element appear only *once* 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. +Do not allocate extra space for another array, you must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. -**Example:** +**Example 1:** ``` Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. -It doesn't matter what you leave beyond the new length. + +It doesn't matter what you leave beyond the returned length. +``` + +**Example 2:** + +``` +Given nums = [0,0,1,1,1,2,2,3,3,4], + +Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. + +It doesn't matter what values are set beyond the returned length. +``` + +**Clarification:** + +Confused why the returned value is an integer but your answer is an array? + +Note that the input array is passed in by **reference**, which means modification to the input array will be known to the caller as well. + +Internally you can think of this: + +``` +// nums is passed in by reference. (i.e., without making a copy) +int len = removeDuplicates(nums); + +// any modification to nums in your function would be known by the caller. +// using the length returned by your function, it prints the first len elements. +for (int i = 0; i < len; i++) { + print(nums[i]); +} ``` **Tags:** Array, Two Pointers diff --git a/note/027/README.md b/note/0027/README.md similarity index 52% rename from note/027/README.md rename to note/0027/README.md index f17349af..4cfd4983 100644 --- a/note/027/README.md +++ b/note/0027/README.md @@ -2,18 +2,51 @@ ## Description -Given an array and a value, remove all instances of that value [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) and return the new length. +Given an array *nums* and a value *val*, remove all instances of that value [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) and return the new length. -Do not allocate extra space for another array, you must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. +Do not allocate extra space for another array, you must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) ** with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. -**Example:** +**Example 1:** ``` Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. + +It doesn't matter what you leave beyond the returned length. +``` + +**Example 2:** + +``` +Given nums = [0,1,2,2,3,0,4,2], val = 2, + +Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. + +Note that the order of those five elements can be arbitrary. + +It doesn't matter what values are set beyond the returned length. +``` + +**Clarification:** + +Confused why the returned value is an integer but your answer is an array? + +Note that the input array is passed in by **reference**, which means modification to the input array will be known to the caller as well. + +Internally you can think of this: + +``` +// nums is passed in by reference. (i.e., without making a copy) +int len = removeElement(nums, val); + +// any modification to nums in your function would be known by the caller. +// using the length returned by your function, it prints the first len elements. +for (int i = 0; i < len; i++) { + print(nums[i]); +} ``` **Tags:** Array, Two Pointers diff --git a/note/028/README.md b/note/0028/README.md similarity index 69% rename from note/028/README.md rename to note/0028/README.md index 8cfa67bc..7ee16a3d 100644 --- a/note/028/README.md +++ b/note/0028/README.md @@ -20,12 +20,18 @@ Input: haystack = "aaaaa", needle = "bba" Output: -1 ``` +**Clarification:** + +What should we return when `needle` is an empty string? This is a great question to ask during an interview. + +For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's [strstr()](http://www.cplusplus.com/reference/cstring/strstr/) and Java's [indexOf()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)). + Tags:** Two Pointers, String ## 思路 -题意是从主串中找到子串的索引,如果找不到则返回-1,当字串长度大于主串,直接返回-1,然后我们只需要遍历比较即可。 +题意是从主串中找到子串的索引,如果找不到则返回-1,当子串长度大于主串,直接返回-1,然后我们只需要遍历比较即可。 ```java class Solution { @@ -33,9 +39,9 @@ class Solution { int l1 = haystack.length(), l2 = needle.length(); if (l1 < l2) return -1; for (int i = 0; ; i++) { + if (i + l2 > l1) return -1; for (int j = 0; ; j++) { if (j == l2) return i; - if (i + j == l1) return -1; if (haystack.charAt(i + j) != needle.charAt(j)) break; } } diff --git a/note/029/README.md b/note/0029/README.md similarity index 77% rename from note/029/README.md rename to note/0029/README.md index d402cd0d..6018b268 100644 --- a/note/029/README.md +++ b/note/0029/README.md @@ -2,9 +2,31 @@ ## Description -Divide two integers without using multiplication, division and mod operator. +Given two integers `dividend` and `divisor`, divide two integers without using multiplication, division and mod operator. -If it is overflow, return MAX_INT. +Return the quotient after dividing `dividend` by `divisor`. + +The integer division should truncate toward zero. + +**Example 1:** + +``` +Input: dividend = 10, divisor = 3 +Output: 3 +``` + +**Example 2:** + +``` +Input: dividend = 7, divisor = -3 +Output: -2 +``` + +**Note:** + +- Both dividend and divisor will be 32-bit signed integers. +- The divisor will never be 0. +- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows. **Tags:** Math, Binary Search diff --git a/note/0030/README.md b/note/0030/README.md new file mode 100644 index 00000000..52e7677d --- /dev/null +++ b/note/0030/README.md @@ -0,0 +1,99 @@ +# [Substring with Concatenation of All Words][title] + +## Description + +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. + +**Example 1:** + +``` +Input: + s = "barfoothefoobarman", + words = ["foo","bar"] +Output: [0,9] +Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively. +The output order does not matter, returning [9,0] is fine too. +``` + +**Example 2:** + +``` +Input: + s = "wordgoodgoodgoodbestword", + words = ["word","good","best","word"] +Output: [] +``` + +**Tags:** Hash Table, Two Pointers, String + + +## 思路 + +题意是给一个字符串 `s` 和等长度的单词数组 `words`,我们要找到的就是在 `s` 串中由所有单词组成的子串的索引(不要求顺序),不明白的话看下例子也就理解了,比如例子 1 的结果 [0, 9]:[`barfoo`,`foobar`] 就是符合的子串。 + +我们把 `words` 每个单词出现的次数都存入到一个 `map` 中,然后遍历 `s` 串,依次截取单词长度的子串做比较,如果都符合那就加入结果,如果不符合,我们要把和它相关联的不符合的都剔除掉,这样在之后的遍历就可以跳过该位置从而达到优化的目的。 + +```java +public class Solution { + public List findSubstring(String s, String[] words) { + if (s == null) return Collections.emptyList(); + int len = s.length(); + if (len == 0) return Collections.emptyList(); + int wordsSize = words.length; + if (wordsSize == 0) return Collections.emptyList(); + int wordLen = words[0].length(), end = len - wordsSize * wordLen; + if (end < 0) return Collections.emptyList(); + Map countMap = new HashMap<>(); + for (String word : words) { + countMap.put(word, countMap.getOrDefault(word, 0) + 1); + } + List res = new ArrayList<>(); + Set ignores = new HashSet<>(); + for (int i = 0; i <= end; ++i) { + if (ignores.contains(i)) continue; + Map findMap = new HashMap<>(); + int st = i, count = 0; + List ignore = new ArrayList<>(); + for (int j = 0; ; ++j) { + int cur = i + j * wordLen; + if (cur + wordLen > len) break; + String word = s.substring(cur, cur + wordLen); + if (countMap.containsKey(word)) { + findMap.put(word, findMap.getOrDefault(word, 0) + 1); + ++count; + while (findMap.get(word) > countMap.get(word)) { + ignore.add(st); + String tmp = s.substring(st, st += wordLen); + findMap.put(tmp, findMap.get(tmp) - 1); + --count; + } + if (count == wordsSize) { + ignore.add(st); + res.add(st); + String tmp = s.substring(st, st += wordLen); + findMap.put(tmp, findMap.get(tmp) - 1); + --count; + } + } else { + for (int k = i; k <= cur; k += wordLen) { + ignore.add(k); + } + break; + } + } + ignores.addAll(ignore); + } + return res; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/substring-with-concatenation-of-all-words +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0031/README.md b/note/0031/README.md new file mode 100644 index 00000000..f85d5f3c --- /dev/null +++ b/note/0031/README.md @@ -0,0 +1,36 @@ +# [Next Permutation][title] + +## Description + +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** and use only constant 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` + +**Tags:** Array + + +## 思路 + +题意是 + +```java + +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/next-permutation +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/033/README.md b/note/0033/README.md similarity index 84% rename from note/033/README.md rename to note/0033/README.md index 821640f7..f096a1aa 100644 --- a/note/033/README.md +++ b/note/0033/README.md @@ -4,12 +4,28 @@ 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`). +(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 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. +Your algorithm's runtime complexity must be in the order of *O*(log *n*). + +**Example 1:** + +``` +Input: nums = [4,5,6,7,0,1,2], target = 0 +Output: 4 +``` + +**Example 2:** + +``` +Input: nums = [4,5,6,7,0,1,2], target = 3 +Output: -1 +``` + **Tags:** Arrays, Binary Search diff --git a/note/035/README.md b/note/0035/README.md similarity index 100% rename from note/035/README.md rename to note/0035/README.md diff --git a/note/038/README.md b/note/0038/README.md similarity index 100% rename from note/038/README.md rename to note/0038/README.md diff --git a/note/043/README.md b/note/0043/README.md similarity index 65% rename from note/043/README.md rename to note/0043/README.md index 48b955f1..2f40b99b 100644 --- a/note/043/README.md +++ b/note/0043/README.md @@ -2,17 +2,28 @@ ## Description -Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`. +1. Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. -**Note:** + **Example 1:** -1. The length of both `num1` and `num2` is < 110. + ``` + Input: num1 = "2", num2 = "3" + Output: "6" + ``` -2. Both `num1` and `num2` contains only digits `0-9`. + **Example 2:** -3. Both `num1` and `num2` does not contain any leading zero. + ``` + Input: num1 = "123", num2 = "456" + Output: "56088" + ``` -4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly. + **Note:** + + 1. The length of both `num1` and `num2` is < 110. + 2. Both `num1` and `num2` contain only digits `0-9`. + 3. Both `num1` and `num2` do not contain any leading zero, except the number 0 itself. + 4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly. **Tags:** Math, String @@ -35,12 +46,12 @@ class Solution { ans[i + j + 1] += c * (c2[j] - '0'); } } - for (int i = l - 1; i > 0; ++i) { + for (int i = l - 1; i > 0; --i) { if (ans[i] > 9) { ans[i - 1] += ans[i] / 10; - ans[i] %= 10; + ans[i] %= 10; } - } + } StringBuilder sb = new StringBuilder(); int i = 0; for (; ; ++i) if (ans[i] != 0) break; diff --git a/note/044/README.md b/note/0044/README.md similarity index 77% rename from note/044/README.md rename to note/0044/README.md index 2798d17f..34f7ae0f 100644 --- a/note/044/README.md +++ b/note/0044/README.md @@ -2,25 +2,67 @@ ## Description -Implement wildcard pattern matching with support for `'?'` and `'*'`. +Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'`. ``` '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). +``` + +The matching should cover the **entire** input string (not partial). + +**Note:** + +- `s` could be empty and contains only lowercase letters `a-z`. +- `p` could be empty and contains only lowercase letters `a-z`, and characters like `?` or `*`. + +**Example 1:** + +``` +Input: +s = "aa" +p = "a" +Output: false +Explanation: "a" does not match the entire string "aa". +``` + +**Example 2:** + +``` +Input: +s = "aa" +p = "*" +Output: true +Explanation: '*' matches any sequence. +``` + +**Example 3:** + +``` +Input: +s = "cb" +p = "?a" +Output: false +Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. +``` -The matching should cover the entire input string (not partial). +**Example 4:** -The function prototype should be: -bool isMatch(const char *s, const char *p) +``` +Input: +s = "adceb" +p = "*a*b" +Output: true +Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". +``` -Some examples: -isMatch("aa","a") → false -isMatch("aa","aa") → true -isMatch("aaa","aa") → false -isMatch("aa", "*") → true -isMatch("aa", "a*") → true -isMatch("ab", "?*") → true -isMatch("aab", "c*a*b") → false +**Example 5:** + +``` +Input: +s = "acdcb" +p = "a*c?b" +Output: false ``` **Tags:** String, Dynamic Programming, Backtracking, Greedy diff --git a/note/049/README.md b/note/0049/README.md similarity index 89% rename from note/049/README.md rename to note/0049/README.md index cc2ebbaa..9832535a 100644 --- a/note/049/README.md +++ b/note/0049/README.md @@ -4,19 +4,22 @@ Given an array of strings, group anagrams together. -For example, given: `["eat", "tea", "tan", "ate", "nat", "bat"]`, - -Return: +**Example:** ``` +Input: ["eat", "tea", "tan", "ate", "nat", "bat"], +Output: [ - ["ate", "eat","tea"], + ["ate","eat","tea"], ["nat","tan"], ["bat"] ] ``` -**Note:** All inputs will be in lower-case. +**Note:** + +- All inputs will be in lowercase. +- The order of your output does not matter. **Tags:** Hash Table, String diff --git a/note/050/README.md b/note/0050/README.md similarity index 78% rename from note/050/README.md rename to note/0050/README.md index a4140f5c..84c125fe 100644 --- a/note/050/README.md +++ b/note/0050/README.md @@ -2,7 +2,7 @@ ## Description -Implement [pow(*x*, *n*)](http://www.cplusplus.com/reference/valarray/pow/). +Implement [pow(*x*, *n*)](http://www.cplusplus.com/reference/valarray/pow/), which calculates *x* raised to the power *n* (xn). **Example 1:** @@ -18,6 +18,19 @@ Input: 2.10000, 3 Output: 9.26100 ``` +**Example 3:** + +``` +Input: 2.00000, -2 +Output: 0.25000 +Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 +``` + +**Note:** + +- -100.0 < *x* < 100.0 +- *n* is a 32-bit signed integer, within the range [−231, 231 − 1] + **Tags:** Math, Binary Search diff --git a/note/053/README.md b/note/0053/README.md similarity index 90% rename from note/053/README.md rename to note/0053/README.md index 816a3d93..43cf6f50 100644 --- a/note/053/README.md +++ b/note/0053/README.md @@ -2,13 +2,17 @@ ## Description -Find the contiguous subarray within an array (containing at least one number) which has the largest sum. +Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. -For example, given the array `[-2,1,-3,4,-1,2,1,-5,4]`, +**Example:** -the contiguous subarray `[4,-1,2,1]` has the largest sum = `6`. +``` +Input: [-2,1,-3,4,-1,2,1,-5,4], +Output: 6 +Explanation: [4,-1,2,1] has the largest sum = 6. +``` -**More practice:** +**Follow up:** If you have figured out the O(*n*) solution, try coding another solution using the divide and conquer approach, which is more subtle. diff --git a/note/056/README.md b/note/0056/README.md similarity index 86% rename from note/056/README.md rename to note/0056/README.md index 70d8e5bd..48621d1a 100644 --- a/note/056/README.md +++ b/note/0056/README.md @@ -4,11 +4,21 @@ Given a collection of intervals, merge all overlapping intervals. -For example, +**Example 1:** -Given `[1,3],[2,6],[8,10],[15,18]`, +``` +Input: [[1,3],[2,6],[8,10],[15,18]] +Output: [[1,6],[8,10],[15,18]] +Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. +``` + +**Example 2:** -return `[1,6],[8,10],[15,18]`. +``` +Input: [[1,4],[4,5]] +Output: [[1,5]] +Explanation: Intervals [1,4] and [4,5] are considerred overlapping. +``` **Tags:** Array, Sort diff --git a/note/057/README.md b/note/0057/README.md similarity index 88% rename from note/057/README.md rename to note/0057/README.md index fcf217cd..f9b82a84 100644 --- a/note/057/README.md +++ b/note/0057/README.md @@ -8,13 +8,18 @@ You may assume that the intervals were initially sorted according to their start **Example 1:** -Given intervals `[1,3],[6,9]`, insert and merge `[2,5]` in as `[1,5],[6,9]`. +``` +Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +Output: [[1,5],[6,9]] +``` **Example 2:** -Given `[1,2],[3,5],[6,7],[8,10],[12,16]`, insert and merge `[4,9]` in as `[1,2],[3,10],[12,16]`. - -This is because the new interval `[4,9]` overlaps with `[3,5],[6,7],[8,10]`. +``` +Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] +Output: [[1,2],[3,10],[12,16]] +Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. +``` **Tags:** Array, Sort diff --git a/note/058/README.md b/note/0058/README.md similarity index 100% rename from note/058/README.md rename to note/0058/README.md diff --git a/note/0063/README.md b/note/0063/README.md new file mode 100644 index 00000000..2905be6f --- /dev/null +++ b/note/0063/README.md @@ -0,0 +1,86 @@ +# [不同路径 II(Unique Paths II)][title] + +## 题目描述 + +一个机器人位于一个 _m x n_ 网格的左上角 (起始点在下图中标记为“Start” )。 + +机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 + +现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? + +![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/robot_maze.png) + +网格中的障碍物和空位置分别用 `1` 和 `0` 来表示。 + +**说明:**_m_ 和 _n_ 的值均不超过 100。 + +**示例 1:** +``` +输入: +[ +  [0,0,0], +  [0,1,0], +  [0,0,0] +] +输出: 2 +解释: +3x3 网格的正中间有一个障碍物。 +从左上角到右下角一共有 2 条不同的路径: +1. 向右 -> 向右 -> 向下 -> 向下 +2. 向下 -> 向下 -> 向右 -> 向右 +``` + +**标签:** 数组、动态规划 + + +## 思路 + +做过爬楼梯的应该很快就能想到这是一道很典型的动态规划题目, + +我们令 `dp[i][j]` 表示走到格子 `(i, j)` 的路径数, + +那么当 `(i, j)` 没障碍物时,`dp[i][j] = 0`; + +那么当 `(i, j)` 有障碍物时,`dp[i][j] = dp[i - 1][j] + dp[i][j - 1]`; + +其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法,因此初始化 `dp[i][0]`(`dp[0][j]`)值为 1,且遇到障碍物时后面值都为 0; + +有了这些条件,我相信你肯定可以写出代码来了,具体如下所示: + + +```java +class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + int m = obstacleGrid.length, n = obstacleGrid[0].length; + int[][] dp = new int[m][n]; + // 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法, + // 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0; + for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) { + dp[i][0] = 1; + } + for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) { + dp[0][j] = 1; + } + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (obstacleGrid[i][j] == 0) { + // 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + } + return dp[m - 1][n - 1]; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode-cn.com/problems/unique-paths-ii +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/066/README.md b/note/0066/README.md similarity index 72% rename from note/066/README.md rename to note/0066/README.md index aaacdb4f..03b2ddda 100644 --- a/note/066/README.md +++ b/note/0066/README.md @@ -2,11 +2,27 @@ ## Description -Given a non-negative integer represented as a **non-empty** array of digits, plus one to the integer. +Given a **non-empty** array of digits representing a non-negative integer, plus one to the integer. -You may assume the integer do not contain any leading zero, except the number 0 itself. +The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. -The digits are stored such that the most significant digit is at the head of the list. +You may assume the integer does not contain any leading zero, except the number 0 itself. + +**Example 1:** + +``` +Input: [1,2,3] +Output: [1,2,4] +Explanation: The array represents the integer 123. +``` + +**Example 2:** + +``` +Input: [4,3,2,1] +Output: [4,3,2,2] +Explanation: The array represents the integer 4321. +``` **Tags:** Array, Math diff --git a/note/067/README.md b/note/0067/README.md similarity index 77% rename from note/067/README.md rename to note/0067/README.md index 28bcab99..e000dd25 100644 --- a/note/067/README.md +++ b/note/0067/README.md @@ -4,13 +4,21 @@ Given two binary strings, return their sum (also a binary string). -For example, +The input strings are both **non-empty** and contains only characters `1` or `0`. -a = `"11"` +**Example 1:** -b = `"1"` +``` +Input: a = "11", b = "1" +Output: "100" +``` + +**Example 2:** -Return `"100"`. +``` +Input: a = "1010", b = "1011" +Output: "10101" +``` **Tags:** Math, String @@ -25,18 +33,18 @@ class Solution { StringBuilder sb = new StringBuilder(); int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1; while (p1 >= 0 && p2 >= 0) { - carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0; - carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0; + carry += a.charAt(p1--) - '0'; + carry += b.charAt(p2--) - '0'; sb.insert(0, (char) (carry % 2 + '0')); carry >>= 1; } while (p1 >= 0) { - carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0; + carry += a.charAt(p1--) - '0'; sb.insert(0, (char) (carry % 2 + '0')); carry >>= 1; } while (p2 >= 0) { - carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0; + carry += b.charAt(p2--) - '0'; sb.insert(0, (char) (carry % 2 + '0')); carry >>= 1; } diff --git a/note/068/README.md b/note/0068/README.md similarity index 68% rename from note/068/README.md rename to note/0068/README.md index 70aa778a..0d3d6f91 100644 --- a/note/068/README.md +++ b/note/0068/README.md @@ -2,38 +2,68 @@ ## Description -Given an array of words and a length *L*, format the text such that each line has exactly *L* characters and is fully (left and right) justified. +Given an array of words and a width *maxWidth*, format the text such that each line has exactly *maxWidth* characters and is fully (left and right) justified. -You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly *L* characters. +You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly *maxWidth* characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. -For the last line of text, it should be left justified and no extra space is inserted between words. +For the last line of text, it should be left justified and no **extra** space is inserted between words. -For example, +**Note:** -**words**: `["This", "is", "an", "example", "of", "text", "justification."]` +- A word is defined as a character sequence consisting of non-space characters only. +- Each word's length is guaranteed to be greater than 0 and not exceed *maxWidth*. +- The input array `words` contains at least one word. -**L**: `16`. - -Return the formatted lines as: +**Example 1:** ``` +Input: +words = ["This", "is", "an", "example", "of", "text", "justification."] +maxWidth = 16 +Output: [ "This is an", "example of text", "justification. " ] - ``` -**Note:** Each word is guaranteed not to exceed *L* in length. +**Example 2:** -**Corner Cases:** +``` +Input: +words = ["What","must","be","acknowledgment","shall","be"] +maxWidth = 16 +Output: +[ + "What must be", + "acknowledgment ", + "shall be " +] +Explanation: Note that the last line is "shall be " instead of "shall be", + because the last line must be left-justified instead of fully-justified. + Note that the second line is also left-justified becase it contains only one word. +``` -- A line other than the last line might contain only one word. What should you do in this case? +**Example 3:** - In this case, that line should be left-justified. +``` +Input: +words = ["Science","is","what","we","understand","well","enough","to","explain", + "to","a","computer.","Art","is","everything","else","we","do"] +maxWidth = 20 +Output: +[ + "Science is what we", + "understand well", + "enough to explain to", + "a computer. Art is", + "everything else we", + "do " +] +``` **Tags:** String diff --git a/note/069/README.md b/note/0069/README.md similarity index 72% rename from note/069/README.md rename to note/0069/README.md index 7b686258..6497b335 100644 --- a/note/069/README.md +++ b/note/0069/README.md @@ -4,9 +4,9 @@ Implement `int sqrt(int x)`. -Compute and return the square root of *x*. +Compute and return the square root of *x*, where *x* is guaranteed to be a non-negative integer. -**x** is guaranteed to be a non-negative integer. +Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. **Example 1:** @@ -20,7 +20,8 @@ Output: 2 ``` Input: 8 Output: 2 -Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated. +Explanation: The square root of 8 is 2.82842..., and since + the decimal part is truncated, 2 is returned. ``` **Tags:** Binary Search, Math diff --git a/note/070/README.md b/note/0070/README.md similarity index 90% rename from note/070/README.md rename to note/0070/README.md index 30f8bcef..193e12e0 100644 --- a/note/070/README.md +++ b/note/0070/README.md @@ -12,9 +12,8 @@ Each time you can either climb 1 or 2 steps. In how many distinct ways can you c ``` Input: 2 -Output: 2 -Explanation: There are two ways to climb to the top. - +Output: 2 +Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps ``` @@ -23,9 +22,8 @@ Explanation: There are two ways to climb to the top. ``` Input: 3 -Output: 3 -Explanation: There are three ways to climb to the top. - +Output: 3 +Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step diff --git a/note/083/README.md b/note/0083/README.md similarity index 91% rename from note/083/README.md rename to note/0083/README.md index 305b3fa7..ebc155ab 100644 --- a/note/083/README.md +++ b/note/0083/README.md @@ -4,11 +4,19 @@ Given a sorted linked list, delete all duplicates such that each element appear only *once*. -For example, +**Example 1:** -Given `1->1->2`, return `1->2`. +``` +Input: 1->1->2 +Output: 1->2 +``` + +**Example 2:** -Given `1->1->2->3->3`, return `1->2->3`. +``` +Input: 1->1->2->3->3 +Output: 1->2->3 +``` **Tags:** Linked List diff --git a/note/088/README.md b/note/0088/README.md similarity index 79% rename from note/088/README.md rename to note/0088/README.md index 44708357..ba64df12 100644 --- a/note/088/README.md +++ b/note/0088/README.md @@ -6,7 +6,18 @@ Given two sorted integer arrays *nums1* and *nums2*, merge *nums2* into *nums1* **Note:** -You may assume that *nums1* has enough space (size that is greater or equal to *m* + *n*) to hold additional elements from *nums2*. The number of elements initialized in *nums1* and *nums2* are *m* and *n* respectively. +- The number of elements initialized in *nums1* and *nums2* are *m* and *n* respectively. +- You may assume that *nums1* has enough space (size that is greater or equal to *m* + *n*) to hold additional elements from *nums2*. + +**Example:** + +``` +Input: +nums1 = [1,2,3,0,0,0], m = 3 +nums2 = [2,5,6], n = 3 + +Output: [1,2,2,3,5,6] +``` **Tags:** Array, Two Pointers diff --git a/note/100/README.md b/note/0100/README.md similarity index 100% rename from note/100/README.md rename to note/0100/README.md diff --git a/note/101/README.md b/note/0101/README.md similarity index 100% rename from note/101/README.md rename to note/0101/README.md diff --git a/note/104/README.md b/note/0104/README.md similarity index 85% rename from note/104/README.md rename to note/0104/README.md index 676c55cc..f1545304 100644 --- a/note/104/README.md +++ b/note/0104/README.md @@ -6,6 +6,22 @@ Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. +**Note:** A leaf is a node with no children. + +**Example:** + +Given binary tree `[3,9,20,null,null,15,7]`, + +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` + +return its depth = 3. + **Tags:** Tree, Depth-first Search diff --git a/note/107/README.md b/note/0107/README.md similarity index 100% rename from note/107/README.md rename to note/0107/README.md diff --git a/note/108/README.md b/note/0108/README.md similarity index 100% rename from note/108/README.md rename to note/0108/README.md diff --git a/note/110/README.md b/note/0110/README.md similarity index 75% rename from note/110/README.md rename to note/0110/README.md index 70c9d8c0..823ea493 100644 --- a/note/110/README.md +++ b/note/0110/README.md @@ -4,7 +4,38 @@ Given a binary tree, determine if it is height-balanced. -For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. +For this problem, a height-balanced binary tree is defined as: + +> a binary tree in which the depth of the two subtrees of *every* node never differ by more than 1. + +**Example 1:** + +Given the following tree `[3,9,20,null,null,15,7]`: + +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` + +Return true. +**Example 2:** + +Given the following tree `[1,2,2,3,3,null,null,4,4]`: + +``` + 1 + / \ + 2 2 + / \ + 3 3 + / \ + 4 4 +``` + +Return false. **Tags:** Tree, Depth-first Search diff --git a/note/111/README.md b/note/0111/README.md similarity index 92% rename from note/111/README.md rename to note/0111/README.md index f6ea8cdf..5c4e2b8a 100644 --- a/note/111/README.md +++ b/note/0111/README.md @@ -6,6 +6,22 @@ Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. +**Note:** A leaf is a node with no children. + +**Example:** + +Given binary tree `[3,9,20,null,null,15,7]`, + +``` + 3 + / \ + 9 20 + / \ + 15 7 +``` + +return its minimum depth = 2. + **Tags:** Tree, Depth-first Search, Breadth-first Search diff --git a/note/112/README.md b/note/0112/README.md similarity index 89% rename from note/112/README.md rename to note/0112/README.md index abf1975c..a287dd09 100644 --- a/note/112/README.md +++ b/note/0112/README.md @@ -4,18 +4,20 @@ Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. -For example: +**Note:** A leaf is a node with no children. + +**Example:** Given the below binary tree and `sum = 22`, ``` - 5 - / \ - 4 8 - / / \ - 11 13 4 - / \ \ - 7 2 1 + 5 + / \ + 4 8 + / / \ + 11 13 4 + / \ \ +7 2 1 ``` return true, as there exist a root-to-leaf path `5->4->11->2` which sum is 22. diff --git a/note/118/README.md b/note/0118/README.md similarity index 79% rename from note/118/README.md rename to note/0118/README.md index dd1a60b6..6e268aa3 100644 --- a/note/118/README.md +++ b/note/0118/README.md @@ -2,13 +2,16 @@ ## Description -Given *numRows*, generate the first *numRows* of Pascal's triangle. +Given a non-negative integer *numRows*, generate the first *numRows* of Pascal's triangle. -For example, given *numRows* = 5, +![img](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) +In Pascal's triangle, each number is the sum of the two numbers directly above it. -Return +**Example:** ``` +Input: 5 +Output: [ [1], [1,1], diff --git a/note/119/README.md b/note/0119/README.md similarity index 69% rename from note/119/README.md rename to note/0119/README.md index 7967f72c..65b792e5 100644 --- a/note/119/README.md +++ b/note/0119/README.md @@ -2,13 +2,21 @@ ## Description -Given an index *k*, return the *k*th row of the Pascal's triangle. +Given a non-negative index *k* where *k* ≤ 33, return the *k*th index row of the Pascal's triangle. -For example, given *k* = 3, +Note that the row index starts from 0. -Return `[1,3,3,1]`. +![img](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) +In Pascal's triangle, each number is the sum of the two numbers directly above it. -**Note:** +**Example:** + +``` +Input: 3 +Output: [1,3,3,1] +``` + +**Follow up:** Could you optimize your algorithm to use only *O*(*k*) extra space? diff --git a/note/121/README.md b/note/0121/README.md similarity index 74% rename from note/121/README.md rename to note/0121/README.md index 648606f5..5699ece1 100644 --- a/note/121/README.md +++ b/note/0121/README.md @@ -4,24 +4,25 @@ Say you have an array for which the *i*th element is the price of a given stock on day *i*. -If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. +If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. + +Note that you cannot sell a stock before you buy one. **Example 1:** ``` -Input: [7, 1, 5, 3, 6, 4] +Input: [7,1,5,3,6,4] Output: 5 - -max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + Not 7-1 = 6, as selling price needs to be larger than buying price. ``` **Example 2:** ``` -Input: [7, 6, 4, 3, 1] +Input: [7,6,4,3,1] Output: 0 - -In this case, no transaction is done, i.e. max profit = 0. +Explanation: In this case, no transaction is done, i.e. max profit = 0. ``` **Tags:** Array, Dynamic Programmin diff --git a/note/122/README.md b/note/0122/README.md similarity index 52% rename from note/122/README.md rename to note/0122/README.md index b1c18ed6..a4a3aaa9 100644 --- a/note/122/README.md +++ b/note/0122/README.md @@ -4,7 +4,36 @@ Say you have an array for which the *i*th element is the price of a given stock on day *i*. -Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). +Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). + +**Note:** You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). + +**Example 1:** + +``` +Input: [7,1,5,3,6,4] +Output: 7 +Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. + Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. +``` + +**Example 2:** + +``` +Input: [1,2,3,4,5] +Output: 4 +Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. + Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are + engaging multiple transactions at the same time. You must sell before buying again. +``` + +**Example 3:** + +``` +Input: [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transaction is done, i.e. max profit = 0. +``` **Tags:** Array, Greedy diff --git a/note/0209/README.md b/note/0209/README.md new file mode 100644 index 00000000..e0984de9 --- /dev/null +++ b/note/0209/README.md @@ -0,0 +1,107 @@ +# [长度最小的子数组][title] + +## 题目描述 + +给定一个含有 **n** 个正整数的数组和一个正整数 **s** ,找出该数组中满足其和 **≥ s** 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 + +**示例:** + +``` +输入:s = 7, nums = [2,3,1,2,4,3] +输出:2 +解释:子数组 [4,3] 是该条件下的长度最小的连续子数组。 +``` + +**进阶:** + +* 如果你已经完成了 _O_(_n_) 时间复杂度的解法, 请尝试 _O_(_n_ log _n_) 时间复杂度的解法。 + +**标签:** 数组、双指针、二分查找 + + +## 思路 0 + +直接暴力法,两重 for 循环,记录最小长度即可,代码很简单,如下所示: + + +```java +class Solution { + public int minSubArrayLen(int s, int[] nums) { + int ans = Integer.MAX_VALUE; + for (int i = 0; i < nums.length; i++) { + int sum = nums[i]; + if (sum >= s) { + return 1; + } + for (int j = i + 1; j < nums.length; j++) { + sum += nums[j]; + if (sum >= s) { + ans = Math.min(ans, j - i + 1); + break; + } + } + } + return ans == Integer.MAX_VALUE ? 0 : ans; + } +} +``` + +## 思路 1 + +对上面进行优化,我们通过首位两个指针来模拟滑动窗口,如果加起来值小于 s,则向右扩大窗口直至不小于 s,然后固定窗口右侧来向左缩小窗口,同时更新符合条件的最小窗口长度即可,代码如下所示: + +```java +class Solution { + public int minSubArrayLen(int s, int[] nums) { + int left = 0, right = 0, sum = 0, ans = Integer.MAX_VALUE; + while (right < nums.length) { + sum += nums[right++]; // 向右扩大窗口 + while (sum >= s) { // 如果不小于 s,则收缩窗口左边界 + ans = Math.min(ans, right - left);// 更新结果 + sum -= nums[left++]; // 向左缩小窗口 + } + } + return ans == Integer.MAX_VALUE ? 0 : ans; + } +} +``` + +## 思路 2 + +进阶中说了,尝试使用 O(nlogn) 时间复杂度的解法,由于数组都是正整数构成,所以前缀和一定是递增的,想到的应该就是用二分查找了,可以用 sums 数组来存储 nums 数组的前缀和,sums[i] 代表 nums[0] 到 nums[i - 1] 总和,然后遍历 sums 数组,对 sums[i] + s 进行二分查找然后不断更新结果即可,具体代码如下所示: + + +```java +class Solution { + public int minSubArrayLen(int s, int[] nums) { + int ans = Integer.MAX_VALUE; + int[] sums = new int[nums.length + 1]; + for (int i = 0; i < nums.length; i++) { + sums[i + 1] = sums[i] + nums[i]; + } + for (int i = 0; i < nums.length; i++) { + int target = s + sums[i]; // 确定要搜索的目标值 + // Java 二分查找 Arrays.binarySearch 如果找到就会返回该元素的索引; + // 如果没找到就会返回一个负数,这个负数取反之后再减一就是查找的值应该在数组中的位置; + // 例如 [-1, 0, 1, 5] 中二分查找 2,其返回值就是 -4,其 -(-4) - 1 = 3,所以 2 这个元素插入到数组的索引就是 3 + int bound = Arrays.binarySearch(sums, target); + if (bound < 0) { + bound = -bound - 1; + } + if (bound < sums.length) { // 当 bound 确定插入点不在 sums 数组的最后面时,说明不小于 target 的值了 + ans = Math.min(ans, bound - i); + } + } + return ans == Integer.MAX_VALUE ? 0 : ans; + } +} +``` + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode-cn.com/problems/minimum-size-subarray-sum +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/543/README.md b/note/0543/README.md similarity index 98% rename from note/543/README.md rename to note/0543/README.md index 16e0c303..1a28f9ba 100644 --- a/note/543/README.md +++ b/note/0543/README.md @@ -5,8 +5,7 @@ Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the **longest** path between any two nodes in a tree. This path may or may not pass through the root. **Example:** - -Given a binary tree +Given a binary tree ``` 1 @@ -14,7 +13,6 @@ Given a binary tree 2 3 / \ 4 5 - ``` Return **3**, which is the length of the path [4,2,1,3] or [5,2,1,3]. diff --git a/note/554/README.md b/note/0554/README.md similarity index 100% rename from note/554/README.md rename to note/0554/README.md diff --git a/note/1014/README.md b/note/1014/README.md new file mode 100644 index 00000000..fe4a965e --- /dev/null +++ b/note/1014/README.md @@ -0,0 +1,59 @@ +# [最佳观光组合(Best Sightseeing Pair)][title] + +## 题目描述 + +给定正整数数组 `A`,`A[i]` 表示第 `i` 个观光景点的评分,并且两个景点 `i` 和 `j` 之间的距离为 `j - i`。 + +一对景点(`i < j`)组成的观光组合的得分为(`A[i] + A[j] + i - j`):景点的评分之和**减去**它们两者之间的距离。 + +返回一对观光景点能取得的最高分。 + +**示例:** + +``` +输入:[8,1,5,2,6] +输出:11 +解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 +``` + +**提示:** + +1. `2 <= A.length <= 50000` +2. `1 <= A[i] <= 1000` + +**标签:** 数组 + + +## 思路 + +直接暴力两层 for 循环肯定过不了关,我们把公式变化为 `(A[i] + i) + (A[j] - j)`,看到此应该就可以想到在每次遍历 `j` 时,只需要知道 `max(A[i] + i)` 即可。 + +```java +class Solution { + + public int maxScoreSightseeingPair(int[] A) { + int ans = 0, cur = A[0] + 0; + for (int j = 1; j < A.length; j++) { + ans = Math.max(ans, cur + A[j] - j); // 计算当前最大得分 + cur = Math.max(cur, A[j] + j); // 更新最大的 A[i] + i + } + return ans; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] A = new int[]{8, 1, 5, 2, 6}; + System.out.println(solution.maxScoreSightseeingPair(A)); + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode-cn.com/problems/best-sightseeing-pair +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/1028/README.md b/note/1028/README.md new file mode 100644 index 00000000..aaa185ba --- /dev/null +++ b/note/1028/README.md @@ -0,0 +1,148 @@ +# [从先序遍历还原二叉树][title] + +## 题目描述 + +我们从二叉树的根节点 `root` 开始进行深度优先搜索。 + +在遍历中的每个节点处,我们输出 `D` 条短划线(其中 `D` 是该节点的深度),然后输出该节点的值。(_如果节点的深度为 `D`,则其直接子节点的深度为 `D + 1`。根节点的深度为 `0`)。_ + +如果节点只有一个子节点,那么保证该子节点为左子节点。 + +给出遍历输出 `S`,还原树并返回其根节点 `root`。 + +**示例 1:** + +**![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/12/recover-a-tree-from-preorder-traversal.png)** + +``` +输入:"1-2--3--4-5--6--7" +输出:[1,2,5,3,4,6,7] +``` + +**示例 2:** + +**![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/12/screen-shot-2019-04-10-at-114101-pm.png)** + +``` +输入:"1-2--3---4-5--6---7" +输出:[1,2,5,3,null,6,null,4,null,7] +``` + +**示例 3:** + +![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/12/screen-shot-2019-04-10-at-114955-pm.png) + +``` +输入:"1-401--349---90--88" +输出:[1,401,null,349,88,90] +``` + +**提示:** + +* 原始树中的节点数介于 `1` 和 `1000` 之间。 +* 每个节点的值介于 `1` 和 `10 ^ 9` 之间。 + +**标签:** 树、深度优先搜索 + + +## 思路 0 + +主要就是根据先序遍历如何把树构建出来,其最主要就是找到当前待插入节点它爹,优先插入到它爹的左子节点,我们可以用一个链表来做辅助,该链表索引代表层级,元素存放其节点,由于是先序遍历(根-左-右),也就是右覆盖左时,此时左树已遍历完成,故无需考虑覆盖问题,利用该链表,我们根据层级便可轻松找到它爹,具体如下所示: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public TreeNode recoverFromPreorder(String S) { + char[] chars = S.toCharArray(); + int len = chars.length; + List levels = new LinkedList<>(); + for (int i = 0; i < len; ) { + int level = 0, val = 0; + while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢 + ++i; + ++level; + } + while (i < len && chars[i] != '-') { // 获取节点的值 + val = val * 10 + chars[i++] - '0'; + } + TreeNode curNode = new TreeNode(val); + if (level > 0) { + TreeNode parent = levels.get(level - 1); + if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。 + parent.left = curNode; + } else { + parent.right = curNode; + } + } + levels.add(level, curNode); // 因为是先序遍历(根-左-右),也就是右覆盖左时,此时左树已遍历完成,故无需考虑覆盖问题 + } + return levels.get(0); + } +} +``` + + +## 思路 1 + +基于上面的思路,其实我们没有必要把所有层级都保存下来,由于是先序遍历,在找待插入节点它爹时,我们可以把不小于它层级的元素都删除,基于此,用一个辅助栈便可完成寻爹之旅,具体如下所示: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public TreeNode recoverFromPreorder(String S) { + char[] chars = S.toCharArray(); + int len = chars.length; + LinkedList stack = new LinkedList<>(); + for (int i = 0; i < len; ) { + int level = 0, val = 0; + while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢 + ++i; + ++level; + } + while (i < len && chars[i] != '-') { // 获取节点的值 + val = val * 10 + chars[i++] - '0'; + } + TreeNode curNode = new TreeNode(val); + while (stack.size() > level) { // 栈顶不是父亲,栈顶出栈 + stack.removeLast(); + } + if (level > 0) { + TreeNode parent = stack.getLast(); + if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。 + parent.left = curNode; + } else { + parent.right = curNode; + } + } + stack.addLast(curNode); + } + return stack.get(0); + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode-cn.com/problems/recover-a-tree-from-preorder-traversal +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/16_11/README.md b/note/16_11/README.md new file mode 100644 index 00000000..13e6d104 --- /dev/null +++ b/note/16_11/README.md @@ -0,0 +1,68 @@ +# [跳水板(Diving Board LCCI)][title] + +## 题目描述 + +你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为`shorter`,长度较长的木板长度为`longer`。你必须正好使用`k`块木板。编写一个方法,生成跳水板所有可能的长度。 + +返回的长度需要从小到大排列。 + +**示例:** + +``` +输入: +shorter = 1 +longer = 2 +k = 3 +输出: {3,4,5,6} +``` + +**提示:** + +* 0 < shorter <= longer +* 0 <= k <= 100000 + +**标签:** 递归、记忆化 + + +## 思路 + +这题乍一看,好像得用递归或动态规划来解,仔细一想,其实就是高中数学学过的等差数列知识。 + +当 `k == 0` 时,返回 `[]` 即可; + +当 `shorter == longer` 时,返回 `[k * shorter]` 即可; + +当 `shorter != longer` 时,那么其实就是一个首项为 `k * shorter`,末项为 `k * longer`,公差为 `longer - shorter` 的等差数列么; + +我们根据以上情况就可以写出如下代码了: + + +```java +public class Solution { + public int[] divingBoard(int shorter, int longer, int k) { + if (k == 0) { + return new int[0]; + } + if (shorter == longer) { + return new int[]{shorter * k}; + } + int[] ans = new int[k + 1]; + int st = k * shorter;// 等差数列的首项 + int delta = longer - shorter;// 公差 + for (int i = 0; i <= k; i++) { + ans[i] = st + i * delta; + } + return ans; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode-cn.com/problems/diving-board-lcci +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/src/com/blankj/easy/_001/Solution.java b/src/com/blankj/easy/_0001/Solution.java similarity index 89% rename from src/com/blankj/easy/_001/Solution.java rename to src/com/blankj/easy/_0001/Solution.java index ff0af5f4..4b0fb6cb 100644 --- a/src/com/blankj/easy/_001/Solution.java +++ b/src/com/blankj/easy/_0001/Solution.java @@ -27,8 +27,9 @@ public int[] twoSum(int[] nums, int target) { int len = nums.length; HashMap map = new HashMap<>(); for (int i = 0; i < len; ++i) { - if (map.containsKey(nums[i])) { - return new int[]{map.get(nums[i]), i}; + final Integer value = map.get(nums[i]); + if (value != null) { + return new int[] { value, i }; } map.put(target - nums[i], i); } diff --git a/src/com/blankj/easy/_007/Solution.java b/src/com/blankj/easy/_0007/Solution.java similarity index 100% rename from src/com/blankj/easy/_007/Solution.java rename to src/com/blankj/easy/_0007/Solution.java diff --git a/src/com/blankj/easy/_009/Solution.java b/src/com/blankj/easy/_0009/Solution.java similarity index 100% rename from src/com/blankj/easy/_009/Solution.java rename to src/com/blankj/easy/_0009/Solution.java diff --git a/src/com/blankj/easy/_013/Solution.java b/src/com/blankj/easy/_0013/Solution.java similarity index 100% rename from src/com/blankj/easy/_013/Solution.java rename to src/com/blankj/easy/_0013/Solution.java diff --git a/src/com/blankj/easy/_014/Solution.java b/src/com/blankj/easy/_0014/Solution.java similarity index 100% rename from src/com/blankj/easy/_014/Solution.java rename to src/com/blankj/easy/_0014/Solution.java diff --git a/src/com/blankj/easy/_020/Solution.java b/src/com/blankj/easy/_0020/Solution.java similarity index 100% rename from src/com/blankj/easy/_020/Solution.java rename to src/com/blankj/easy/_0020/Solution.java diff --git a/src/com/blankj/easy/_021/Solution.java b/src/com/blankj/easy/_0021/Solution.java similarity index 100% rename from src/com/blankj/easy/_021/Solution.java rename to src/com/blankj/easy/_0021/Solution.java diff --git a/src/com/blankj/easy/_026/Solution.java b/src/com/blankj/easy/_0026/Solution.java similarity index 100% rename from src/com/blankj/easy/_026/Solution.java rename to src/com/blankj/easy/_0026/Solution.java diff --git a/src/com/blankj/easy/_027/Solution.java b/src/com/blankj/easy/_0027/Solution.java similarity index 100% rename from src/com/blankj/easy/_027/Solution.java rename to src/com/blankj/easy/_0027/Solution.java diff --git a/src/com/blankj/easy/_028/Solution.java b/src/com/blankj/easy/_0028/Solution.java similarity index 94% rename from src/com/blankj/easy/_028/Solution.java rename to src/com/blankj/easy/_0028/Solution.java index 25699215..246ba868 100644 --- a/src/com/blankj/easy/_028/Solution.java +++ b/src/com/blankj/easy/_0028/Solution.java @@ -13,9 +13,9 @@ public int strStr(String haystack, String needle) { int l1 = haystack.length(), l2 = needle.length(); if (l1 < l2) return -1; for (int i = 0; ; i++) { + if (i + l2 > l1) return -1; for (int j = 0; ; j++) { if (j == l2) return i; - if (i + j == l1) return -1; if (haystack.charAt(i + j) != needle.charAt(j)) break; } } diff --git a/src/com/blankj/easy/_035/Solution.java b/src/com/blankj/easy/_0035/Solution.java similarity index 100% rename from src/com/blankj/easy/_035/Solution.java rename to src/com/blankj/easy/_0035/Solution.java diff --git a/src/com/blankj/easy/_038/Solution.java b/src/com/blankj/easy/_0038/Solution.java similarity index 100% rename from src/com/blankj/easy/_038/Solution.java rename to src/com/blankj/easy/_0038/Solution.java diff --git a/src/com/blankj/easy/_053/Solution.java b/src/com/blankj/easy/_0053/Solution.java similarity index 100% rename from src/com/blankj/easy/_053/Solution.java rename to src/com/blankj/easy/_0053/Solution.java diff --git a/src/com/blankj/easy/_058/Solution.java b/src/com/blankj/easy/_0058/Solution.java similarity index 100% rename from src/com/blankj/easy/_058/Solution.java rename to src/com/blankj/easy/_0058/Solution.java diff --git a/src/com/blankj/easy/_066/Solution.java b/src/com/blankj/easy/_0066/Solution.java similarity index 100% rename from src/com/blankj/easy/_066/Solution.java rename to src/com/blankj/easy/_0066/Solution.java diff --git a/src/com/blankj/easy/_067/Solution.java b/src/com/blankj/easy/_0067/Solution.java similarity index 94% rename from src/com/blankj/easy/_067/Solution.java rename to src/com/blankj/easy/_0067/Solution.java index 614cdc76..71e953b9 100644 --- a/src/com/blankj/easy/_067/Solution.java +++ b/src/com/blankj/easy/_0067/Solution.java @@ -13,8 +13,8 @@ public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1; while (p1 >= 0 && p2 >= 0) { - carry += a.charAt(p1--); - carry += b.charAt(p2--); + carry += a.charAt(p1--) - '0'; + carry += b.charAt(p2--) - '0'; sb.insert(0, (char) (carry % 2 + '0')); carry >>= 1; } diff --git a/src/com/blankj/easy/_069/Solution.java b/src/com/blankj/easy/_0069/Solution.java similarity index 100% rename from src/com/blankj/easy/_069/Solution.java rename to src/com/blankj/easy/_0069/Solution.java diff --git a/src/com/blankj/easy/_070/Solution.java b/src/com/blankj/easy/_0070/Solution.java similarity index 100% rename from src/com/blankj/easy/_070/Solution.java rename to src/com/blankj/easy/_0070/Solution.java diff --git a/src/com/blankj/easy/_083/Solution.java b/src/com/blankj/easy/_0083/Solution.java similarity index 100% rename from src/com/blankj/easy/_083/Solution.java rename to src/com/blankj/easy/_0083/Solution.java diff --git a/src/com/blankj/easy/_088/Solution.java b/src/com/blankj/easy/_0088/Solution.java similarity index 100% rename from src/com/blankj/easy/_088/Solution.java rename to src/com/blankj/easy/_0088/Solution.java diff --git a/src/com/blankj/easy/_100/Solution.java b/src/com/blankj/easy/_0100/Solution.java similarity index 100% rename from src/com/blankj/easy/_100/Solution.java rename to src/com/blankj/easy/_0100/Solution.java diff --git a/src/com/blankj/easy/_101/Solution.java b/src/com/blankj/easy/_0101/Solution.java similarity index 100% rename from src/com/blankj/easy/_101/Solution.java rename to src/com/blankj/easy/_0101/Solution.java diff --git a/src/com/blankj/easy/_104/Solution.java b/src/com/blankj/easy/_0104/Solution.java similarity index 100% rename from src/com/blankj/easy/_104/Solution.java rename to src/com/blankj/easy/_0104/Solution.java diff --git a/src/com/blankj/easy/_107/Solution.java b/src/com/blankj/easy/_0107/Solution.java similarity index 100% rename from src/com/blankj/easy/_107/Solution.java rename to src/com/blankj/easy/_0107/Solution.java diff --git a/src/com/blankj/easy/_108/Solution.java b/src/com/blankj/easy/_0108/Solution.java similarity index 100% rename from src/com/blankj/easy/_108/Solution.java rename to src/com/blankj/easy/_0108/Solution.java diff --git a/src/com/blankj/easy/_110/Solution.java b/src/com/blankj/easy/_0110/Solution.java similarity index 100% rename from src/com/blankj/easy/_110/Solution.java rename to src/com/blankj/easy/_0110/Solution.java diff --git a/src/com/blankj/easy/_111/Solution.java b/src/com/blankj/easy/_0111/Solution.java similarity index 100% rename from src/com/blankj/easy/_111/Solution.java rename to src/com/blankj/easy/_0111/Solution.java diff --git a/src/com/blankj/easy/_112/Solution.java b/src/com/blankj/easy/_0112/Solution.java similarity index 100% rename from src/com/blankj/easy/_112/Solution.java rename to src/com/blankj/easy/_0112/Solution.java diff --git a/src/com/blankj/easy/_118/Solution.java b/src/com/blankj/easy/_0118/Solution.java similarity index 100% rename from src/com/blankj/easy/_118/Solution.java rename to src/com/blankj/easy/_0118/Solution.java diff --git a/src/com/blankj/easy/_119/Solution.java b/src/com/blankj/easy/_0119/Solution.java similarity index 100% rename from src/com/blankj/easy/_119/Solution.java rename to src/com/blankj/easy/_0119/Solution.java diff --git a/src/com/blankj/easy/_121/Solution.java b/src/com/blankj/easy/_0121/Solution.java similarity index 100% rename from src/com/blankj/easy/_121/Solution.java rename to src/com/blankj/easy/_0121/Solution.java diff --git a/src/com/blankj/easy/_122/Solution.java b/src/com/blankj/easy/_0122/Solution.java similarity index 100% rename from src/com/blankj/easy/_122/Solution.java rename to src/com/blankj/easy/_0122/Solution.java diff --git a/src/com/blankj/easy/_543/Solution.java b/src/com/blankj/easy/_0543/Solution.java similarity index 100% rename from src/com/blankj/easy/_543/Solution.java rename to src/com/blankj/easy/_0543/Solution.java diff --git a/src/com/blankj/easy/_16_11/Solution.java b/src/com/blankj/easy/_16_11/Solution.java new file mode 100644 index 00000000..2e9e7906 --- /dev/null +++ b/src/com/blankj/easy/_16_11/Solution.java @@ -0,0 +1,34 @@ +package com.blankj.easy._16_11; + +import java.util.Arrays; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2020/07/08
+ *     desc  :
+ * 
+ */ +public class Solution { + public int[] divingBoard(int shorter, int longer, int k) { + if (k == 0) { + return new int[0]; + } + if (shorter == longer) { + return new int[]{shorter * k}; + } + int[] ans = new int[k + 1]; + int st = k * shorter;// 等差数列的首项 + int delta = longer - shorter;// 公差 + for (int i = 0; i <= k; i++) { + ans[i] = st + i * delta; + } + return ans; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(Arrays.toString(solution.divingBoard(1, 2, 3))); + } +} diff --git a/src/com/blankj/hard/_004/Solution.java b/src/com/blankj/hard/_0004/Solution.java similarity index 100% rename from src/com/blankj/hard/_004/Solution.java rename to src/com/blankj/hard/_0004/Solution.java diff --git a/src/com/blankj/hard/_010/Solution.java b/src/com/blankj/hard/_0010/Solution.java similarity index 100% rename from src/com/blankj/hard/_010/Solution.java rename to src/com/blankj/hard/_0010/Solution.java diff --git a/src/com/blankj/hard/_023/Solution.java b/src/com/blankj/hard/_0023/Solution.java similarity index 100% rename from src/com/blankj/hard/_023/Solution.java rename to src/com/blankj/hard/_0023/Solution.java diff --git a/src/com/blankj/hard/_025/Solution.java b/src/com/blankj/hard/_0025/Solution.java similarity index 100% rename from src/com/blankj/hard/_025/Solution.java rename to src/com/blankj/hard/_0025/Solution.java diff --git a/src/com/blankj/hard/_0030/Solution.java b/src/com/blankj/hard/_0030/Solution.java new file mode 100644 index 00000000..750652ec --- /dev/null +++ b/src/com/blankj/hard/_0030/Solution.java @@ -0,0 +1,77 @@ +package com.blankj.hard._030; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2018/02/01
+ *     desc  :
+ * 
+ */ +public class Solution { + public List findSubstring(String s, String[] words) { + if (s == null) return Collections.emptyList(); + int len = s.length(); + if (len == 0) return Collections.emptyList(); + int wordsSize = words.length; + if (wordsSize == 0) return Collections.emptyList(); + int wordLen = words[0].length(), end = len - wordsSize * wordLen; + if (end < 0) return Collections.emptyList(); + Map countMap = new HashMap<>(); + for (String word : words) { + countMap.put(word, countMap.getOrDefault(word, 0) + 1); + } + List res = new ArrayList<>(); + Set ignores = new HashSet<>(); + for (int i = 0; i <= end; ++i) { + if (ignores.contains(i)) continue; + Map findMap = new HashMap<>(); + int st = i, count = 0; + List ignore = new ArrayList<>(); + for (int j = 0; ; ++j) { + int cur = i + j * wordLen; + if (cur + wordLen > len) break; + String word = s.substring(cur, cur + wordLen); + if (countMap.containsKey(word)) { + findMap.put(word, findMap.getOrDefault(word, 0) + 1); + ++count; + while (findMap.get(word) > countMap.get(word)) { + ignore.add(st); + String tmp = s.substring(st, st += wordLen); + findMap.put(tmp, findMap.get(tmp) - 1); + --count; + } + if (count == wordsSize) { + ignore.add(st); + res.add(st); + String tmp = s.substring(st, st += wordLen); + findMap.put(tmp, findMap.get(tmp) - 1); + --count; + } + } else { + for (int k = i; k <= cur; k += wordLen) { + ignore.add(k); + } + break; + } + } + ignores.addAll(ignore); + } + return res; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.findSubstring("wordgoodgoodgoodbestword", new String[]{"word", "good", "best", "good"})); + System.out.println(solution.findSubstring("barfoothefoobarman", new String[]{"foo", "bar"})); + System.out.println(solution.findSubstring("barfoofoobarthefoobarman", new String[]{"bar", "foo", "the"})); + } +} diff --git a/src/com/blankj/hard/_044/Solution.java b/src/com/blankj/hard/_0044/Solution.java similarity index 100% rename from src/com/blankj/hard/_044/Solution.java rename to src/com/blankj/hard/_0044/Solution.java diff --git a/src/com/blankj/medium/_057/Solution.java b/src/com/blankj/hard/_0057/Solution.java similarity index 97% rename from src/com/blankj/medium/_057/Solution.java rename to src/com/blankj/hard/_0057/Solution.java index 8fde4e3a..1e5b4cea 100644 --- a/src/com/blankj/medium/_057/Solution.java +++ b/src/com/blankj/hard/_0057/Solution.java @@ -1,4 +1,4 @@ -package com.blankj.medium._057; +package com.blankj.hard._0057; import com.blankj.structure.Interval; diff --git a/src/com/blankj/hard/_068/Solution.java b/src/com/blankj/hard/_0068/Solution.java similarity index 100% rename from src/com/blankj/hard/_068/Solution.java rename to src/com/blankj/hard/_0068/Solution.java diff --git a/src/com/blankj/hard/_1028/Solution.java b/src/com/blankj/hard/_1028/Solution.java new file mode 100644 index 00000000..da93396b --- /dev/null +++ b/src/com/blankj/hard/_1028/Solution.java @@ -0,0 +1,79 @@ +package com.blankj.hard._1028; + +import com.blankj.structure.TreeNode; + +import java.util.LinkedList; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2020/06/19
+ *     desc  :
+ * 
+ */ +public class Solution { +// public TreeNode recoverFromPreorder(String S) { +// char[] chars = S.toCharArray(); +// int len = chars.length; +// List levels = new LinkedList<>(); +// for (int i = 0; i < len; ) { +// int level = 0, val = 0; +// while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢 +// ++i; +// ++level; +// } +// while (i < len && chars[i] != '-') { // 获取节点的值 +// val = val * 10 + chars[i++] - '0'; +// } +// TreeNode curNode = new TreeNode(val); +// if (level > 0) { +// TreeNode parent = levels.get(level - 1); +// if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。 +// parent.left = curNode; +// } else { +// parent.right = curNode; +// } +// } +// levels.add(level, curNode); // 因为是前序遍历(根-左-右),也就是右覆盖左时,此时左树已遍历完成,故无需考虑覆盖问题 +// } +// return levels.get(0); +// } + + public TreeNode recoverFromPreorder(String S) { + char[] chars = S.toCharArray(); + int len = chars.length; + LinkedList stack = new LinkedList<>(); + for (int i = 0; i < len; ) { + int level = 0, val = 0; + while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢 + ++i; + ++level; + } + while (i < len && chars[i] != '-') { // 获取节点的值 + val = val * 10 + chars[i++] - '0'; + } + TreeNode curNode = new TreeNode(val); + while (stack.size() > level) { // 栈顶不是父亲,栈顶出栈 + stack.removeLast(); + } + if (level > 0) { + TreeNode parent = stack.getLast(); + if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。 + parent.left = curNode; + } else { + parent.right = curNode; + } + } + stack.addLast(curNode); + } + return stack.get(0); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + TreeNode.print(solution.recoverFromPreorder("1-2--3--4-5--6--7")); + System.out.println("=============================================="); + TreeNode.print(solution.recoverFromPreorder("1-2--3---4-5--6---7")); + } +} diff --git a/src/com/blankj/medium/_002/Solution.java b/src/com/blankj/medium/_0002/Solution.java similarity index 100% rename from src/com/blankj/medium/_002/Solution.java rename to src/com/blankj/medium/_0002/Solution.java diff --git a/src/com/blankj/medium/_003/Solution.java b/src/com/blankj/medium/_0003/Solution.java similarity index 100% rename from src/com/blankj/medium/_003/Solution.java rename to src/com/blankj/medium/_0003/Solution.java diff --git a/src/com/blankj/medium/_005/Solution.java b/src/com/blankj/medium/_0005/Solution.java similarity index 100% rename from src/com/blankj/medium/_005/Solution.java rename to src/com/blankj/medium/_0005/Solution.java diff --git a/src/com/blankj/medium/_006/Solution.java b/src/com/blankj/medium/_0006/Solution.java similarity index 100% rename from src/com/blankj/medium/_006/Solution.java rename to src/com/blankj/medium/_0006/Solution.java diff --git a/src/com/blankj/medium/_008/Solution.java b/src/com/blankj/medium/_0008/Solution.java similarity index 71% rename from src/com/blankj/medium/_008/Solution.java rename to src/com/blankj/medium/_0008/Solution.java index 2e4effb2..725e1c96 100644 --- a/src/com/blankj/medium/_008/Solution.java +++ b/src/com/blankj/medium/_0008/Solution.java @@ -17,12 +17,13 @@ public int myAtoi(String str) { } for (; i < len; ++i) { int tmp = str.charAt(i) - '0'; - if (tmp < 0 || tmp > 9) - break; - if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < tmp) + if (tmp < 0 || tmp > 9) break; + if (ans > Integer.MAX_VALUE / 10 + || (ans == Integer.MAX_VALUE / 10 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) { return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; - else + } else { ans = ans * 10 + tmp; + } } return sign * ans; } @@ -35,5 +36,8 @@ public static void main(String[] args) { System.out.println(solution.myAtoi("a1")); System.out.println(solution.myAtoi("100000000000000000000")); System.out.println(solution.myAtoi("-100000000000000000000")); + System.out.println(solution.myAtoi("-3924x8fc")); + System.out.println(solution.myAtoi(String.valueOf(Integer.MIN_VALUE))); + System.out.println(solution.myAtoi(String.valueOf(Integer.MAX_VALUE))); } } \ No newline at end of file diff --git a/src/com/blankj/medium/_011/Solution.java b/src/com/blankj/medium/_0011/Solution.java similarity index 100% rename from src/com/blankj/medium/_011/Solution.java rename to src/com/blankj/medium/_0011/Solution.java diff --git a/src/com/blankj/medium/_012/Solution.java b/src/com/blankj/medium/_0012/Solution.java similarity index 100% rename from src/com/blankj/medium/_012/Solution.java rename to src/com/blankj/medium/_0012/Solution.java diff --git a/src/com/blankj/medium/_015/Solution.java b/src/com/blankj/medium/_0015/Solution.java similarity index 100% rename from src/com/blankj/medium/_015/Solution.java rename to src/com/blankj/medium/_0015/Solution.java diff --git a/src/com/blankj/medium/_016/Solution.java b/src/com/blankj/medium/_0016/Solution.java similarity index 100% rename from src/com/blankj/medium/_016/Solution.java rename to src/com/blankj/medium/_0016/Solution.java diff --git a/src/com/blankj/medium/_017/Solution.java b/src/com/blankj/medium/_0017/Solution.java similarity index 100% rename from src/com/blankj/medium/_017/Solution.java rename to src/com/blankj/medium/_0017/Solution.java diff --git a/src/com/blankj/medium/_018/Solution.java b/src/com/blankj/medium/_0018/Solution.java similarity index 100% rename from src/com/blankj/medium/_018/Solution.java rename to src/com/blankj/medium/_0018/Solution.java diff --git a/src/com/blankj/medium/_019/Solution.java b/src/com/blankj/medium/_0019/Solution.java similarity index 100% rename from src/com/blankj/medium/_019/Solution.java rename to src/com/blankj/medium/_0019/Solution.java diff --git a/src/com/blankj/medium/_022/Solution.java b/src/com/blankj/medium/_0022/Solution.java similarity index 100% rename from src/com/blankj/medium/_022/Solution.java rename to src/com/blankj/medium/_0022/Solution.java diff --git a/src/com/blankj/medium/_024/Solution.java b/src/com/blankj/medium/_0024/Solution.java similarity index 100% rename from src/com/blankj/medium/_024/Solution.java rename to src/com/blankj/medium/_0024/Solution.java diff --git a/src/com/blankj/medium/_029/Solution.java b/src/com/blankj/medium/_0029/Solution.java similarity index 100% rename from src/com/blankj/medium/_029/Solution.java rename to src/com/blankj/medium/_0029/Solution.java diff --git a/src/com/blankj/medium/_033/Solution.java b/src/com/blankj/medium/_0033/Solution.java similarity index 100% rename from src/com/blankj/medium/_033/Solution.java rename to src/com/blankj/medium/_0033/Solution.java diff --git a/src/com/blankj/medium/_043/Solution.java b/src/com/blankj/medium/_0043/Solution.java similarity index 100% rename from src/com/blankj/medium/_043/Solution.java rename to src/com/blankj/medium/_0043/Solution.java diff --git a/src/com/blankj/medium/_049/Solution.java b/src/com/blankj/medium/_0049/Solution.java similarity index 100% rename from src/com/blankj/medium/_049/Solution.java rename to src/com/blankj/medium/_0049/Solution.java diff --git a/src/com/blankj/medium/_050/Solution.java b/src/com/blankj/medium/_0050/Solution.java similarity index 100% rename from src/com/blankj/medium/_050/Solution.java rename to src/com/blankj/medium/_0050/Solution.java diff --git a/src/com/blankj/medium/_056/Solution.java b/src/com/blankj/medium/_0056/Solution.java similarity index 100% rename from src/com/blankj/medium/_056/Solution.java rename to src/com/blankj/medium/_0056/Solution.java diff --git a/src/com/blankj/medium/_0067/Solution.java b/src/com/blankj/medium/_0067/Solution.java new file mode 100644 index 00000000..aba07bad --- /dev/null +++ b/src/com/blankj/medium/_0067/Solution.java @@ -0,0 +1,40 @@ +package com.blankj.medium._0067; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2020/07/07
+ *     desc  :
+ * 
+ */ +public class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + int m = obstacleGrid.length, n = obstacleGrid[0].length; + int[][] dp = new int[m][n]; + // 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法, + // 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0; + for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) { + dp[i][0] = 1; + } + for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) { + dp[0][j] = 1; + } + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (obstacleGrid[i][j] == 0) { + // 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + } + return dp[m - 1][n - 1]; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; + System.out.println(solution.uniquePathsWithObstacles(obstacleGrid)); + } +} diff --git a/src/com/blankj/medium/_0209/Solution.java b/src/com/blankj/medium/_0209/Solution.java new file mode 100644 index 00000000..cdfedebc --- /dev/null +++ b/src/com/blankj/medium/_0209/Solution.java @@ -0,0 +1,70 @@ +package com.blankj.medium._0209; + +import java.util.Arrays; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2020/06/30
+ *     desc  :
+ * 
+ */ +public class Solution { +// public int minSubArrayLen(int s, int[] nums) { +// int ans = Integer.MAX_VALUE; +// for (int i = 0; i < nums.length; i++) { +// int sum = nums[i]; +// if (sum >= s) { +// return 1; +// } +// for (int j = i + 1; j < nums.length; j++) { +// sum += nums[j]; +// if (sum >= s) { +// ans = Math.min(ans, j - i + 1); +// break; +// } +// } +// } +// return ans == Integer.MAX_VALUE ? 0 : ans; +// } + +// public int minSubArrayLen(int s, int[] nums) { +// int left = 0, right = 0, sum = 0, ans = Integer.MAX_VALUE; +// while (right < nums.length) { +// sum += nums[right++]; // 向右扩大窗口 +// while (sum >= s) { // 如果不小于 s,则收缩窗口左边界 +// ans = Math.min(ans, right - left);// 更新结果 +// sum -= nums[left++]; // 向左缩小窗口 +// } +// } +// return ans == Integer.MAX_VALUE ? 0 : ans; +// } + + public int minSubArrayLen(int s, int[] nums) { + int ans = Integer.MAX_VALUE; + int[] sums = new int[nums.length + 1]; + for (int i = 0; i < nums.length; i++) { + sums[i + 1] = sums[i] + nums[i]; + } + for (int i = 0; i < nums.length; i++) { + int target = s + sums[i]; // 确定要搜索的目标值 + // Java 二分查找 Arrays.binarySearch 如果找到就会返回该元素的索引; + // 如果没找到就会返回一个负数,这个负数取反之后再减一就是查找的值应该在数组中的位置; + // 例如 [-1, 0, 1, 5] 中二分查找 2,其返回值就是 -4,其 -(-4) - 1 = 3,所以 2 这个元素插入到数组的索引就是 3 + int bound = Arrays.binarySearch(sums, target); + if (bound < 0) { + bound = -bound - 1; + } + if (bound < sums.length) { // 当 bound 确定插入点不在 sums 数组的最后面时,说明不小于 target 的值了 + ans = Math.min(ans, bound - i); + } + } + return ans == Integer.MAX_VALUE ? 0 : ans; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 3})); + } +} \ No newline at end of file diff --git a/src/com/blankj/medium/_554/Solution.java b/src/com/blankj/medium/_0554/Solution.java similarity index 100% rename from src/com/blankj/medium/_554/Solution.java rename to src/com/blankj/medium/_0554/Solution.java diff --git a/src/com/blankj/medium/_1014/Solution.java b/src/com/blankj/medium/_1014/Solution.java new file mode 100644 index 00000000..fa0ece30 --- /dev/null +++ b/src/com/blankj/medium/_1014/Solution.java @@ -0,0 +1,27 @@ +package com.blankj.medium._1014; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2020/06/18
+ *     desc  :
+ * 
+ */ +public class Solution { + + public int maxScoreSightseeingPair(int[] A) { + int ans = 0, cur = A[0] + 0; + for (int j = 1; j < A.length; j++) { + ans = Math.max(ans, cur + A[j] - j); // 计算当前最大得分 + cur = Math.max(cur, A[j] + j); // 更新最大的 A[i] + i + } + return ans; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] A = new int[]{8, 1, 5, 2, 6}; + System.out.println(solution.maxScoreSightseeingPair(A)); + } +}