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 d0cfe765..7f7fa5da 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # awesome-java-leetcode -我如今是一名Android Developer,大学的我曾是一名ACMer,我一直认为数据结构和算法是作为一名程序员必须掌握和善于利用的,为了不让数据结构和算法淡出我的记忆,所以我打算重拾LeetCode之Algorithm,语言选择的是Java,题库会一点点完善起来,按简单,中等,困难分类,相应难度下按题号排序,源代码在[src][src]目录中,相关解题都在[note][note]目录中,想要学习数据结构和算法或打算刷LeetCode的小伙伴们欢迎star哦。 +我如今是一名 Android Developer,大学的我曾是一名 ACMer,我一直认为数据结构和算法是作为一名程序员必须掌握和善于利用的,为了不让数据结构和算法淡出我的记忆,所以我打算重拾 LeetCode 之 Algorithm,语言选择的是 Java,题库会一点点完善起来,按简单,中等,困难分类,相应难度下按题号排序,源代码在 [src][src] 目录中,相关解题都在 [note][note] 目录中,想要学习数据结构和算法或打算刷 LeetCode 的小伙伴们欢迎 star 哦。 -如今有机会面试Facebook,附上LeetCode上Facebook的面试题目序号,希望可以帮助到以后想入Facebook的小伙伴:-) +如今有机会面试 Facebook,附上 LeetCode 上 Facebook 的面试题目序号,希望可以帮助到以后想入 Facebook 的小伙伴:-) ``` 1,10,13,15,17,20,23,25,26,28,33,38,43,44,49,50,56,57,67,68,69,71,75,76 @@ -12,143 +12,176 @@ 341,377,380,398,404,410,461,477,494,523,525,534,535,543,554 ``` -如果想知道更多公司LeetCode面试题,可以参看[Companies.md][companies]。 +如果想知道更多公司 LeetCode 面试题,可以参看 [Companies.md][companies]。 附上镇楼诗: -> 明有科举八股,今有LeetCode。 -> 八股定格式而取文采心意,LeetCode定题目且重答案背诵。 +> 明有科举八股,今有 LeetCode。 +> 八股定格式而取文采心意,LeetCode 定题目且重答案背诵。 > 美其名曰:"practice makes perfect." > 为何今不如古? > 非也非也, -> 科举为国取士,LeetCode为Google筛码工,各取所需也。 - +> 科举为国取士,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, Dynamic Programming, Divide and Conquer| -|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| -|8|[String to Integer (atoi)][008]|Math, String| -|15|[3Sum][015]|Array, Two Pointers| -|17|[Letter Combinations of a Phone Number][017]|String, Backtracking| -|19|[Remove Nth Node From End of List][019]|Linked List, Two Pointers| -|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|[Reverse Nodes in k-Group][044]|String, Dynamic Programming, Backtracking, Greedy| -|57|[Insert Interval][057]|Array, Sort| +| # | 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 -[008]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/008/README.md -[015]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/015/README.md -[017]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/017/README.md -[019]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/019/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 +[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 63% rename from note/001/README.md rename to note/0001/README.md index 5a4e5866..d7e9f7a8 100644 --- a/note/001/README.md +++ b/note/0001/README.md @@ -18,9 +18,9 @@ return [0, 1]. **Tags:** Array, Hash Table -## 思路0 +## 思路 0 -题意是让你从给定的数组中找到两个元素的和为指定值的两个索引,最容易的当然是循环两次,复杂度为`O(n^2)`,首次提交居然是2ms,打败了100%的提交,谜一样的结果,之后再次提交就再也没跑到过2ms了。 +题意是让你从给定的数组中找到两个元素的和为指定值的两个索引,最容易的当然是循环两次,复杂度为 `O(n^2)`,首次提交居然是 2ms,打败了 100% 的提交,谜一样的结果,之后再次提交就再也没跑到过 2ms 了。 ```java class Solution { @@ -37,9 +37,9 @@ class Solution { } ``` -## 思路1 +## 思路 1 -利用HashMap作为存储,键为目标值减去当前元素值,索引为值,比如`i = 0`时,此时首先要判断`nums[0] = 2`是否在map中,如果不存在,那么插入键值对`key = 9 - 2 = 7, value = 0`,之后当`i = 1`时,此时判断`nums[1] = 7`已存在于map中,那么取出该`value = 0`作为第一个返回值,当前`i`作为第二个返回值,具体代码如下所示。 +利用 HashMap 作为存储,键为目标值减去当前元素值,索引为值,比如 `i = 0` 时,此时首先要判断 `nums[0] = 2` 是否在 map 中,如果不存在,那么插入键值对 `key = 9 - 2 = 7, value = 0`,之后当 `i = 1` 时,此时判断 `nums[1] = 7` 已存在于 map 中,那么取出该 `value = 0` 作为第一个返回值,当前 `i` 作为第二个返回值,具体代码如下所示。 ```java class Solution { @@ -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); } @@ -60,7 +61,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/002/README.md b/note/0002/README.md similarity index 77% rename from note/002/README.md rename to note/0002/README.md index 1aa30033..1700c527 100644 --- a/note/002/README.md +++ b/note/0002/README.md @@ -2,19 +2,24 @@ ## Description -You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. +You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order** and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. -**Input:** (2 -> 4 -> 3) + (5 -> 6 -> 4) -**Output:** 7 -> 0 -> 8 +**Example** + +``` +Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) +Output: 7 -> 0 -> 8 +Explanation: 342 + 465 = 807. +``` **Tags:** Linked List, Math ## 思路 -题意我也是看了好久才看懂,就是以链表表示一个数,低位在前,高位在后,所以题中的例子就是`342 + 465 = 807`,所以我们模拟计算即可。 +题意我也是看了好久才看懂,就是以链表表示一个数,低位在前,高位在后,所以题中的例子就是 `342 + 465 = 807`,所以我们模拟计算即可。 ```java /** @@ -52,7 +57,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/003/README.md b/note/0003/README.md similarity index 74% rename from note/003/README.md rename to note/0003/README.md index 527314c0..30366d46 100644 --- a/note/003/README.md +++ b/note/0003/README.md @@ -10,14 +10,14 @@ Given `"abcabcbb"`, the answer is `"abc"`, which the length is 3. Given `"bbbbb"`, the answer is `"b"`, with the length of 1. -Given `"pwwkew"`, the answer is `"wke"`, with the length of 3. Note that the answer must be a **substring**, `"pwke"` is a *subsequence*and not a substring. +Given `"pwwkew"`, the answer is `"wke"`, with the length of 3. Note that the answer must be a **substring**, `"pwke"` is a *subsequence* and not a substring. **Tags:** Hash Table, Two Pointers, String ## 思路 -题意是计算不带重复字符的最长子字符串的长度,开辟一个hash数组来存储该字符上次出现的位置,比如`hash[a] = 3`就是代表`a`字符前一次出现的索引在3,遍历该字符串,获取到上次出现的最大索引(只能向前,不能退后),与当前的索引做差获取的就是本次所需长度,从中迭代出最大值就是最终答案。 +题意是计算不带重复字符的最长子字符串的长度,开辟一个 hash 数组来存储该字符上次出现的位置,比如 `hash[a] = 3` 就是代表 `a` 字符前一次出现的索引在 3,遍历该字符串,获取到上次出现的最大索引(只能向前,不能退后),与当前的索引做差获取的就是本次所需长度,从中迭代出最大值就是最终答案。 ```java class Solution { @@ -43,7 +43,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0004/README.md b/note/0004/README.md new file mode 100644 index 00000000..521fc440 --- /dev/null +++ b/note/0004/README.md @@ -0,0 +1,89 @@ +# [Median of Two Sorted Arrays][title] + +## Description + +There are two sorted arrays **nums1** and **nums2** of size m and n respectively. + +Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). + +**Example 1:** + +``` +nums1 = [1, 3] +nums2 = [2] + +The median is 2.0 +``` + +**Example 2:** + +``` +nums1 = [1, 2] +nums2 = [3, 4] + +The median is (2 + 3)/2 = 2.5 +``` + +**Tags:** Array, Binary Search, Divide and Conquer + + +## 思路 + +题意是给你两个已排序的递增数组,让你找出其中位数。 + +乍一看这题并不是很难,因为两序列有序,所以我们很容想到时间复杂度为 `O(m + n)` 的做法:依次取出两数组中较小的元素,然后找到中间的元素即可。但这题要求的时间复杂度为 `O(log(m + n))`,那么我们自然而然地就能想到二分查找法进行求解。 + +题目是让找两数组的中位数,我们可以泛化为求两数组中第 `k` 大的元素,那么,求中位数就是其中的一个特例而已。`helper` 函数所起到的作用就是求两数组中第 `k` 大的元素,下面来解释其原理: + +假设数组分别记为 `A`,`B`,当前需要搜索第 `k` 大的数,于是我们可以考虑从数组 `A` 中取出前 `m` 个元素,从数组 `B` 中取出前 `k - m` 个元素。由于数组 `A`,`B` 分别排序,则 `A[m - 1]` 大于从数组 `A` 中取出的其他所有元素,`B[k - m - 1]` 大于数组 `B` 中取出的其他所有元素。此时,尽管取出元素之间的相对大小关系不确定,但 `A[m - 1]` 与 `B[k - m - 1]` 的较大者一定是这 `k` 个元素中最大的。那么,较小的那个元素一定不是第 `k` 大的,这里留给读者自己想象。 + +为叙述方便,假设 `A[m - 1]` 是较小的那个元素,那么我们可以把 `A[0]`,`A[1]`...`A[m - 1]` 排除掉,并且更新 `k` 值为 `k - m`,也就是下一次就是从剩余的元素中寻找第 `k - m` 大的元素,这样,我们就完成了一次范围缩小,同理进行下一轮的操作。 + +那么什么时候停止操作呢?分两种情况: + +1. 当某个数组的数都被取完了,那么直接返回另一个数组的后 `k` 个元素即可。 + +2. 当 `k = 1` 时,也就是只需再找一个数即可,也就是取两者当前较小的那个即可。 + +特别地,我们选取 `m = k / 2`,下面是我画的草图,希望能帮助大家理解。 + +![](https://raw.githubusercontent.com/Blankj/awesome-java-leetcode/master/note/004/my_draw.jpg) + +借助上面的理论,你能写出相关代码了吗? + +```java +class Solution { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int len = nums1.length + nums2.length; + if (len % 2 == 0) { + return (helper(nums1, 0, nums2, 0, len / 2) + helper(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0; + } + return helper(nums1, 0, nums2, 0, (len + 1) / 2); + } + + private int helper(int[] nums1, int m, int[] nums2, int n, int k) { + if (m >= nums1.length) return nums2[n + k - 1]; + if (n >= nums2.length) return nums1[m + k - 1]; + if (k == 1) return Math.min(nums1[m], nums2[n]); + + int p1 = m + k / 2 - 1; + int p2 = n + k / 2 - 1; + int mid1 = p1 < nums1.length ? nums1[p1] : Integer.MAX_VALUE; + int mid2 = p2 < nums2.length ? nums2[p2] : Integer.MAX_VALUE; + if (mid1 < mid2) { + return helper(nums1, m + k / 2, nums2, n, k - k / 2); + } + return helper(nums1, m, nums2, n + k / 2, k - k / 2); + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/median-of-two-sorted-arrays +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0004/my_draw.jpg b/note/0004/my_draw.jpg new file mode 100644 index 00000000..0c3a0739 Binary files /dev/null and b/note/0004/my_draw.jpg differ diff --git a/note/0005/README.md b/note/0005/README.md new file mode 100644 index 00000000..fb74d65b --- /dev/null +++ b/note/0005/README.md @@ -0,0 +1,162 @@ +# [Longest Palindromic Substring][title] + +## Description + +Given a string **s**, find the longest palindromic substring in **s**. You may assume that the maximum length of **s** is 1000. + +**Example 1:** + +``` +Input: "babad" + +Output: "bab" + +Note: "aba" is also a valid answer. +``` + +**Example 2:** + +``` +Input: "cbbd" + +Output: "bb" +``` + +**Tags:** String, Dynamic Programming + + +## 思路 0 + +题意是寻找出字符串中最长的回文串,所谓回文串就是正序和逆序相同的字符串,也就是关于中间对称。我们先用最常规的做法,依次去求得每个字符的最长回文,要注意每个字符有奇数长度的回文串和偶数长度的回文串两种情况,相信你可以很轻易地从如下代码中找到相关代码,记录最长回文的始末位置即可,时间复杂度的话,首先要遍历一遍字符串,然后对每个字符都去求得最长回文,所以时间复杂度为 `O(n^2)`。 + +```java +class Solution { + int st, end; + + public String longestPalindrome(String s) { + int len = s.length(); + if (len <= 1) return s; + char[] chars = s.toCharArray(); + for (int i = 0; i < len; i++) { + helper(chars, i, i); + helper(chars, i, i + 1); + } + return s.substring(st, end + 1); + } + + private void helper(char[] chars, int l, int r) { + while (l >= 0 && r < chars.length && chars[l] == chars[r]) { + --l; + ++r; + } + if (end - st < r - l - 2) { + st = l + 1; + end = r - 1; + } + } +} +``` + + +## 思路 1 + +如果利用暴力法遍历所有字串是否回文的情况这道题肯定是 `Time Limit Exceeded` 的,那么我们是否可以把之前遍历的结果利用上呢,那么动态规划的想法就呼之欲出了,我们定义 `dp[i][j]` 的意思为字符串区间 `[i, j]` 是否为回文串,那么我们分三种情况: + +1. 当 `i == j` 时,那么毫无疑问 `dp[i][j] = true`; + +2. 当 `i + 1 == j` 时,那么 `dp[i][j]` 的值取决于 `s[i] == s[j]`; + +3. 当 `i + 1 < j` 时,那么 `dp[i][j]` 的值取决于 `dp[i + 1][j - 1] && s[i] == s[j]`。 + +根据以上的动态转移方程,我们的问题即可迎刃而解,时间复杂度的话显而易见,也是 `O(n^2)`。 + +```java +class Solution { + public String longestPalindrome(String s) { + int len = s.length(); + if (len <= 1) return s; + int st = 0, end = 0; + char[] chars = s.toCharArray(); + boolean[][] dp = new boolean[len][len]; + for (int i = 0; i < len; i++) { + dp[i][i] = true; + for (int j = 0; j < i; j++) { + if (j + 1 == i) { + dp[j][i] = chars[j] == chars[i]; + } else { + dp[j][i] = dp[j + 1][i - 1] && chars[j] == chars[i]; + } + if (dp[j][i] && i - j > end - st) { + st = j; + end = i; + } + } + } + return s.substring(st, end + 1); + } +} +``` + + +## 思路 2 + +马拉车算法(Manacher's Algorithm) + +### 背景 + +给定一个字符串,求出其最长回文子串(回文字符串就是从左到右读和从右往左读完全一样,也就是字符串关于中间对称)。例如: + +1. s = "babad",最长回文长度为 `3`,可以是 `bab` 或者 `aba`; + +2. s = "cbbda",最长回文长度为 `2`,即 `bb`; + +3. s = "abcde",最长回文长度为 `1`,即单个字符本身。 + +这个问题等同于 LeetCode 上的 [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring),其相关题解可以查看这里:[传送门](https://github.com/Blankj/awesome-java-leetcode/blob/master/note/005/README.md) + +以上问题的传统思路大概是遍历每一个字符,以该字符为中心向两边查找,其时间复杂度为 `O(n^2)`,效率很差。 + +1975 年,一个叫 Manacher 的人发明了 Manacher 算法(中文名:马拉车算法),该算法可以把时间复杂度提升到 `O(n)`,下面我以我理解的思路来讲解其原理。 + + +### 分析 + +由于回文串的奇偶行不确定,比如 `lol` 是奇回文,而 `lool` 是偶回文,马拉车算法的第一步就是对其进行预处理,做法就是在每个字符两侧都加上一个特殊字符,一般就是不会出现在原串中的即可,我们可以选取 `#`,那么 + +``` +lol -> #l#o#l# +lool -> #l#o#o#l# +``` + +这样处理后,不管原来字符串长度是奇数还是偶数,最终得到的长度都将是奇数,从而能把两种情况合并起来一起考虑,记预处理后的字符串为 `str`。 + +我们把一个回文串中最左或最右位置的字符与其对称轴的距离称为回文半径。 + +马拉车算法定义了一个回文半径数组 `len`,用 `len[i]` 表示以第 `i` 个字符为对称轴的回文串的回文半径,比如以 `str[i]` 为中心的最长回文串是 `str[l, r]`,那么 `len[i] = r - i + 1` + +我们以 `lollool` 为例,参看下表。 + +| str | # | l | # | o | # | l | # | l | # | o | # | o | # | l | # | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| len[] | 1 | 2 | 1 | 4 | l | 2 | 5 | 2 | 1 | 2 | 5 | 2 | 1 | 2 | 1 | + +可以发现 `len[i] - 1` 就等于该回文串在原串中的长度。 + +证明:在转换后的字符串 `str` 中,那么对于以 `str[i]` 为中心的最长回文串的长度为 `2 * len[i] - 1`,其中又有 `len[i]` 个分隔符,所以在原字符串中的回文串长度就是 `len[i] - 1`。 + +那么我们剩下的工作就是求 `len` 数组。 + +为了防止数组越界,我们在首位再加上非 `#` 的不常用字符,比如 `~`,那么 `lollool` 就表示为 `~#l#o#l#l#o#o#l#~`,这样我们就省去写很多 `if else` 的边界处理。 + +我们先看一张图,如下所示: + + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/longest-palindromic-substring +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0006/README.md b/note/0006/README.md new file mode 100644 index 00000000..a5ec493e --- /dev/null +++ b/note/0006/README.md @@ -0,0 +1,128 @@ +# [ZigZag Conversion][title] + +## Description + +The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) + +``` +P A H N +A P L S I I G +Y I R +``` + +And then read line by line: `"PAHNAPLSIIGYIR"` + +Write the code that will take a string and make this conversion given a number of rows: + +``` +string convert(string s, int numRows); +``` + +**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 + + +## 思路 0 + +题意是让你把字符串按波浪形排好,然后返回横向读取的字符串。 + +听不懂的话,看下面的表示应该就明白了: + +``` +0 2n-2 4n-4 +1 2n-3 2n-1 4n-5 4n-5 +2 2n-4 2n 4n-6 . +. . . . . +. n+1 . 3n-1 . +n-2 n 3n-4 3n-2 5n-6 +n-1 3n-3 5n-5 +``` + +那么我们可以根据上面找规律,可以看到波峰和波谷是单顶点的,它们周期是 `2 * (n - 1)`,单独处理即可;中间的部分每个周期会出现两次,规律很好找,留给读者自己想象,不懂的可以结合以下代码。 + +```java +class Solution { + public String convert(String s, int numRows) { + if (numRows <= 1) return s; + int len = s.length(); + char[] chars = s.toCharArray(); + int cycle = 2 * (numRows - 1); + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < len; j += cycle) { + sb.append(chars[j]); + } + for (int i = 1; i < numRows - 1; i++) { + int step = 2 * i; + for (int j = i; j < len; j += step) { + sb.append(chars[j]); + step = cycle - step; + } + } + for (int j = numRows - 1; j < len; j += cycle) { + sb.append(chars[j]); + } + return sb.toString(); + } +} +``` + + +## 思路 1 + +另外一种思路就是开辟相应行数的 `StringBuilder` 对象,然后模拟波浪生成的样子分别插入到相应的 `StringBuilder` 对象,比较直白简单,具体代码如下。 + +```java +class Solution { + public String convert(String s, int numRows) { + if (numRows <= 1) return s; + int len = s.length(); + char[] chars = s.toCharArray(); + StringBuilder[] sbs = new StringBuilder[numRows]; + for (int i = 0; i < numRows; i++) { + sbs[i] = new StringBuilder(); + } + int i = 0; + while (i < len) { + for (int j = 0; j < numRows && i < len; ++j) { + sbs[j].append(chars[i++]); + } + for (int j = numRows - 2; j >= 1 && i < len; --j) { + sbs[j].append(chars[i++]); + } + } + for (i = 1; i < numRows; i++) { + sbs[0].append(sbs[i]); + } + return sbs[0].toString(); + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/zigzag-conversion +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0007/README.md b/note/0007/README.md new file mode 100644 index 00000000..e7809e9b --- /dev/null +++ b/note/0007/README.md @@ -0,0 +1,58 @@ +# [Reverse Integer][title] + +## Description + +Given a 32-bit signed integer, reverse digits of an integer. + +**Example 1:** + +``` +Input: 123 +Output: 321 +``` + +**Example 2:** + +``` +Input: -123 +Output: -321 +``` + +**Example 3:** + +``` +Input: 120 +Output: 21 +``` + +**Note:** + +Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. + +**Tags:** Math + + +## 思路 + +题意是给你一个整型数,求它的逆序整型数,而且有个小坑点,当它的逆序整型数溢出的话,那么就返回 0,用我们代码表示的话可以求得结果保存在 long 中,最后把结果和整型的两个范围比较即可。 + +```java +class Solution { + public int reverse(int x) { + long res = 0; + for (; x != 0; x /= 10) + res = res * 10 + x % 10; + return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/reverse-integer +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0008/README.md b/note/0008/README.md new file mode 100644 index 00000000..257e7df7 --- /dev/null +++ b/note/0008/README.md @@ -0,0 +1,100 @@ +# [String to Integer (atoi)][title] + +## Description + +Implement `atoi` which converts a string to an integer. + +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. + +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. + +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. + +If no valid conversion could be performed, a zero value is returned. + +**Note:** + +- 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. + +**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:** + +``` +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 + + +## 思路 + +题意是把一个字符串转为整型,但要注意所给的要求,先去除最前面的空格,然后判断正负数,注意正数可能包含 `+`,如果之后存在非数字或全为空则返回 `0`,而如果合法的值超过 int 表示的最大范围,则根据正负号返回 `INT_MAX` 或 `INT_MIN`。 + +```java +class Solution { + public int myAtoi(String str) { + int i = 0, ans = 0, sign = 1, len = str.length(); + while (i < len && str.charAt(i) == ' ') ++i; + if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) { + sign = str.charAt(i++) == '+' ? 1 : -1; + } + 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 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) { + return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; + } else { + ans = ans * 10 + tmp; + } + } + return sign * ans; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/string-to-integer-atoi +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0009/README.md b/note/0009/README.md new file mode 100644 index 00000000..9571fa0f --- /dev/null +++ b/note/0009/README.md @@ -0,0 +1,81 @@ +# [Palindrome Number][title] + +## Description + +Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. + +**Example 1:** + +``` +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. +``` + +**Example 3:** + +``` +Input: 10 +Output: false +Explanation: Reads 01 from right to left. Therefore it is not a palindrome. +``` + +**Follow up:** + +Coud you solve it without converting the integer to a string? + +**Tags:** Math + + +## 思路 0 + +题意是判断一个有符号整型数是否是回文,也就是逆序过来的整数和原整数相同,首先负数肯定不是,接下来我们分析一下最普通的解法,就是直接算出他的回文数,然后和给定值比较即可。 + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0) return false; + int copyX = x, reverse = 0; + while (copyX > 0) { + reverse = reverse * 10 + copyX % 10; + copyX /= 10; + } + return x == reverse; + } +} +``` + +## 思路 1 + +好好思考下是否需要计算整个长度,比如 1234321,其实不然,我们只需要计算一半的长度即可,就是在计算过程中的那个逆序数比不断除 10 的数大就结束计算即可,但是这也带来了另一个问题,比如 10 的倍数的数 10010,它也会返回 `true`,所以我们需要对 10 的倍数的数再加个判断即可,代码如下所示。 + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) return false; + int halfReverseX = 0; + while (x > halfReverseX) { + halfReverseX = halfReverseX * 10 + x % 10; + x /= 10; + } + return halfReverseX == x || halfReverseX / 10 == x; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/palindrome-number +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0010/README.md b/note/0010/README.md new file mode 100644 index 00000000..61421646 --- /dev/null +++ b/note/0010/README.md @@ -0,0 +1,178 @@ +# [Regular Expression Matching][title] + +## Description + +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 (.)". +``` + +**Example 4:** + +``` +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". +``` + +**Example 5:** + +``` +Input: +s = "mississippi" +p = "mis*is*p*." +Output: false +``` + +**Tags:** String, Dynamic Programming, Backtracking + + +## 思路 0 + +题意是让让你从判断 `s` 字符串是否正则匹配于 `p`,这道题和 [Wildcard Matching][044] 很是相似,区别在于 `*`,通配符的 `*` 是可以随意出现的,跟前面字符没有任何关系,其作用是可以表示任意字符串;而正则匹配的 `*` 不能单独存在,前面必须具有一个字符,其意义是表明前面的这个字符个数可以是任意个数,包括 0 个。首先我们用递归的方式来实现,其思路如下: + +* 如果 `s` 和 `p` 都为空,那么返回 `true`; + +* 如果 `p` 的长度为 1,当 `s` 的长度也为 1,并且他们首位匹配则返回 `true`,否则返回 `false`; + +* 如果 `p` 的第二个字符不为 '*',如果 `s` 为空,那就返回 `false`,首位匹配则返回递归调用他们去掉首位的子字符串,否则返回 `false`; + +* 如果 `p` 的第二个字符为 '*',循环当 `s` 不为空,且首位匹配,如果递归调用是否匹配 `s` 字符串和 `p` 去掉前两位的子字符串,则返回 `true`,否则 `s` 去掉首字母继续循环; + +* 返回递归调用 `s` 字符串和 `p` 去掉前两位的子字符串是否匹配。 + +```java +class Solution { + public boolean isMatch(String s, String p) { + if (p.isEmpty()) return s.isEmpty(); + if (p.length() == 1) { + return s.length() == 1 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); + } + if (p.charAt(1) != '*') { + if (s.isEmpty()) return false; + return (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') + && isMatch(s.substring(1), p.substring(1)); + } + // match 1 or more preceding element + while (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) { + if (isMatch(s, p.substring(2))) return true; + s = s.substring(1); + } + // match 0 preceding element + return isMatch(s, p.substring(2)); + } +} +``` + + +## 思路 1 + +我们可以把上面的思路更简单化,如下: + +* 如果 `s` 和 `p` 都为空,那么返回 `true`; + +* 如果 `p` 的第二个字符为 `*`,由于 `*` 前面的字符个数可以为任意,那么我们先递归调用个数为 0 的情况;或者当 `s` 不为空,如果他们的首字母匹配,那么我们就递归调用去掉去掉首字母的 `s` 和完整的 `p`; + +* 如果 `p` 的第二个字符不为 `*`,那么我们就老老实实判断第一个字符是否匹配并且递归调用他们去掉首位的子字符串。 + +```java +class Solution { + public boolean isMatch(String s, String p) { + if (p.isEmpty()) return s.isEmpty(); + if (p.length() > 1 && p.charAt(1) == '*') { + return isMatch(s, p.substring(2)) + || (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') + && isMatch(s.substring(1), p)); + } + return !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') + && isMatch(s.substring(1), p.substring(1)); + } +} +``` + +## 思路 2 + +另一种思路就是动态规划了,我们定义 `dp[i][j]` 的真假来表示 `s[0..i)` 是否匹配 `p[0..j)`,通过思路 1,我们可以确定其状态转移方程如下所示: + +* 如果 `p[j - 1] == '*'`, `dp[i][j] = dp[i][j - 2] || (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') && dp[i - 1][j];`; + +* 如果 `p[j - 1] != '*'`,`dp[i][j] = dp[i - 1][j - 1] && (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]);`。 + +```java +class Solution { + public boolean isMatch(String s, String p) { + if (p.length() == 0) return s.length() == 0; + int sL = s.length(), pL = p.length(); + boolean[][] dp = new boolean[sL + 1][pL + 1]; + char[] sc = s.toCharArray(), pc = p.toCharArray(); + dp[0][0] = true; + for (int i = 2; i <= pL; ++i) { + if (pc[i - 1] == '*' && dp[0][i - 2]) { + dp[0][i] = true; + } + } + for (int i = 1; i <= sL; ++i) { + for (int j = 1; j <= pL; ++j) { + if (pc[j - 1] == '*') { + dp[i][j] = dp[i][j - 2] || (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') && dp[i - 1][j]; + } else { + dp[i][j] = dp[i - 1][j - 1] && (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]); + } + } + } + return dp[sL][pL]; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[044]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/044/README.md +[title]: https://leetcode.com/problems/regular-expression-matching +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0011/README.md b/note/0011/README.md new file mode 100644 index 00000000..e7e8dd7e --- /dev/null +++ b/note/0011/README.md @@ -0,0 +1,47 @@ +# [Container With Most Water][title] + +## Description + +Given *n* non-negative integers *a1*, *a2*, ..., *an*, where each represents a point at coordinate (*i*, *ai*). *n* vertical lines are drawn such that the two endpoints of line *i* is at (*i*, *ai*) and (*i*, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. + +Note: You may not slant the container and *n* is at least 2. + +**Tags:** Array, Two Pointers + + +## 思路 + +题意是给你 *a1*, *a2*, ..., *an* 这 *n* 个数,代表 (*i*, *ai*) 坐标,让你从中找两个点与 x 轴围成的容器可以容纳最多的水。 + +不明白的话可以看数据为 `1 8 6 2 5 4 8 3 7` 所示的图。 + +![](https://raw.githubusercontent.com/Blankj/awesome-java-leetcode/master/note/011/water.png) + +如果用暴力法求每种情况的结果,其时间复杂度为 O(n^2),相信肯定会超时,我们可以探索下是否有更巧妙的办法呢,题目的标签有双指针,是否就可以想到首尾各放一指针,然后根据条件来收缩。首先计算一次首尾构成的最大面积,然后分析下该移动哪个指针,如果移动大的那个指针的话,那样只会减小面积,所以我们要移动小的那个指针,小的那个指针移动到哪呢?当然是移动到大于之前的值的地方,否则面积不都比之前小么,然后继续更新最大值即可,借助如上分析写出如下代码应该不是什么难事了吧。 + + +```java +class Solution { + public int maxArea(int[] height) { + int l = 0, r = height.length - 1; + int max = 0, h = 0; + while (l < r) { + h = Math.min(height[l], height[r]); + max = Math.max(max, (r - l) * h); + while (height[l] <= h && l < r) ++l; + while (height[r] <= h && l < r) --r; + } + return max; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/container-with-most-water +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0011/water.png b/note/0011/water.png new file mode 100644 index 00000000..7533029c Binary files /dev/null and b/note/0011/water.png differ diff --git a/note/0012/README.md b/note/0012/README.md new file mode 100644 index 00000000..b5f19663 --- /dev/null +++ b/note/0012/README.md @@ -0,0 +1,100 @@ +# [Integer to Roman][title] + +## Description + +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + +``` +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 + + +## 思路 + +题意是整型数转罗马数字,范围从 1 到 3999,查看下百度百科的罗马数字介绍如下: + +* 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3; + +* 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12; + +* 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9。 + +那么我们可以把整数的每一位分离出来,让其每一位都用相应的罗马数字位表示,最终拼接完成。比如 `621` 我们可以分离百、十、个分别为 `6`、`2`、`1`,那么 `600` 对应的罗马数字是 `DC`,`20` 对应的罗马数字是 `XX`,`1` 对应的罗马数字是 `I`,所以最终答案便是 `DCXXI`。 + +```java +class Solution { + public String intToRoman(int num) { + String M[] = {"", "M", "MM", "MMM"}; + String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/integer-to-roman +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0013/README.md b/note/0013/README.md new file mode 100644 index 00000000..43c78400 --- /dev/null +++ b/note/0013/README.md @@ -0,0 +1,113 @@ +# [Roman to Integer][title] + +## Description + +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + +``` +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 + + +## 思路 + +题意是罗马数字转整型数,范围从 1 到 3999,查看下百度百科的罗马数字介绍如下: + +* 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3; + +* 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12; + +* 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9。 + +那么我们可以利用 map 来完成罗马数字的 7 个数字符号:I、V、X、L、C、D、M 和整数的映射关系,然后根据上面的解释来模拟完成即可。 + +```java +class Solution { + public int romanToInt(String s) { + Map map = new HashMap<>(); + map.put('I', 1); + map.put('V', 5); + map.put('X', 10); + map.put('L', 50); + map.put('C', 100); + map.put('D', 500); + map.put('M', 1000); + int len = s.length(); + int sum = map.get(s.charAt(len - 1)); + for (int i = len - 2; i >= 0; --i) { + if (map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { + sum -= map.get(s.charAt(i)); + } else { + sum += map.get(s.charAt(i)); + } + } + return sum; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/roman-to-integer +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/014/README.md b/note/0014/README.md similarity index 58% rename from note/014/README.md rename to note/0014/README.md index a6bd44ae..03e70e4a 100644 --- a/note/014/README.md +++ b/note/0014/README.md @@ -4,12 +4,33 @@ 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 ## 思路 -题意是让你从字符串数组中找出公共前缀,我的想法是找出最短的那个字符串的长度`minLen`,然后在`0...minLen`的范围比较所有字符串,如果比较到有不同的字符,那么直接返回当前索引长度的字符串即可,否则最后返回最短的字符串即可。 +题意是让你从字符串数组中找出公共前缀,我的想法是找出最短的那个字符串的长度 `minLen`,然后在 `0...minLen` 的范围比较所有字符串,如果比较到有不同的字符,那么直接返回当前索引长度的字符串即可,否则最后返回最短的字符串即可。 ```java class Solution { @@ -30,7 +51,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0015/README.md b/note/0015/README.md new file mode 100644 index 00000000..b127a623 --- /dev/null +++ b/note/0015/README.md @@ -0,0 +1,70 @@ +# [3Sum][title] + +## Description + +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. + +**Example:** + +``` +Given array nums = [-1, 0, 1, 2, -1, -4], + +A solution set is: +[ + [-1, 0, 1], + [-1, -1, 2] +] +``` + +**Tags:** Array, Two Pointers + + +## 思路 + +题意是让你从数组中找出所有三个和为 0 的元素构成的非重复序列,这样的话我们可以把数组先做下排序,然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者的和与 0 的大小来移动两个指针,其中细节操作就是优化和去重。 + +```java +class Solution { + public List> threeSum(int[] nums) { + List> list = new ArrayList<>(); + int len = nums.length; + if (len < 3) return list; + Arrays.sort(nums); + int max = nums[len - 1]; + if (max < 0) return list; + for (int i = 0; i < len - 2; ) { + if (nums[i] > 0) break; + if (nums[i] + 2 * max < 0) { + while (nums[i] == nums[++i] && i < len - 2) ; + continue; + } + int left = i + 1, right = len - 1; + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + if (sum == 0) { + list.add(Arrays.asList(nums[i], nums[left], nums[right])); + while (nums[left] == nums[++left] && left < right) ; + while (nums[right] == nums[--right] && left < right) ; + } else if (sum < 0) ++left; + else --right; + } + while (nums[i] == nums[++i] && i < len - 2) ; + } + return list; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/3sum +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0016/README.md b/note/0016/README.md new file mode 100644 index 00000000..fb5a00d0 --- /dev/null +++ b/note/0016/README.md @@ -0,0 +1,56 @@ +# [3Sum Closest][title] + +## Description + +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:** + +``` +Given array nums = [-1, 2, 1, -4], and target = 1. + +The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). +``` + +**Tags:** Array, Two Pointers + + +## 思路 + +题意是让你从数组中找出最接近 `target` 的三个数的和,该题和 [3Sum][015] 的思路基本一样,先对数组进行排序,然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者的和与 `target` 的差值来移动两个指针,并更新其结果,当然,如果三者的和直接与 `target` 值相同,那么返回 `target` 结果即可。 + +```java +public class Solution { + public int threeSumClosest(int[] nums, int target) { + int delta = 0x7fffffff, res = 0; + Arrays.sort(nums); + int len = nums.length - 2; + for (int i = 0; i < len; i++) { + int left = i + 1, right = nums.length - 1; + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + int curDelta = Math.abs(sum - target); + if (curDelta == 0) return sum; + if (curDelta < delta) { + delta = curDelta; + res = sum; + } + if (sum > target) --right; + else ++left; + } + } + return res; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[015]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/015/README.md +[title]: https://leetcode.com/problems/3sum-closest +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/017/README.md b/note/0017/README.md similarity index 95% rename from note/017/README.md rename to note/0017/README.md index 2ebe22f0..2849bfc6 100644 --- a/note/017/README.md +++ b/note/0017/README.md @@ -8,18 +8,21 @@ 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"]. ``` **Note:** + Although the above answer is in lexicographical order, your answer could be in any order you want. **Tags:** String, Backtracking -## 思路0 +## 思路 0 题意是给你按键,让你组合出所有不同结果,首先想到的肯定是回溯了,对每个按键的所有情况进行回溯,回溯的终点就是结果字符串长度和按键长度相同。 @@ -46,7 +49,7 @@ class Solution { } ``` -## 思路1 +## 思路 1 还有一种思路就是利用队列,根据上一次队列中的值,该值拼接当前可选值来不断迭代其结果,具体代码如下。 @@ -76,7 +79,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0018/README.md b/note/0018/README.md new file mode 100644 index 00000000..4685eeb4 --- /dev/null +++ b/note/0018/README.md @@ -0,0 +1,138 @@ +# [4Sum][title] + +## Description + +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. + +**Example:** + +``` +Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. + +A solution set is: +[ + [-1, 0, 0, 1], + [-2, -1, 1, 2], + [-2, 0, 0, 2] +] +``` + +**Tags:** Array, Hash Table, Two Pointers + + +## 思路 0 + +题意是让你从数组中找出所有四个数的和为 `target` 的元素构成的非重复序列,该题和 [3Sum][015] 的思路基本一样,先对数组进行排序,然后遍历这个排序数组,因为这次是四个元素的和,所以外层需要两重循环,然后还是用两个指针分别指向当前元素的下一个和数组尾部,判断四者的和与 `target` 的大小来移动两个指针,其中细节操作还是优化和去重。 + +```java +class Solution { + public List> fourSum(int[] nums, int target) { + List> res = new ArrayList<>(); + int len = nums.length; + if (len < 4) return res; + Arrays.sort(nums); + int max = nums[len - 1]; + if (4 * max < target) return res; + for (int i = 0; i < len - 3;) { + if (nums[i] * 4 > target) break; + if (nums[i] + 3 * max < target) { + while (nums[i] == nums[++i] && i < len - 3) ; + continue; + } + + for (int j = i + 1; j < len - 2;) { + int subSum = nums[i] + nums[j]; + if (nums[i] + nums[j] * 3 > target) break; + if (subSum + 2 * max < target) { + while (nums[j] == nums[++j] && j < len - 2) ; + continue; + } + + int left = j + 1, right = len - 1; + while (left < right) { + int sum = subSum + nums[left] + nums[right]; + if (sum == target) { + res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); + while (nums[left] == nums[++left] && left < right); + while (nums[right] == nums[--right] && left < right); + } else if (sum < target) ++left; + else --right; + } + while (nums[j] == nums[++j] && j < len - 2) ; + } + while (nums[i] == nums[++i] && i < len - 3) ; + } + return res; + } +} +``` + + +## 思路 1 + +从 [Two Sum][001]、[3Sum][015] 到现在的 4Sum,其实都是把高阶降为低阶,那么我们就可以写出 kSum 的函数来对其进行降阶处理,降到 2Sum 后那么我们就可以对其进行最后的判断了,代码如下所示,其也做了相应的优化和去重。 + +```java +class Solution { + public List> fourSum(int[] nums, int target) { + Arrays.sort(nums); + int len = nums.length; + if (len < 4) return Collections.emptyList(); + int max = nums[len - 1]; + if (4 * max < target) return Collections.emptyList(); + return kSum(nums, 0, 4, target); + } + + private List> kSum(int[] nums, int start, int k, int target) { + List> res = new ArrayList<>(); + if (k == 2) { + int left = start, right = nums.length - 1; + while (left < right) { + int sum = nums[left] + nums[right]; + if (sum == target) { + List twoSum = new LinkedList<>(); + twoSum.add(nums[left]); + twoSum.add(nums[right]); + res.add(twoSum); + while (nums[left] == nums[++left] && left < right) ; + while (nums[right] == nums[--right] && left < right) ; + } else if (sum < target) ++left; + else --right; + } + } else { + int i = start, end = nums.length - (k - 1), max = nums[nums.length - 1]; + while (i < end) { + if (nums[i] * k > target) return res; + if (nums[i] + (k - 1) * max < target) { + while (nums[i] == nums[++i] && i < end) ; + continue; + } + List> temp = kSum(nums, i + 1, k - 1, target - nums[i]); + for (List t : temp) { + t.add(0, nums[i]); + } + res.addAll(temp); + while (nums[i] == nums[++i] && i < end) ; + } + } + return res; + } +} +``` + + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[001]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/001/README.md +[015]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/015/README.md +[title]: https://leetcode.com/problems/4sum +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/019/README.md b/note/0019/README.md similarity index 57% rename from note/019/README.md rename to note/0019/README.md index d62a4314..935113e4 100644 --- a/note/019/README.md +++ b/note/0019/README.md @@ -2,28 +2,30 @@ ## 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 ## 思路 -题意是让你删除链表中的倒数第n个数,我的解法是利用双指针,这两个指针相差n个元素,当后面的指针扫到链表末尾的时候,自然它前面的那个指针所指向的下一个元素就是要删除的元素,即`pre.next = pre.next.next;`,但是如果一开始后面的指针指向的为空,此时代表的意思就是要删除第一个元素,即`head = head.next;`。 +题意是让你删除链表中的倒数第 n 个数,我的解法是利用双指针,这两个指针相差 n 个元素,当后面的指针扫到链表末尾的时候,自然它前面的那个指针所指向的下一个元素就是要删除的元素,即 `pre.next = pre.next.next;`,但是如果一开始后面的指针指向的为空,此时代表的意思就是要删除第一个元素,即 `head = head.next;`。 ```java /** @@ -58,7 +60,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/020/README.md b/note/0020/README.md similarity index 59% rename from note/020/README.md rename to note/0020/README.md index 431a6674..410d983a 100644 --- a/note/020/README.md +++ b/note/0020/README.md @@ -4,14 +4,54 @@ 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 ## 思路 -题意是判断括号匹配是否正确,很明显,我们可以用栈来解决这个问题,当出现左括号的时候入栈,当遇到右括号时,判断栈顶的左括号是否何其匹配,不匹配的话直接返回`false`即可,最终判断是否空栈即可,这里我们可以用数组模拟栈的操作使其操作更快,有个细节注意下`top = 1;`,从而省去了之后判空的操作和`top - 1`导致数组越界的错误。 +题意是判断括号匹配是否正确,很明显,我们可以用栈来解决这个问题,当出现左括号的时候入栈,当遇到右括号时,判断栈顶的左括号是否何其匹配,不匹配的话直接返回 `false` 即可,最终判断是否空栈即可,这里我们可以用数组模拟栈的操作使其操作更快,有个细节注意下 `top = 1;`,从而省去了之后判空的操作和 `top - 1` 导致数组越界的错误。 ```java class Solution { @@ -37,7 +77,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/021/README.md b/note/0021/README.md similarity index 71% rename from note/021/README.md rename to note/0021/README.md index 4e907659..90d77ed4 100644 --- a/note/021/README.md +++ b/note/0021/README.md @@ -2,14 +2,14 @@ ## Description -Given a sorted array, remove the duplicates in place such that each element appear only *once* and return the new length. +Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. -Do not allocate extra space for another array, you must do this in place with constant memory. +**Example:** -For example, -Given input array *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. +``` +Input: 1->2->4, 1->3->4 +Output: 1->1->2->3->4->4 +``` **Tags:** Linked List @@ -50,7 +50,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0022/README.md b/note/0022/README.md new file mode 100644 index 00000000..ea8a8c59 --- /dev/null +++ b/note/0022/README.md @@ -0,0 +1,94 @@ +# [Generate Parentheses][title] + +## Description + +Given *n* pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + +For example, given *n* = 3, a solution set is: + +``` +[ + "((()))", + "(()())", + "(())()", + "()(())", + "()()()" +] +``` + +**Tags:** String, Backtracking + + +## 思路 0 + +题意是给你 `n` 值,让你找到所有格式正确的圆括号匹配组,题目中已经给出了 `n = 3` 的所有结果。遇到这种问题,第一直觉就是用到递归或者堆栈,我们选取递归来解决,也就是 `helper` 函数的功能,从参数上来看肯定很好理解了,`leftRest` 代表还有几个左括号可以用,`rightNeed` 代表还需要几个右括号才能匹配,初始状态当然是 `rightNeed = 0, leftRest = n`,递归的终止状态就是 `rightNeed == 0 && leftRest == 0`,也就是左右括号都已匹配完毕,然后把 `str` 加入到链表中即可。 + +```java +class Solution { + public List generateParenthesis(int n) { + List list = new ArrayList<>(); + helper(list, "", 0, n); + return list; + } + + private void helper(List list, String str, int rightNeed, int leftRest) { + if (rightNeed == 0 && leftRest == 0) { + list.add(str); + return; + } + if (rightNeed > 0) helper(list, str + ")", rightNeed - 1, leftRest); + if (leftRest > 0) helper(list, str + "(", rightNeed + 1, leftRest - 1); + } +} +``` + + +## 思路 1 + +另一种实现方式就是迭代的思想了,我们来找寻其规律如下所示: + +``` +f(0): “” + +f(1): “(“f(0)”)” + +f(2): "(“f(0)”)"f(1), “(“f(1)”)” + +f(3): "(“f(0)”)"f(2), "(“f(1)”)"f(1), “(“f(2)”)” +... +``` + +可以递推出 `f(n) = "(“f(0)”)"f(n-1) , "(“f(1)”)"f(n-2) "(“f(2)”)"f(n-3) … "(“f(i)”)“f(n-1-i) … “(f(n-1)”)”` + +根据如上递推式写出如下代码应该不难了吧。 + +```java +class Solution { + public List generateParenthesis(int n) { + HashMap> hashMap = new HashMap<>(); + hashMap.put(0, Collections.singletonList("")); + for (int i = 1; i <= n; i++) { + List list = new ArrayList<>(); + for (int j = 0; j < i; j++) { + for (String fj : hashMap.get(j)) { + for (String fi_j_1 : hashMap.get(i - j - 1)) { + list.add("(" + fj + ")" + fi_j_1);// calculate f(i) + } + } + } + hashMap.put(i, list); + } + return hashMap.get(n); + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/generate-parentheses +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/023/README.md b/note/0023/README.md similarity index 80% rename from note/023/README.md rename to note/0023/README.md index 30bab15f..3de0690a 100644 --- a/note/023/README.md +++ b/note/0023/README.md @@ -2,14 +2,26 @@ ## Description -Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. +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 -## 思路0 +## 思路 0 -题意是合并多个已排序的链表,分析并描述其复杂度,我们可以用分治法来两两合并他们,假设`k`为总链表个数,`N`为总元素个数,那么其时间复杂度为`O(Nlogk)`。 +题意是合并多个已排序的链表,分析并描述其复杂度,我们可以用分治法来两两合并他们,假设 `k` 为总链表个数,`N` 为总元素个数,那么其时间复杂度为 `O(Nlogk)`。 ```java /** @@ -52,9 +64,9 @@ class Solution { } ``` -## 思路1 +## 思路 1 -还有另一种思路是利用优先队列,该数据结构用到的是堆排序,所以对总链表个数为`k`的复杂度为`logk`,总元素为个数为`N`的话,其时间复杂度也为`O(Nlogk)`。 +还有另一种思路是利用优先队列,该数据结构用到的是堆排序,所以对总链表个数为 `k` 的复杂度为 `logk`,总元素为个数为 `N` 的话,其时间复杂度也为 `O(Nlogk)`。 ```java /** @@ -93,7 +105,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0024/README.md b/note/0024/README.md new file mode 100644 index 00000000..8667b5c1 --- /dev/null +++ b/note/0024/README.md @@ -0,0 +1,83 @@ +# [Swap Nodes in Pairs][title] + +## Description + +Given a linked list, swap every two adjacent nodes and return its head. + +**Example:** + +``` +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 + + +## 思路 0 + +题意是让你交换链表中相邻的两个节点,最终返回交换后链表的头,限定你空间复杂度为 O(1)。我们可以用递归来算出子集合的结果,递归的终点就是指针指到链表末少于两个元素时,如果不是终点,那么我们就对其两节点进行交换,这里我们需要一个临时节点来作为交换桥梁,就不多说了。 + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) return head; + ListNode node = head.next; + head.next = swapPairs(node.next); + node.next = head; + return node; + } +} +``` + + +## 思路 1 + +另一种实现方式就是用循环来实现了,两两交换节点,也需要一个临时节点来作为交换桥梁,直到当前指针指到链表末少于两个元素时停止,代码很简单,如下所示。 + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + ListNode preHead = new ListNode(0), cur = preHead; + preHead.next = head; + while (cur.next != null && cur.next.next != null) { + ListNode temp = cur.next.next; + cur.next.next = temp.next; + temp.next = cur.next; + cur.next = temp; + cur = cur.next.next; + } + return preHead.next; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/swap-nodes-in-pairs +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/025/README.md b/note/0025/README.md similarity index 70% rename from note/025/README.md rename to note/0025/README.md index 39d78ee9..fd042a9e 100644 --- a/note/025/README.md +++ b/note/0025/README.md @@ -1,4 +1,4 @@ -# [Merge k Sorted Lists][title] +# [Reverse Nodes in k-Group][title] ## Description @@ -6,29 +6,35 @@ 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. +**Example:** -For example, Given this linked list: `1->2->3->4->5` For *k* = 2, you should return: `2->1->4->3->5` For *k* = 3, you should return: `3->2->1->4->5` +**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 ## 思路 -题意是让你以`k`个元素为一组来翻转链表,最后不足`k`个的话不需要翻转,最传统的思路就是每遇到`k`个元素,对其`k`个元素进行翻转,而难点就是在此,下面介绍其原理,我们以例子中的`k = 3`为例,其`pre`和`next`如下所示。 +题意是让你以 `k` 个元素为一组来翻转链表,最后不足 `k` 个的话不需要翻转,最传统的思路就是每遇到 `k` 个元素,对其 `k` 个元素进行翻转,而难点就是在此,下面介绍其原理,我们以例子中的 `k = 3` 为例,其 `pre` 和 `next` 如下所示。 + ``` 0->1->2->3->4->5 | | pre next ``` -我们要做的就是把`pre`和`next`之间的元素逆序,思想是依次从第二个元素到第`k`个元素,依次把它插入到`pre`后面,过程如下。 + +我们要做的就是把 `pre` 和 `next` 之间的元素逆序,思想是依次从第二个元素到第 `k` 个元素,依次把它插入到 `pre` 后面,过程如下。 + ``` head move | | @@ -48,8 +54,8 @@ pre next | | pre next ``` -好了,根据原理,那写出代码就不难了。 +好了,根据原理,那写出代码就不难了。 ```java /** @@ -93,9 +99,9 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] -[title]: https://leetcode.com/problems/merge-k-sorted-lists +[title]: https://leetcode.com/problems/reverse-nodes-in-k-group [ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0026/README.md b/note/0026/README.md new file mode 100644 index 00000000..58340c4b --- /dev/null +++ b/note/0026/README.md @@ -0,0 +1,79 @@ +# [Remove Duplicates from Sorted Array][title] + +## Description + +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](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. + +**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 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 + + +## 思路 + +题意是让你从一个有序的数组中移除重复的元素,并返回之后数组的长度。我的思路是判断长度小于等于 1 的话直接返回原长度即可,否则的话遍历一遍数组,用一个 `tail` 变量指向尾部,如果后面的元素和前面的元素不同,就让 `tail` 变量加一,最后返回 `tail` 即可。 + +```java +class Solution { + public int removeDuplicates(int[] nums) { + int len = nums.length; + if (len <= 1) return len; + int tail = 1; + for (int i = 1; i < len; ++i) { + if (nums[i - 1] != nums[i]) { + nums[tail++] = nums[i]; + } + } + return tail; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/remove-duplicates-from-sorted-array +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0027/README.md b/note/0027/README.md new file mode 100644 index 00000000..4cfd4983 --- /dev/null +++ b/note/0027/README.md @@ -0,0 +1,81 @@ +# [Remove Element][title] + +## Description + +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. + +The order of elements can be changed. It doesn't matter what you leave beyond the new length. + +**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 + + +## 思路 + +题意是移除数组中值等于 `val` 的元素,并返回之后数组的长度,并且题目中指定空间复杂度为 O(1),我的思路是用 `tail` 标记尾部,遍历该数组时当索引元素不等于 `val` 时,`tail` 加一,尾部指向当前元素,最后返回 `tail` 即可。 + +```java +class Solution { + public int removeElement(int[] nums, int val) { + int tail = 0; + for (int i = 0, len = nums.length; i < len; ++i) { + if (nums[i] != val) { + nums[tail++] = nums[i]; + } + } + return tail; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/remove-element +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0028/README.md b/note/0028/README.md new file mode 100644 index 00000000..7ee16a3d --- /dev/null +++ b/note/0028/README.md @@ -0,0 +1,60 @@ +# [Implement strStr()][title] + +## Description + +Implement [strStr()](http://www.cplusplus.com/reference/cstring/strstr/). + +Return the index of the first occurrence of needle in haystack, or **-1** if needle is not part of haystack. + +**Example 1:** + +``` +Input: haystack = "hello", needle = "ll" +Output: 2 +``` + +**Example 2:** + +``` +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,然后我们只需要遍历比较即可。 + +```java +class Solution { + 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 (haystack.charAt(i + j) != needle.charAt(j)) break; + } + } + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/implement-strstr +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0029/README.md b/note/0029/README.md new file mode 100644 index 00000000..6018b268 --- /dev/null +++ b/note/0029/README.md @@ -0,0 +1,75 @@ +# [Divide Two Integers][title] + +## Description + +Given two integers `dividend` and `divisor`, divide two integers without using multiplication, division and mod operator. + +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 + + +## 思路 + +题意是让你算两个整型数相除后的结果,如果结果溢出就返回 `MAX_INT`,但不能使用乘、除、余的操作符,如果是用加减操作符的话肯定会超时哈,这样的话我们就只能想到位操作符了。 + +首先,我们分析下溢出的情况,也就是当被除数为 `Integer.MIN_VALUE`,除数为 `-1` 时会溢出,因为 `|Integer.MIN_VALUE| = Integer.MAX_VALUE + 1`。 + +然后,我们把除数和被除数都转为 `long` 类型的正数去做下一步操作,我这里以 `22` 和 `3` 相除为例子,因为 `22 >= 3`,我们对 `3` 进行左移一位,也就是乘 2,结果为 `6`,比 `22` 小,我们继续对 `6` 左移一位结果为 `12`,还是比 `22` 小,我们继续对 `12` 左移一位为 `24`,比 `22` 大,这时我们可以分析出,`22` 肯定比 `3` 的 `4` 倍要大,`4` 是怎么来的?因为我们左移了两次,也就是 `1 << 2 = 4`,此时我们记下这个 `4`,然后让 `22 - 3 * 4 = 10`,因为 `10 >= 3`,对 `10` 和 `3` 进行同样的操作,我们可以得到 `2`,此时加上上次的 `4`,和为 `6`,也就是 `22` 比 `3` 的 `6` 倍要大,此时还剩余 `10 - 6 = 4`,因为 `4 >= 3`,所以对 `4` 和 `3` 进行同样的操作,我们发现并不能对 `3` 进行左移了,因为 `4 >= 3`,所以 `1` 倍还是有的,所以加上最后的 `1`,结果为 `6 + 1 = 7`,也就是 `22` 整除 `3` 结果为 `7`。 + +最终,我们对结果赋予符号位即可,根据以上思路来书写如下代码应该不是难事了吧。 + +```java +class Solution { + public int divide(int dividend, int divisor) { + if (dividend == Integer.MIN_VALUE && divisor == -1) { + return Integer.MAX_VALUE; + } + long dvd = Math.abs((long) dividend); + long dvr = Math.abs((long) divisor); + int res = 0; + while (dvd >= dvr) { + long temp = dvr, multiple = 1; + while (dvd >= temp << 1) { + temp <<= 1; + multiple <<= 1; + } + dvd -= temp; + res += multiple; + } + return (dividend < 0) ^ (divisor < 0) ? -res : res; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/divide-two-integers +[ajl]: https://github.com/Blankj/awesome-java-leetcode 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 80% rename from note/033/README.md rename to note/0033/README.md index 937b00c7..f096a1aa 100644 --- a/note/033/README.md +++ b/note/0033/README.md @@ -4,18 +4,35 @@ 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 ## 思路 题意是让你从一个旋转过后的递增序列中寻找给定值,找到返回索引,找不到返回-1,我们在下面这组数据中寻找规律。 + ``` 1 2 4 5 6 7 0 2 4 5 6 7 0 1 @@ -24,6 +41,7 @@ You may assume no duplicate exists in the array. 6 7 0 1 2 4 5 7 0 1 2 4 5 6 ``` + 由于是旋转一次,所以肯定有一半及以上的序列仍然是具有递增性质的,我们观察到如果中间的数比左面的数大的话,那么左半部分序列是递增的,否则右半部分就是递增的,那么我们就可以确定给定值是否在递增序列中,从而决定取舍哪半边。 @@ -50,7 +68,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/035/README.md b/note/0035/README.md similarity index 72% rename from note/035/README.md rename to note/0035/README.md index d259b583..3b78d99f 100644 --- a/note/035/README.md +++ b/note/0035/README.md @@ -6,19 +6,40 @@ Given a sorted array and a target value, return the index if the target is found You may assume no duplicates in the array. -Here are few examples. +**Example 1:** -`[1,3,5,6]`, 5 → 2 -`[1,3,5,6]`, 2 → 1 -`[1,3,5,6]`, 7 → 4 -`[1,3,5,6]`, 0 → 0 +``` +Input: [1,3,5,6], 5 +Output: 2 +``` + +**Example 2:** + +``` +Input: [1,3,5,6], 2 +Output: 1 +``` + +**Example 3:** + +``` +Input: [1,3,5,6], 7 +Output: 4 +``` + +**Example 1:** + +``` +Input: [1,3,5,6], 0 +Output: 0 +``` **Tags:** Array, Binary Search ## 思路 -题意是让你从一个没有重复元素的已排序数组中找到插入位置的索引。因为数组已排序,所以我们可以想到二分查找法,因为查找到的条件是找到第一个等于或者大于`target`的元素的位置,所以二分法略作变动即可。 +题意是让你从一个没有重复元素的已排序数组中找到插入位置的索引。因为数组已排序,所以我们可以想到二分查找法,因为查找到的条件是找到第一个等于或者大于 `target` 的元素的位置,所以二分法略作变动即可。 ```java class Solution { @@ -37,7 +58,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/038/README.md b/note/0038/README.md similarity index 71% rename from note/038/README.md rename to note/0038/README.md index 04766156..2176dc5b 100644 --- a/note/038/README.md +++ b/note/0038/README.md @@ -10,14 +10,15 @@ The count-and-say sequence is the sequence of integers with the first five terms 3. 21 4. 1211 5. 111221 - ``` `1` is read off as `"one 1"` or `11`. + `11` is read off as `"two 1s"` or `21`. + `21` is read off as `"one 2`, then `one 1"` or `1211`. -Given an integer *n*, generate the *n*th term of the count-and-say sequence. +Given an integer *n*, generate the *n*th term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. @@ -26,7 +27,6 @@ Note: Each term of the sequence of integers will be represented as a string. ``` Input: 1 Output: "1" - ``` **Example 2:** @@ -41,7 +41,7 @@ Output: "1211" ## 思路 -题意是数和说,根据如下序列`1, 11, 21, 1211, 111221, ...`,求第n个数,规则很简单,就是数和说,数就是数这个数数字有几个,说就是说这个数,所以`1`就是1个1:`11`,`11`就是有2个1:`21`,`21`就是1个2、1个1:`1211`,可想而知后面就是`111221`,思路的话就是按这个逻辑模拟出来即可。 +题意是数和说,根据如下序列 `1, 11, 21, 1211, 111221, ...`,求第 n 个数,规则很简单,就是数和说,数就是数这个数数字有几个,说就是说这个数,所以 `1` 就是 1 个 1:`11`,`11` 就是有 2 个 1:`21`,`21` 就是 1 个 2、1 个 1:`1211`,可想而知后面就是 `111221`,思路的话就是按这个逻辑模拟出来即可。 ```java class Solution { @@ -70,7 +70,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/004/README.md b/note/004/README.md deleted file mode 100644 index e60a7009..00000000 --- a/note/004/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# [Median of Two Sorted Arrays][title] - -## Description - -There are two sorted arrays **nums1** and **nums2** of size m and n respectively. - -Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). - -**Example 1:** - -``` -nums1 = [1, 3] -nums2 = [2] - -The median is 2.0 - -``` - -**Example 2:** - -``` -nums1 = [1, 2] -nums2 = [3, 4] - -The median is (2 + 3)/2 = 2.5 -``` - -**Tags:** Array, Binary Search, Divide and Conquer - - -## 思路 - -题意是给你两个已排序的递增数组,让你找出其中位数,乍一看这题并不是很难,其实这题难度不可小觑,要做出时间复杂度为O(log (m+n))的话需要了解从两个递增数组中找出第k大的元素,也就是我写的`helper`函数所起到的作用。下面来解释以下其原理:假设数组分别记为A,B,当前需要搜索第k大的数,于是我们可以考虑从数组A中取出前m个元素,从数组B中取出k-m个元素。由于数组A,B分别排序,则A[m]大于从数组A中取出的其他所有元素,B[k-m] 大于数组B中取出的其他所有元素。此时,尽管取出元素之间的相对大小关系不确定,但A[m]与B[k-m]的较大者一定是这k个元素中最大的。那么,较小的那个元素一定不是第k大的,它至多是第k-1大的:因为它小于其他未被取出的所有元素,并且小于取出的k个元素中最大的那个。为叙述方便,假设A[m]是较小的那个元素。那么,我们可以进一步说,A[1], A[2]…A[m-1]也一定不是第k大的元素,因为它们小于A[m],而A[m]至多是第k-1大的。因此,我们可以把较小元素所在数组中选出的所有元素统统排除,并且相应地减少k值。这样,我们就完成了一次范围缩小。特别地,我们可以选取m=k/2。而本题只是其一种情况而已,也就当总长为偶数时,找出其中间的两个数,相加除二即可;当总长为奇数时,找到中间的数即可。 - -```java -class Solution { - public double findMedianSortedArrays(int[] nums1, int[] nums2) { - int len = nums1.length + nums2.length; - if (len % 2 == 0) { - return (helper(nums1, 0, nums2, 0, len / 2) + helper(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0; - } - return helper(nums1, 0, nums2, 0, (len + 1) / 2); - } - - private int helper(int[] nums1, int m, int[] nums2, int n, int k) { - if (m >= nums1.length) return nums2[n + k - 1]; - if (n >= nums2.length) return nums1[m + k - 1]; - if (k == 1) return Math.min(nums1[m], nums2[n]); - - int p1 = m + k / 2 - 1; - int p2 = n + k / 2 - 1; - int mid1 = p1 < nums1.length ? nums1[p1] : Integer.MAX_VALUE; - int mid2 = p2 < nums2.length ? nums2[p2] : Integer.MAX_VALUE; - if (mid1 < mid2) { - return helper(nums1, m + k / 2, nums2, n, k - k / 2); - } - return helper(nums1, m, nums2, n + k / 2, k - k / 2); - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/median-of-two-sorted-arrays -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/043/README.md b/note/0043/README.md similarity index 61% rename from note/043/README.md rename to note/0043/README.md index 1ec3ae74..2f40b99b 100644 --- a/note/043/README.md +++ b/note/0043/README.md @@ -2,14 +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. -2. Both `num1` and `num2` contains only digits `0-9`. -3. Both `num1` and `num2` does not contain any leading zero. -4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly. + ``` + Input: num1 = "2", num2 = "3" + Output: "6" + ``` + + **Example 2:** + + ``` + Input: num1 = "123", num2 = "456" + Output: "56088" + ``` + + **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 @@ -32,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; @@ -50,7 +64,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0044/README.md b/note/0044/README.md new file mode 100644 index 00000000..34f7ae0f --- /dev/null +++ b/note/0044/README.md @@ -0,0 +1,143 @@ +# [Wildcard Matching][title] + +## Description + +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'. +``` + +**Example 4:** + +``` +Input: +s = "adceb" +p = "*a*b" +Output: true +Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". +``` + +**Example 5:** + +``` +Input: +s = "acdcb" +p = "a*c?b" +Output: false +``` + +**Tags:** String, Dynamic Programming, Backtracking, Greedy + + +## 思路 0 + +题意是让让你从判断 `s` 字符串是否通配符匹配于 `p`,这道题和[Regular Expression Matching][010]很是相似,区别在于 `*`,正则匹配的 `*` 不能单独存在,前面必须具有一个字符,其意义是表明前面的这个字符个数可以是任意个数,包括 0 个;而通配符的 `*` 是可以随意出现的,跟前面字符没有任何关系,其作用是可以表示任意字符串。在此我们可以利用 *贪心算法* 来解决这个问题,需要两个额外指针 `p` 和 `match` 来分别记录最后一个 `*` 的位置和 `*` 匹配到 `s` 字符串的位置,其贪心体现在如果遇到 `*`,那就尽可能取匹配后方的内容,如果匹配失败,那就回到上一个遇到 `*` 的位置来继续贪心。 + +```java +class Solution { + public boolean isMatch(String s, String p) { + if (p.length() == 0) return s.length() == 0; + int si = 0, pi = 0, match = 0, star = -1; + int sl = s.length(), pl = p.length(); + char[] sc = s.toCharArray(), pc = p.toCharArray(); + while (si < sl) { + if (pi < pl && (pc[pi] == sc[si] || pc[pi] == '?')) { + si++; + pi++; + } else if (pi < pl && pc[pi] == '*') { + star = pi++; + match = si; + } else if (star != -1) { + si = ++match; + pi = star + 1; + } else return false; + } + while (pi < pl && pc[pi] == '*') pi++; + return pi == pl; + } +} +``` + + +## 思路 1 + +另一种思路就是动态规划了,我们定义 `dp[i][j]` 的真假来表示 `s[0..i)` 是否匹配 `p[0..j)`,其状态转移方程如下所示: + +* 如果 `p[j - 1] != '*'`,`P[i][j] = P[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?');` + +* 如果 `p[j - 1] == '*'`,`P[i][j] = P[i][j - 1] || P[i - 1][j]` + +```java +class Solution { + public boolean isMatch(String s, String p) { + if (p.length() == 0) return s.length() == 0; + int sl = s.length(), pl = p.length(); + boolean[][] dp = new boolean[sl + 1][pl + 1]; + char[] sc = s.toCharArray(), pc = p.toCharArray(); + dp[0][0] = true; + for (int i = 1; i <= pl; ++i) { + if (pc[i - 1] == '*') dp[0][i] = dp[0][i - 1]; + } + for (int i = 1; i <= sl; ++i) { + for (int j = 1; j <= pl; ++j) { + if (pc[j - 1] != '*') { + dp[i][j] = dp[i - 1][j - 1] && (sc[i - 1] == pc[j - 1] || pc[j - 1] == '?'); + } else { + dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; + } + } + } + return dp[sl][pl]; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[010]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/010/README.md +[title]: https://leetcode.com/problems/wildcard-matching +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/049/README.md b/note/0049/README.md similarity index 85% rename from note/049/README.md rename to note/0049/README.md index 6930def9..9832535a 100644 --- a/note/049/README.md +++ b/note/0049/README.md @@ -4,18 +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 @@ -52,7 +56,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0050/README.md b/note/0050/README.md new file mode 100644 index 00000000..84c125fe --- /dev/null +++ b/note/0050/README.md @@ -0,0 +1,66 @@ +# [Pow(x, n)][title] + +## Description + +Implement [pow(*x*, *n*)](http://www.cplusplus.com/reference/valarray/pow/), which calculates *x* raised to the power *n* (xn). + +**Example 1:** + +``` +Input: 2.00000, 10 +Output: 1024.00000 +``` + +**Example 2:** + +``` +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 + + +## 思路 + +题意是让你计算 `x^n`,如果直接计算肯定会超时,那么我们可以想到可以使用二分法来降低时间复杂度。 + +```java +class Solution { + public double myPow(double x, int n) { + if (n < 0) return helper(1 / x, -n); + return helper(x, n); + } + + private double helper(double x, int n) { + if (n == 0) return 1; + if (n == 1) return x; + double d = helper(x, n >>> 1); + if (n % 2 == 0) return d * d; + return d * d * x; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/powx-n +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/053/README.md b/note/0053/README.md similarity index 68% rename from note/053/README.md rename to note/0053/README.md index 53a57465..43cf6f50 100644 --- a/note/053/README.md +++ b/note/0053/README.md @@ -2,21 +2,26 @@ ## 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]`, -the contiguous subarray `[4,-1,2,1]` has the largest sum = `6`. +**Example:** -**More practice:** +``` +Input: [-2,1,-3,4,-1,2,1,-5,4], +Output: 6 +Explanation: [4,-1,2,1] has the largest sum = 6. +``` + +**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. -**Tags:** Array, Dynamic Programming, Divide and Conquer +**Tags:** Array, Divide and Conquer, Dynamic Programming -## 思路0 +## 思路 0 -题意是求数组中子数组的最大和,这种最优问题一般第一时间想到的就是动态规划,我们可以这样想,当部分序列和大于零的话就一直加下一个元素即可,并和当前最大值进行比较,如果出现部分序列小于零的情况,那肯定就是从当前元素算起。其转移方程就是`dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);`,由于我们不需要保留dp状态,故可以优化空间复杂度为1,即`dp = nums[i] + (dp > 0 ? dp : 0);`。 +题意是求数组中子数组的最大和,这种最优问题一般第一时间想到的就是动态规划,我们可以这样想,当部分序列和大于零的话就一直加下一个元素即可,并和当前最大值进行比较,如果出现部分序列小于零的情况,那肯定就是从当前元素算起。其转移方程就是 `dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);`,由于我们不需要保留 dp 状态,故可以优化空间复杂度为 1,即 `dp = nums[i] + (dp > 0 ? dp : 0);`。 ```java class Solution { @@ -31,9 +36,9 @@ class Solution { } ``` -## 思路1 +## 思路 1 -题目也给了我们另一种思路,就是分治,所谓分治就是把问题分割成更小的,最后再合并即可,我们把`nums`一分为二先,那么就有两种情况,一种最大序列包括中间的值,一种就是不包括,也就是在左边或者右边;当最大序列在中间的时候那我们就把它两侧的最大和算出即可;当在两侧的话就继续分治即可。 +题目也给了我们另一种思路,就是分治,所谓分治就是把问题分割成更小的,最后再合并即可,我们把 `nums` 一分为二先,那么就有两种情况,一种最大序列包括中间的值,一种就是不包括,也就是在左边或者右边;当最大序列在中间的时候那我们就把它两侧的最大和算出即可;当在两侧的话就继续分治即可。 ```java class Solution { @@ -65,7 +70,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/056/README.md b/note/0056/README.md similarity index 70% rename from note/056/README.md rename to note/0056/README.md index ec9009d9..48621d1a 100644 --- a/note/056/README.md +++ b/note/0056/README.md @@ -4,16 +4,28 @@ Given a collection of intervals, merge all overlapping intervals. -For example, -Given `[1,3],[2,6],[8,10],[15,18]`, -return `[1,6],[8,10],[15,18]`. +**Example 1:** + +``` +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:** + +``` +Input: [[1,4],[4,5]] +Output: [[1,5]] +Explanation: Intervals [1,4] and [4,5] are considerred overlapping. +``` **Tags:** Array, Sort ## 思路 -题意是给你一组区间,让你把区间合并成没有交集的一组区间。我们可以把区间按`start`进行排序,然后遍历排序后的区间,如果当前的`start`小于前者的`end`,那么说明这两个存在交集,我们取两者中较大的`end`即可;否则的话直接插入到结果序列中即可。 +题意是给你一组区间,让你把区间合并成没有交集的一组区间。我们可以把区间按 `start` 进行排序,然后遍历排序后的区间,如果当前的 `start` 小于前者的 `end`,那么说明这两个存在交集,我们取两者中较大的 `end` 即可;否则的话直接插入到结果序列中即可。 ```java /** @@ -57,7 +69,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/057/README.md b/note/0057/README.md similarity index 85% rename from note/057/README.md rename to note/0057/README.md index 91767640..f9b82a84 100644 --- a/note/057/README.md +++ b/note/0057/README.md @@ -7,12 +7,19 @@ Given a set of *non-overlapping* intervals, insert a new interval into the inter You may assume that the intervals were initially sorted according to their start times. **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 @@ -20,8 +27,11 @@ This is because the new interval `[4,9]` overlaps with `[3,5],[6,7],[8,10]`. ## 思路 题意是给你一组有序区间,和一个待插入区间,让你待插入区间插入到前面的区间中,我们分三步走: + 1. 首先把有序区间中小于待插入区间的部分加入到结果中; + 2. 其次是插入待插入区间,如果有交集的话取两者交集的端点值; + 3. 最后把有序区间中大于待插入区间的部分加入到结果中; ```java @@ -63,7 +73,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/058/README.md b/note/0058/README.md similarity index 72% rename from note/058/README.md rename to note/0058/README.md index a8925546..4afc1c35 100644 --- a/note/058/README.md +++ b/note/0058/README.md @@ -8,18 +8,19 @@ If the last word does not exist, return 0. **Note:** A word is defined as a character sequence consists of non-space characters only. -For example, +**Example:** -Given *s* = `"Hello World"`, - -return `5`. +``` +Input: "Hello World" +Output: 5 +``` **Tags:** String ## 思路 -题意是让你从一个只包含大小字母和空格字符的字符串中得到最后一个单词的长度,很简单,我们倒序遍历,先得到最后一个非空格字符的索引,然后再得到它前面的空格字符索引,两者相减即可。当然,我们使用API来完成这件事更加方便,只需一行代码`return s.trim().length() - s.trim().lastIndexOf(" ") - 1;`,但我相信作者出这道题的目的肯定不是考你API的使用,所以我们还是用自己的思路来实现。 +题意是让你从一个只包含大小字母和空格字符的字符串中得到最后一个单词的长度,很简单,我们倒序遍历,先得到最后一个非空格字符的索引,然后再得到它前面的空格字符索引,两者相减即可。当然,我们使用 API 来完成这件事更加方便,只需一行代码 `return s.trim().length() - s.trim().lastIndexOf(" ") - 1;`,但我相信作者出这道题的目的肯定不是考你 API 的使用,所以我们还是用自己的思路来实现。 ```java class Solution { @@ -36,7 +37,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 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 50% rename from note/066/README.md rename to note/0066/README.md index 37a3377d..03b2ddda 100644 --- a/note/066/README.md +++ b/note/0066/README.md @@ -2,18 +2,34 @@ ## 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 ## 思路 -题意是给你一个数字数组,高位在前,并且首位不为0除非这个数组就是`[0]`,让你给该数组低位加一求其结果,那么我们就模拟小学数学那样进位去算即可,如果一直进位到首位,这种情况也就是都是由9组成的数组,此时我们只要new出一个多一个长度的数组即可,并把第0个元素赋1即可。 +题意是给你一个数字数组,高位在前,并且首位不为 0 除非这个数组就是 `[0]`,让你给该数组低位加一求其结果,那么我们就模拟小学数学那样进位去算即可,如果一直进位到首位,这种情况也就是都是由 9 组成的数组,此时我们只要 new 出一个多一个长度的数组即可,并把第 0 个元素赋 1 即可。 ```java class Solution { @@ -40,7 +56,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/067/README.md b/note/0067/README.md similarity index 61% rename from note/067/README.md rename to note/0067/README.md index 9cdf218b..e000dd25 100644 --- a/note/067/README.md +++ b/note/0067/README.md @@ -4,17 +4,28 @@ Given two binary strings, return their sum (also a binary string). -For example, -a = `"11"` -b = `"1"` -Return `"100"`. +The input strings are both **non-empty** and contains only characters `1` or `0`. + +**Example 1:** + +``` +Input: a = "11", b = "1" +Output: "100" +``` + +**Example 2:** + +``` +Input: a = "1010", b = "1011" +Output: "10101" +``` **Tags:** Math, String ## 思路 -题意是给你两个二进制串,求其和的二进制串。我们就按照小学算数那么来做,用`carry`表示进位,从后往前算,依次往前,每算出一位就插入到最前面即可,直到把两个二进制串都遍历完即可。 +题意是给你两个二进制串,求其和的二进制串。我们就按照小学算数那么来做,用 `carry` 表示进位,从后往前算,依次往前,每算出一位就插入到最前面即可,直到把两个二进制串都遍历完即可。 ```java class Solution { @@ -22,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; } @@ -48,7 +59,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0068/README.md b/note/0068/README.md new file mode 100644 index 00000000..0d3d6f91 --- /dev/null +++ b/note/0068/README.md @@ -0,0 +1,128 @@ +# [Text Justification][title] + +## Description + +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 *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. + +**Note:** + +- 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. + +**Example 1:** + +``` +Input: +words = ["This", "is", "an", "example", "of", "text", "justification."] +maxWidth = 16 +Output: +[ + "This is an", + "example of text", + "justification. " +] +``` + +**Example 2:** + +``` +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. +``` + +**Example 3:** + +``` +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 + + +## 思路 + +题意是给你一组单词和最大行宽,让你对齐他们,对齐的规则就是尽可能一行可以放下足够多的单词,如果最后有多余的空格,那就把空格均匀地插入到单词之间,如果不能平分的话,那就从左开始依次多插一个空格,最后一行单词之间就正常地一个空格即可,如果凑不到最大行宽,那就在末尾补充空格即可,描述地比较差,不懂的话其实看看 demo 也就懂了哈。题还是比较坑的,毕竟踩的比赞的人多,我也是靠模拟老老实实做出来的,求出可以最多插入空格数,然后用它除以可以插入的槽数获取每个单词之间的空格,它两取余的话就是最面需要多插入一个空格的个数,最后一行的话就单独处理即可。 + +```java +class Solution { + public List fullJustify(String[] words, int maxWidth) { + int len = words.length; + List ans = new ArrayList<>(); + StringBuilder spaces = new StringBuilder(); + for (int i = 0; i < maxWidth; ++i) { + spaces.append(" "); + } + int curLen = -1, start = 0; + for (int i = 0; i < len; ++i) { + if (curLen + words[i].length() + 1 <= maxWidth) { + curLen += words[i].length() + 1; + } else { + StringBuilder sub = new StringBuilder(words[start]); + int rest = maxWidth - curLen; + int l = i - start - 1; + if (l <= 0) { + sub.append(spaces.substring(0, rest)); + } else { + int m = rest / l + 1; + int mod = rest % l; + for (int j = start + 1; j < i; ++j) { + if (mod-- > 0) { + sub.append(spaces.substring(0, m + 1)).append(words[j]); + } else { + sub.append(spaces.substring(0, m)).append(words[j]); + } + } + } + ans.add(sub.toString()); + start = i; + curLen = words[i].length(); + } + } + StringBuilder sub = new StringBuilder(words[start]); + for (int i = start + 1; i < len; ++i) { + sub.append(" ").append(words[i]); + } + ans.add(sub + spaces.substring(0, maxWidth - sub.length())); + return ans; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/text-justification +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/0069/README.md b/note/0069/README.md new file mode 100644 index 00000000..6497b335 --- /dev/null +++ b/note/0069/README.md @@ -0,0 +1,54 @@ +# [Sqrt(x)][title] + +## Description + +Implement `int sqrt(int x)`. + +Compute and return the square root of *x*, where *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:** + +``` +Input: 4 +Output: 2 +``` + +**Example 2:** + +``` +Input: 8 +Output: 2 +Explanation: The square root of 8 is 2.82842..., and since + the decimal part is truncated, 2 is returned. +``` + +**Tags:** Binary Search, Math + + +## 思路 + +题意是求平方根,参考 [牛顿迭代法求平方根](https://wenku.baidu.com/view/6b74c622bcd126fff7050bfe.html),然后再参考维基百科的 [Integer square root](https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division) 即可。 + +```java +class Solution { + public int mySqrt(int x) { + long n = x; + while (n * n > x) { + n = (n + x / n) >> 1; + } + return (int) n; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/sqrtx +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/007/README.md b/note/007/README.md deleted file mode 100644 index a029947f..00000000 --- a/note/007/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# [Reverse Integer][title] - -## Description - -Reverse digits of an integer. - -**Example1:** x = 123, return 321 - -**Example2:** x = -123, return -321 - -**Spoilers:** - -**Have you thought about this?** - -Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! - -If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. - -Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? - -For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. - -**Note:** - -The input is assumed to be a 32-bit signed integer. Your function should **return 0 when the reversed integer overflows**. - -**Tags:** Math - - -## 思路 - -题意是给你一个整型数,求它的逆序整型数,而且有个小坑点,当它的逆序整型数溢出的话,那么就返回0,用我们代码表示的话可以求得结果保存在long中,最后把结果和整型的两个范围比较即可。 - -```java -class Solution { - public int reverse(int x) { - long res = 0; - for (; x != 0; x /= 10) - res = res * 10 + x % 10; - return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/reverse-integer -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/070/README.md b/note/0070/README.md similarity index 51% rename from note/070/README.md rename to note/0070/README.md index d1b98fe4..193e12e0 100644 --- a/note/070/README.md +++ b/note/0070/README.md @@ -8,12 +8,33 @@ Each time you can either climb 1 or 2 steps. In how many distinct ways can you c **Note:** Given *n* will be a positive integer. +**Example 1:** + +``` +Input: 2 +Output: 2 +Explanation: There are two ways to climb to the top. +1. 1 step + 1 step +2. 2 steps +``` + +**Example 2:** + +``` +Input: 3 +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 +``` + **Tags:** Dynamic Programming ## 思路 -题意是爬楼梯,每次你只能爬一步或者两步,问到顶层共有多少种方案。我们假设到顶层共有`f(n)`种,那么`f(n) = f(n - 1) + f(n - 2)`肯定是成立的,意思就是我们迈向顶层的最后一步是在倒数第一级台阶或者在倒数第二级台阶。算法我对空间复杂度进行了优化,因为在迭代过程中只需要两个变量即可。 +题意是爬楼梯,每次你只能爬一步或者两步,问到顶层共有多少种方案。我们假设到顶层共有 `f(n)` 种,那么 `f(n) = f(n - 1) + f(n - 2)` 肯定是成立的,意思就是我们迈向顶层的最后一步是在倒数第一级台阶或者在倒数第二级台阶。算法我对空间复杂度进行了优化,因为在迭代过程中只需要两个变量即可。 ```java class Solution { @@ -31,7 +52,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/008/README.md b/note/008/README.md deleted file mode 100644 index d0565433..00000000 --- a/note/008/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# [String to Integer (atoi)][title] - -## Description - -Implement atoi to convert 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. - -**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. - -**Spoilers:** - -**Requirements for atoi:** - -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. - -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. - -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. - -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. - -**Tags:** Math, String - - -## 思路 - -题意是把一个字符串转为整型,但要注意所给的要求,先去除最前面的空格,然后判断正负数,注意正数可能包含`+`,如果之后存在非数字或全为空则返回`0`,而如果合法的值超过int表示的最大范围,则根据正负号返回`INT_MAX`或`INT_MIN`。 - -```java -class Solution { - public int myAtoi(String str) { - int i = 0, ans = 0, sign = 1, len = str.length(); - while (i < len && str.charAt(i) == ' ') ++i; - if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) { - sign = str.charAt(i++) == '+' ? 1 : -1; - } - 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) - return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; - else - ans = ans * 10 + tmp; - } - return sign * ans; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/string-to-integer-atoi -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/083/README.md b/note/0083/README.md similarity index 85% rename from note/083/README.md rename to note/0083/README.md index e581ec26..ebc155ab 100644 --- a/note/083/README.md +++ b/note/0083/README.md @@ -4,9 +4,19 @@ Given a sorted linked list, delete all duplicates such that each element appear only *once*. -For example, -Given `1->1->2`, return `1->2`. -Given `1->1->2->3->3`, return `1->2->3`. +**Example 1:** + +``` +Input: 1->1->2 +Output: 1->2 +``` + +**Example 2:** + +``` +Input: 1->1->2->3->3 +Output: 1->2->3 +``` **Tags:** Linked List @@ -43,7 +53,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0088/README.md b/note/0088/README.md new file mode 100644 index 00000000..ba64df12 --- /dev/null +++ b/note/0088/README.md @@ -0,0 +1,49 @@ +# [Merge Sorted Array][title] + +## Description + +Given two sorted integer arrays *nums1* and *nums2*, merge *nums2* into *nums1* as one sorted array. + +**Note:** + +- 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 + + +## 思路 + +题意是给两个已排序的数组 `nums1` 和 `nums2`,合并 `nums2` 到 `nums1` 中,两数组元素个数分别为 `m` 和 `n`,而且 `nums1` 数组的长度足够容纳 `m + n` 个元素,如果我们按顺序排下去,那肯定要开辟一个新数组来保存元素,如果我们选择逆序,这样利用 `nums1` 自身空间足矣,不会出现覆盖的情况,依次把大的元素插入到 `nums1` 的末尾,确保 `nums2` 中的元素全部插入到 `nums1` 即可。 + +```java +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int p = m-- + n-- - 1; + while (m >= 0 && n >= 0) + nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; + while (n >= 0) + nums1[p--] = nums2[n--]; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/merge-sorted-array +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/009/README.md b/note/009/README.md deleted file mode 100644 index 0dd1d5a1..00000000 --- a/note/009/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# [Palindrome Number][title] - -## Description - -Determine whether an integer is a palindrome. Do this without extra space. - -**Spoilers:** - -**Some hints:** - -Could negative integers be palindromes? (ie, -1) - -If you are thinking of converting the integer to string, note the restriction of using extra space. - -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? - -There is a more generic way of solving this problem. - -**Tags:** Math - - -## 思路0 - -题意是判断一个有符号整型数是否是回文,也就是逆序过来的整数和原整数相同,首先负数肯定不是,接下来我们分析一下最普通的解法,就是直接算出他的回文数,然后和给定值比较即可。 - -```java -class Solution { - public boolean isPalindrome(int x) { - if (x < 0) return false; - int copyX = x, reverse = 0; - while (copyX > 0) { - reverse = reverse * 10 + copyX % 10; - copyX /= 10; - } - return x == reverse; - } -} -``` - -## 思路1 - -好好思考下是否需要计算整个长度,比如1234321,其实不然,我们只需要计算一半的长度即可,就是在计算过程中的那个逆序数比不断除10的数大就结束计算即可,但是这也带来了另一个问题,比如10的倍数的数10010,它也会返回`true`,所以我们需要对10的倍数的数再加个判断即可,代码如下所示。 - -```java -public boolean isPalindrome(int x) { - if (x < 0 || (x != 0 && x % 10 == 0)) return false; - int halfReverseX = 0; - while (x > halfReverseX) { - halfReverseX = halfReverseX * 10 + x % 10; - x /= 10; - } - return halfReverseX == x || halfReverseX / 10 == x; -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/palindrome-number -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/010/README.md b/note/010/README.md deleted file mode 100644 index 08e6674d..00000000 --- a/note/010/README.md +++ /dev/null @@ -1,128 +0,0 @@ -# [Regular Expression Matching][title] - -## Description - -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). - -The function prototype should be: -bool isMatch(const char *s, const char *p) - -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 -``` - -**Tags:** String, Dynamic Programming, Backtracking - - -## 思路0 - -题意是让让你从判断`s`字符串是否正则匹配于`p`,这道题和[Wildcard Matching][044]很是相似,区别在于`*`,通配符的`*`是可以随意出现的,跟前面字符没有任何关系,其作用是可以表示任意字符串;而正则匹配的`*`不能单独存在,前面必须具有一个字符,其意义是表明前面的这个字符个数可以是任意个数,包括0个。首先我们用递归的方式来实现,其思路如下: -* 如果`s`和`p`都为空,那么返回`true` -* 如果`p`的长度为1,当`s`的长度也为1,并且他们首位匹配则返回`true`,否则返回`false` -* 如果`p`的第二个字符不为'*',如果`s`为空,那就返回`false`,首位匹配则返回递归调用他们去掉首位的子字符串,否则返回`false` -* 如果`p`的第二个字符为'*',循环当`s`不为空,且首位匹配,如果递归调用是否匹配`s`字符串和`p`去掉前两位的子字符串,则返回`true`,否则`s`去掉首字母继续循环 -* 返回递归调用`s`字符串和`p`去掉前两位的子字符串是否匹配 - -```java -class Solution { - public boolean isMatch(String s, String p) { - if (p.isEmpty()) return s.isEmpty(); - if (p.length() == 1) { - return s.length() == 1 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); - } - if (p.charAt(1) != '*') { - if (s.isEmpty()) return false; - return (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') - && isMatch(s.substring(1), p.substring(1)); - } - // match 1 or more preceding element - while (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) { - if (isMatch(s, p.substring(2))) return true; - s = s.substring(1); - } - // match 0 preceding element - return isMatch(s, p.substring(2)); - } -} -``` - - -## 思路1 - -我们可以把上面的思路更简单化,如下 -* 如果`s`和`p`都为空,那么返回`true` -* 如果`p`的第二个字符为`*`,由于`*`前面的字符个数可以为任意,那么我们先递归调用个数为0的情况;或者当`s`不为空,如果他们的首字母匹配,那么我们就递归调用去掉去掉首字母的`s`和完整的`p` -* 如果`p`的第二个字符不为`*`,那么我们就老老实实判断第一个字符是否匹配并且递归调用他们去掉首位的子字符串 - -```java -class Solution { - public boolean isMatch(String s, String p) { - if (p.isEmpty()) return s.isEmpty(); - if (p.length() > 1 && p.charAt(1) == '*') { - return isMatch(s, p.substring(2)) - || (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') - && isMatch(s.substring(1), p)); - } - return !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') - && isMatch(s.substring(1), p.substring(1)); - } -} -``` - -## 思路2 - -另一种思路就是动态规划了,我们定义`dp[i][j]`的真假来表示`s[0..i)`是否匹配`p[0..j)`,通过思路1,我们可以确定其状态转移方程如下所示: -* 如果`p[j - 1] == '*'`, `dp[i][j] = dp[i][j - 2] || (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') && dp[i - 1][j];` -* 如果`p[j - 1] != '*'`,`dp[i][j] = dp[i - 1][j - 1] && (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]);` - - - -```java -class Solution { - public boolean isMatch(String s, String p) { - if (p.length() == 0) return s.length() == 0; - int sL = s.length(), pL = p.length(); - boolean[][] dp = new boolean[sL + 1][pL + 1]; - char[] sc = s.toCharArray(), pc = p.toCharArray(); - dp[0][0] = true; - for (int i = 2; i <= pL; ++i) { - if (pc[i - 1] == '*' && dp[0][i - 2]) { - dp[0][i] = true; - } - } - for (int i = 1; i <= sL; ++i) { - for (int j = 1; j <= pL; ++j) { - if (pc[j - 1] == '*') { - dp[i][j] = dp[i][j - 2] || (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') && dp[i - 1][j]; - } else { - dp[i][j] = dp[i - 1][j - 1] && (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]); - } - } - } - return dp[sL][pL]; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[044]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/044/README.md -[title]: https://leetcode.com/problems/regular-expression-matching -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/100/README.md b/note/0100/README.md similarity index 56% rename from note/100/README.md rename to note/0100/README.md index a06660f0..341c01de 100644 --- a/note/100/README.md +++ b/note/0100/README.md @@ -2,9 +2,45 @@ ## Description -Given two binary trees, write a function to check if they are equal or not. +Given two binary trees, write a function to check if they are the same or not. -Two binary trees are considered equal if they are structurally identical and the nodes have the same value. +Two binary trees are considered the same if they are structurally identical and the nodes have the same value. + +**Example 1:** + +``` +Input: 1 1 + / \ / \ + 2 3 2 3 + + [1,2,3], [1,2,3] + +Output: true +``` + +**Example 2:** + +``` +Input: 1 1 + / \ + 2 2 + + [1,2], [1,null,2] + +Output: false +``` + +**Example 3:** + +``` +Input: 1 1 + / \ / \ + 2 1 1 2 + + [1,2,1], [1,1,2] + +Output: false +``` **Tags:** Tree, Depth-first Search @@ -38,7 +74,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/101/README.md b/note/0101/README.md similarity index 84% rename from note/101/README.md rename to note/0101/README.md index 1f83fd85..8f0e0b05 100644 --- a/note/101/README.md +++ b/note/0101/README.md @@ -12,7 +12,6 @@ For example, this binary tree `[1,2,2,3,4,4,3]` is symmetric: 2 2 / \ / \ 3 4 4 3 - ``` But the following `[1,2,2,null,3,null,3]` is not: @@ -23,16 +22,16 @@ But the following `[1,2,2,null,3,null,3]` is not: 2 2 \ \ 3 3 - ``` **Note:** + Bonus points if you could solve it both recursively and iteratively. **Tags:** Tree, Depth-first Search, Breadth-first Search -## 思路0 +## 思路 0 题意是判断一棵二叉树是否左右对称,首先想到的是深搜,比较根结点的左右两棵子树是否对称,如果左右子树的值相同,那么再分别对左子树的左节点和右子树的右节点,左子树的右节点和右子树的左节点做比较即可。 @@ -48,20 +47,20 @@ Bonus points if you could solve it both recursively and iteratively. */ class Solution { public boolean isSymmetric(TreeNode root) { - return root == null || isSymmetricHelper(root.left, root.right); + return root == null || helper(root.left, root.right); } public boolean helper(TreeNode left, TreeNode right) { if (left == null || right == null) return left == right; if (left.val != right.val) return false; - return isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left); + return helper(left.left, right.right) && helper(left.right, right.left); } } ``` -## 思路1 +## 思路 1 -第二种思路就是宽搜了,宽搜肯定要用到队列,Java中可用`LinkedList`替代,也是要做到左子树的左节点和右子树的右节点,左子树的右节点和右子树的左节点做比较即可。 +第二种思路就是宽搜了,宽搜肯定要用到队列,Java 中可用 `LinkedList` 替代,也是要做到左子树的左节点和右子树的右节点,左子树的右节点和右子树的左节点做比较即可。 ```java /** @@ -96,9 +95,10 @@ class Solution { } ``` + ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/104/README.md b/note/0104/README.md similarity index 79% rename from note/104/README.md rename to note/0104/README.md index 960f325d..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 @@ -34,7 +50,7 @@ The maximum depth is the number of nodes along the longest path from the root no ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/107/README.md b/note/0107/README.md similarity index 96% rename from note/107/README.md rename to note/0107/README.md index 7d220cc9..a8600d7c 100644 --- a/note/107/README.md +++ b/note/0107/README.md @@ -5,6 +5,7 @@ Given a binary tree, return the *bottom-up level order* traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: + Given binary tree `[3,9,20,null,null,15,7]`, ``` @@ -28,11 +29,10 @@ return its bottom-up level order traversal as: **Tags:** Tree, Breadth-first Search -## 思路0 +## 思路 0 题意是从下往上按层遍历二叉树,每一层是从左到右,按层遍历,很明显,宽搜第一时间符合,因为是从下往上,所以插入的时候每次插到链表头即可。 - ```java /** * Definition for a binary tree node. @@ -65,7 +65,7 @@ class Solution { } ``` -## 思路1 +## 思路 1 另一种思路就是深搜,深搜的时候同时记录深度,然后在相应的层插入节点值即可。 @@ -101,7 +101,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/108/README.md b/note/0108/README.md similarity index 79% rename from note/108/README.md rename to note/0108/README.md index 95b1be29..115a8f02 100644 --- a/note/108/README.md +++ b/note/0108/README.md @@ -4,6 +4,22 @@ Given an array where elements are sorted in ascending order, convert it to a height balanced BST. +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:** + +``` +Given the sorted array: [-10,-3,0,5,9], + +One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: + + 0 + / \ + -3 9 + / / + -10 5 +``` + **Tags:** Tree, Depth-first Search @@ -12,8 +28,11 @@ Given an array where elements are sorted in ascending order, convert it to a hei 题意是把一个有序数组转化为一棵二叉搜索树,二叉搜索树具有以下性质: 1. 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值; + 2. 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值; + 3. 任意节点的左、右子树也分别为二叉查找树; + 4. 没有键值相等的节点。 所以我们可以用递归来构建一棵二叉搜索树,每次把数组分为两半,把数组中间的值作为其父节点,然后把数组的左右两部分继续构造其左右子树。 @@ -49,7 +68,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/110/README.md b/note/0110/README.md similarity index 58% rename from note/110/README.md rename to note/0110/README.md index 773aff0c..823ea493 100644 --- a/note/110/README.md +++ b/note/0110/README.md @@ -4,15 +4,45 @@ 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 ## 思路 -题意是判断一棵二叉树是否是高度平衡的,所谓二叉树高度平衡指的是二叉树的每个节点的两棵子树的高度差都不超过1,那么我们只需计算左右子树的高度,判断其高度差是否不超过1即可,如果超过1,就代表其不是高度平衡的,立即返回不是即可,我这里用返回`-1`代表不是。 - +题意是判断一棵二叉树是否是高度平衡的,所谓二叉树高度平衡指的是二叉树的每个节点的两棵子树的高度差都不超过 1,那么我们只需计算左右子树的高度,判断其高度差是否不超过 1 即可,如果超过 1,就代表其不是高度平衡的,立即返回不是即可,我这里用返回 `-1` 代表不是。 ```java /** @@ -44,7 +74,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/111/README.md b/note/0111/README.md similarity index 75% rename from note/111/README.md rename to note/0111/README.md index e816e619..5c4e2b8a 100644 --- a/note/111/README.md +++ b/note/0111/README.md @@ -6,13 +6,28 @@ 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. -**Tags:** Tree, Depth-first Search, Breadth-first Search +**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 -## 思路0 -题意是查找二叉树的最小深度,也就是找到从根结点到叶子节点的最小深度,最容易想到的当然是深搜,如果节点的左右深度都不是0的话,说明该节点含有左右子树,所以它的最小高度就是1加上其左右子树高度较小者,否则如果左子树为空或者右子树为空或者两者都为空,那么就是1加上非空子树高度。 +## 思路 0 +题意是查找二叉树的最小深度,也就是找到从根结点到叶子节点的最小深度,最容易想到的当然是深搜,如果节点的左右深度都不是 0 的话,说明该节点含有左右子树,所以它的最小高度就是 1 加上其左右子树高度较小者,否则如果左子树为空或者右子树为空或者两者都为空,那么就是 1 加上非空子树高度。 ```java /** @@ -35,7 +50,7 @@ class Solution { } ``` -## 思路1 +## 思路 1 第二种思路就是利用宽搜了,搜索到该层有叶子节点,那就返回该层宽度即可。 @@ -75,9 +90,9 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] -[title]: https://leetcode.com/problems/balanced-binary-tree +[title]: https://leetcode.com/problems/minimum-depth-of-binary-tree [ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/112/README.md b/note/0112/README.md similarity index 84% rename from note/112/README.md rename to note/0112/README.md index 9483d7df..a287dd09 100644 --- a/note/112/README.md +++ b/note/0112/README.md @@ -4,19 +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. @@ -51,7 +52,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/118/README.md b/note/0118/README.md similarity index 74% rename from note/118/README.md rename to note/0118/README.md index f0fac05c..6e268aa3 100644 --- a/note/118/README.md +++ b/note/0118/README.md @@ -2,12 +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, -Return +![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. + +**Example:** ``` +Input: 5 +Output: [ [1], [1,1], @@ -49,7 +53,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/119/README.md b/note/0119/README.md similarity index 63% rename from note/119/README.md rename to note/0119/README.md index cc754b06..65b792e5 100644 --- a/note/119/README.md +++ b/note/0119/README.md @@ -2,12 +2,22 @@ ## 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, -Return `[1,3,3,1]`. +Note that the row index starts from 0. + +![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. + +**Example:** + +``` +Input: 3 +Output: [1,3,3,1] +``` + +**Follow up:** -**Note:** Could you optimize your algorithm to use only *O*(*k*) extra space? **Tags:** Array @@ -35,7 +45,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/121/README.md b/note/0121/README.md similarity index 69% rename from note/121/README.md rename to note/0121/README.md index 8ed719d4..5699ece1 100644 --- a/note/121/README.md +++ b/note/0121/README.md @@ -4,25 +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 @@ -49,7 +49,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/0122/README.md b/note/0122/README.md new file mode 100644 index 00000000..a4a3aaa9 --- /dev/null +++ b/note/0122/README.md @@ -0,0 +1,65 @@ +# [Best Time to Buy and Sell Stock II][title] + +## Description + +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 (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 + + +## 思路 + +题意是给出一个数组代表每天的股票金额,在每天只能买或卖的情况下求出收益最高值,这...,这也太简单了吧,把所有相邻递增的值都加起来即可。 + +```java +class Solution { + public int maxProfit(int[] prices) { + int max = 0; + for (int i = 1; i < prices.length; ++i) { + if (prices[i] > prices[i - 1]) max += prices[i] - prices[i - 1]; + } + return max; + } +} +``` + + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] + + + +[title]: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii +[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/013/README.md b/note/013/README.md deleted file mode 100644 index 557ba029..00000000 --- a/note/013/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# [Roman to Integer][title] - -## Description - -Given a roman numeral, convert it to an integer. - -Input is guaranteed to be within the range from 1 to 3999. - -**Tags:** Math, String - - -## 思路 - -题意是罗马数字转整型数,范围从1到3999,查看下百度百科的罗马数字介绍如下, - -* 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3; -* 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12; -* 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9; - -那么我们可以利用map来完成罗马数字的7个数字符号:I、V、X、L、C、D、M和整数的映射关系,然后根据上面的解释来模拟完成即可。 - -```java -class Solution { - public int romanToInt(String s) { - Map map = new HashMap<>(); - map.put('I', 1); - map.put('V', 5); - map.put('X', 10); - map.put('L', 50); - map.put('C', 100); - map.put('D', 500); - map.put('M', 1000); - int len = s.length(); - int sum = map.get(s.charAt(len - 1)); - for (int i = len - 2; i >= 0; --i) { - if (map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { - sum -= map.get(s.charAt(i)); - } else { - sum += map.get(s.charAt(i)); - } - } - return sum; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/roman-to-integer -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/015/README.md b/note/015/README.md deleted file mode 100644 index 70a6ca0c..00000000 --- a/note/015/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# [3Sum][title] - -## 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. - -**Note:** The solution set must not contain duplicate triplets. - -``` -For example, given array S = [-1, 0, 1, 2, -1, -4], - -A solution set is: -[ - [-1, 0, 1], - [-1, -1, 2] -] -``` - -**Tags:** Array, Two Pointers - - -## 思路 - -题意是让你从数组中找出所有三个和为0的元素构成的非重复序列,这样的话我们可以把数组先做下排序,然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者和与0的大小来移动两个指针,其中细节操作就是注意去重。 - -```java -class Solution { - public List> threeSum(int[] nums) { - Arrays.sort(nums); - List> list = new ArrayList<>(); - int i = 0; - while (i < nums.length - 2) { - if (nums[i] > 0) break; - int left = i + 1, right = nums.length - 1; - while (left < right) { - int sum = nums[i] + nums[left] + nums[right]; - if (sum == 0) { - list.add(Arrays.asList(nums[i], nums[left++], nums[right--])); - while (left < right && nums[left] == nums[left - 1]) ++left; - while (left < right && nums[right] == nums[right + 1]) --right; - } else if (sum < 0) ++left; - else --right; - } - while (nums[i] == nums[++i] && i < nums.length - 2) ; - } - return list; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/3sum -[ajl]: https://github.com/Blankj/awesome-java-leetcode 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/026/README.md b/note/026/README.md deleted file mode 100644 index ca163f6c..00000000 --- a/note/026/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# [Remove Duplicates from Sorted Array][title] - -## Description - -Given a sorted array, remove the duplicates in place such that each element appear only *once* and return the new length. - -Do not allocate extra space for another array, you must do this in place with constant memory. - -For example, -Given input array *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. - -**Tags:** Array, Two Pointers - - -## 思路 - -题意是让你从一个有序的数组中移除重复的元素,并返回之后数组的长度。我的思路是判断长度小于等于1的话直接返回原长度即可,否则的话遍历一遍数组,用一个`tail`变量指向尾部,如果后面的元素和前面的元素不同,就让`tail`变量加一,最后返回`tail`即可。 - -```java -class Solution { - public int removeDuplicates(int[] nums) { - int len = nums.length; - if (len <= 1) return len; - int tail = 1; - for (int i = 1; i < len; ++i) { - if (nums[i - 1] != nums[i]) { - nums[tail++] = nums[i]; - } - } - return tail; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/remove-duplicates-from-sorted-array -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/027/README.md b/note/027/README.md deleted file mode 100644 index 4d3d89a5..00000000 --- a/note/027/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# [Remove Element][title] - -## Description - -Given an array and a value, remove all instances of that value in place and return the new length. - -Do not allocate extra space for another array, you must do this in place with constant memory. - -The order of elements can be changed. It doesn't matter what you leave beyond the new length. - -**Example:** - -Given input array *nums* = `[3,2,2,3]`, *val* = `3` - -Your function should return length = 2, with the first two elements of *nums* being 2. - -**Tags:** Array, Two Pointers - - -## 思路 - -题意是移除数组中值等于`val`的元素,并返回之后数组的长度,并且题目中指定空间复杂度为O(1),我的思路是用`tail`标记尾部,遍历该数组时当索引元素不等于`val`时,`tail`加一,尾部指向当前元素,最后返回`tail`即可。 - -```java -class Solution { - public int removeElement(int[] nums, int val) { - int tail = 0; - for (int i = 0, len = nums.length; i < len; ++i) { - if (nums[i] != val) { - nums[tail++] = nums[i]; - } - } - return tail; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/remove-element -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/028/README.md b/note/028/README.md deleted file mode 100644 index 6f681933..00000000 --- a/note/028/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# [Implement strStr()][title] - -## Description - -Implement strStr(). - -Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. - -**Tags:** Two Pointers, String - - -## 思路 - -题意是从主串中找到子串的索引,如果找不到则返回-1,当字串长度大于主串,直接返回-1,然后我们只需要遍历比较即可。 - -```java -class Solution { - public int strStr(String haystack, String needle) { - int l1 = haystack.length(), l2 = needle.length(); - if (l1 < l2) return -1; - for (int i = 0; ; i++) { - 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; - } - } - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/implement-strstr -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/044/README.md b/note/044/README.md deleted file mode 100644 index 59291b91..00000000 --- a/note/044/README.md +++ /dev/null @@ -1,99 +0,0 @@ -# [Wildcard Matching][title] - -## Description - -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). - -The function prototype should be: -bool isMatch(const char *s, const char *p) - -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 -``` - -**Tags:** String, Dynamic Programming, Backtracking, Greedy - - -## 思路0 - -题意是让让你从判断`s`字符串是否通配符匹配于`p`,这道题和[Regular Expression Matching][010]很是相似,区别在于`*`,正则匹配的`*`不能单独存在,前面必须具有一个字符,其意义是表明前面的这个字符个数可以是任意个数,包括0个;而通配符的`*`是可以随意出现的,跟前面字符没有任何关系,其作用是可以表示任意字符串。在此我们可以利用*贪心算法*来解决这个问题,需要两个额外指针`p`和`match`来分别记录最后一个`*`的位置和`*`匹配到`s`字符串的位置,其贪心体现在如果遇到`*`,那就尽可能取匹配后方的内容,如果匹配失败,那就回到上一个遇到`*`的位置来继续贪心。 - -```java -class Solution { - public boolean isMatch(String s, String p) { - if (p.length() == 0) return s.length() == 0; - int si = 0, pi = 0, match = 0, star = -1; - int sl = s.length(), pl = p.length(); - char[] sc = s.toCharArray(), pc = p.toCharArray(); - while (si < sl) { - if (pi < pl && (pc[pi] == sc[si] || pc[pi] == '?')) { - si++; - pi++; - } else if (pi < pl && pc[pi] == '*') { - star = pi++; - match = si; - } else if (star != -1) { - si = ++match; - pi = star + 1; - } else return false; - } - while (pi < pl && pc[pi] == '*') pi++; - return pi == pl; - } -} -``` - - -## 思路1 - -另一种思路就是动态规划了,我们定义`dp[i][j]`的真假来表示`s[0..i)`是否匹配`p[0..j)`,其状态转移方程如下所示: -* 如果`p[j - 1] != '*'`,`P[i][j] = P[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?');` -* 如果`p[j - 1] == '*'`,`P[i][j] = P[i][j - 1] || P[i - 1][j]` - -```java -class Solution { - public boolean isMatch(String s, String p) { - if (p.length() == 0) return s.length() == 0; - int sl = s.length(), pl = p.length(); - boolean[][] dp = new boolean[sl + 1][pl + 1]; - char[] sc = s.toCharArray(), pc = p.toCharArray(); - dp[0][0] = true; - for (int i = 1; i <= pl; ++i) { - if (pc[i - 1] == '*') dp[0][i] = dp[0][i - 1]; - } - for (int i = 1; i <= sl; ++i) { - for (int j = 1; j <= pl; ++j) { - if (pc[j - 1] != '*') { - dp[i][j] = dp[i - 1][j - 1] && (sc[i - 1] == pc[j - 1] || pc[j - 1] == '?'); - } else { - dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; - } - } - } - return dp[sl][pl]; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[010]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/010/README.md -[title]: https://leetcode.com/problems/wildcard-matching -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/050/README.md b/note/050/README.md deleted file mode 100644 index c8b3a99e..00000000 --- a/note/050/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# [Pow(x, n)][title] - -## Description - -Implement pow(x, n). - -**Tags:** Math, Binary Search - - -## 思路 - -题意是让你计算`x^n`,如果直接计算肯定会超时,那么我们可以想到可以使用二分法来降低时间复杂度。 - -```java -class Solution { - public double myPow(double x, int n) { - if (n < 0) return helper(1 / x, -n); - return helper(x, n); - } - - private double helper(double x, int n) { - if (n == 0) return 1; - if (n == 1) return x; - double d = helper(x, n >>> 1); - if (n % 2 == 0) return d * d; - return d * d * x; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/powx-n -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/543/README.md b/note/0543/README.md similarity index 93% rename from note/543/README.md rename to note/0543/README.md index 551dbca2..1a28f9ba 100644 --- a/note/543/README.md +++ b/note/0543/README.md @@ -5,7 +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 @@ -13,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]. @@ -58,7 +57,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/554/README.md b/note/0554/README.md similarity index 96% rename from note/554/README.md rename to note/0554/README.md index a99b35ae..2bfa6a4a 100644 --- a/note/554/README.md +++ b/note/0554/README.md @@ -29,6 +29,7 @@ Explanation: **Note:** 1. The width sum of bricks in different rows are the same and won't exceed INT_MAX. + 2. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000. **Tags:** Hash Table @@ -62,7 +63,7 @@ class Solution { ## 结语 -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] diff --git a/note/069/README.md b/note/069/README.md deleted file mode 100644 index 4525d2a4..00000000 --- a/note/069/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# [Sqrt(x)][title] - -## Description - -Implement `int sqrt(int x)`. - -Compute and return the square root of x. - -**Tags:** Binary Search, Math - - -## 思路 - -题意是求平方根,参考[牛顿迭代法求平方根](https://wenku.baidu.com/view/6b74c622bcd126fff7050bfe.html),然后再参考维基百科的[Integer square root](https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division)即可。 - -```java -class Solution { - public int mySqrt(int x) { - long n = x; - while (n * n > x) { - n = (n + x / n) >> 1; - } - return (int) n; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/sqrtx -[ajl]: https://github.com/Blankj/awesome-java-leetcode diff --git a/note/088/README.md b/note/088/README.md deleted file mode 100644 index b4cf4532..00000000 --- a/note/088/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# [Merge Sorted Array][title] - -## Description - -Given two sorted integer arrays *nums1* and *nums2*, merge *nums2* into *nums1* as one sorted array. - -**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. - -**Tags:** Array, Two Pointers - - -## 思路 - -题意是给两个已排序的数组`nums1`和`nums2`,合并`nums2`到`nums1`中,两数组元素个数分别为`m`和`n`,而且`nums1`数组的长度足够容纳`m + n`个元素,如果我们按顺序排下去,那肯定要开辟一个新数组来保存元素,如果我们选择逆序,这样利用`nums1`自身空间足矣,不会出现覆盖的情况,依次把大的元素插入到`nums1`的末尾,确保`nums2`中的元素全部插入到`nums1`即可。 - -```java -class Solution { - public void merge(int[] nums1, int m, int[] nums2, int n) { - int p = m-- + n-- - 1; - while (m >= 0 && n >= 0) - nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; - while (n >= 0) - nums1[p--] = nums2[n--]; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/merge-sorted-array -[ajl]: https://github.com/Blankj/awesome-java-leetcode 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/122/README.md b/note/122/README.md deleted file mode 100644 index ab4a45a2..00000000 --- a/note/122/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# [Best Time to Buy and Sell Stock II][title] - -## Description - -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). - -**Tags:** Array, Greedy - - -## 思路 - -题意是给出一个数组代表每天的股票金额,在每天只能买或卖的情况下求出收益最高值,这...,这也太简单了吧,把所有相邻递增的值都加起来即可。 - -```java -class Solution { - public int maxProfit(int[] prices) { - int max = 0; - for (int i = 1; i < prices.length; ++i) { - if (prices[i] > prices[i - 1]) max += prices[i] - prices[i - 1]; - } - return max; - } -} -``` - - -## 结语 - -如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl] - - - -[title]: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii -[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 99% rename from src/com/blankj/easy/_013/Solution.java rename to src/com/blankj/easy/_0013/Solution.java index 2322a0ed..204d9f4e 100644 --- a/src/com/blankj/easy/_013/Solution.java +++ b/src/com/blankj/easy/_0013/Solution.java @@ -36,6 +36,6 @@ public int romanToInt(String s) { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.romanToInt("DCXXI"));// 621 - System.out.println(solution.romanToInt("CCCXLVIII"));// 384 + System.out.println(solution.romanToInt("CCCXLVIII"));// 348 } } 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 89% rename from src/com/blankj/easy/_101/Solution.java rename to src/com/blankj/easy/_0101/Solution.java index 0c6d58f1..4fd23e88 100644 --- a/src/com/blankj/easy/_101/Solution.java +++ b/src/com/blankj/easy/_0101/Solution.java @@ -15,13 +15,13 @@ */ public class Solution { // public boolean isSymmetric(TreeNode root) { -// return root == null || isSymmetricHelper(root.left, root.right); +// return root == null || helper(root.left, root.right); // } // // private boolean helper(TreeNode left, TreeNode right) { // if (left == null || right == null) return left == right; // if (left.val != right.val) return false; -// return isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left); +// return helper(left.left, right.right) && helper(left.right, right.left); // } public boolean isSymmetric(TreeNode root) { 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/_0044/Solution.java b/src/com/blankj/hard/_0044/Solution.java new file mode 100644 index 00000000..2a9de72c --- /dev/null +++ b/src/com/blankj/hard/_0044/Solution.java @@ -0,0 +1,107 @@ +package com.blankj.hard._044; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2017/10/16
+ *     desc  :
+ * 
+ */ +public class Solution { +// public boolean isMatch(String s, String p) { +// if (p.length() == 0) return s.length() == 0; +// int si = 0, pi = 0, match = 0, star = -1; +// int sl = s.length(), pl = p.length(); +// char[] sc = s.toCharArray(), pc = p.toCharArray(); +// while (si < sl) { +// if (pi < pl && (pc[pi] == sc[si] || pc[pi] == '?')) { +// si++; +// pi++; +// } else if (pi < pl && pc[pi] == '*') { +// star = pi++; +// match = si; +// } else if (star != -1) { +// si = ++match; +// pi = star + 1; +// } else return false; +// } +// while (pi < pl && pc[pi] == '*') pi++; +// return pi == pl; +// } + +// public boolean isMatch(String s, String p) { +// if (p.length() == 0) return s.length() == 0; +// int sl = s.length(), pl = p.length(); +// boolean[][] dp = new boolean[sl + 1][pl + 1]; +// char[] sc = s.toCharArray(), pc = p.toCharArray(); +// dp[0][0] = true; +// for (int i = 1; i <= pl; ++i) { +// if (pc[i - 1] == '*') dp[0][i] = dp[0][i - 1]; +// } +// for (int i = 1; i <= sl; ++i) { +// for (int j = 1; j <= pl; ++j) { +// if (pc[j - 1] != '*') { +// dp[i][j] = dp[i - 1][j - 1] && (sc[i - 1] == pc[j - 1] || pc[j - 1] == '?'); +// } else { +// dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; +// } +// } +// } +// return dp[sl][pl]; +// } + + public List fullJustify(String[] words, int maxWidth) { + int len = words.length; + if (len == 0) return Collections.emptyList(); + List ans = new ArrayList<>(); + StringBuilder spaces = new StringBuilder(); + for (int i = 0; i < maxWidth; ++i) { + spaces.append(" "); + } + int sLen = -1, left = 0; + for (int i = 0; i < len; ++i) { + if (sLen + words[i].length() + 1 <= maxWidth) { + sLen += words[i].length() + 1; + } else { + StringBuilder sub = new StringBuilder(words[left]); + int rest = maxWidth - sLen; + int seg = i - left; + if (seg == 0) { + sub.append(spaces.substring(0, rest)); + } else { + int leastSpace = rest / seg + 1; + int restSpace = rest % seg; + for (int j = left + 1; j < i; ++j) { + if (restSpace-- > 0) { + sub.append(spaces.substring(0, leastSpace + 1)).append(words[j]); + } else { + sub.append(spaces.substring(0, leastSpace)).append(words[j]); + } + } + } + ans.add(sub.toString()); + left = i; + sLen = words[i].length(); + } + } + StringBuilder sub = new StringBuilder(words[left]); + for (int i = left + 1; i < len; ++i) { + sub.append(" ").append(words[i]); + } + ans.add(sub + spaces.substring(0, maxWidth - sub.length())); + return ans; + } + + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.fullJustify(new String[]{"", ""}, 0)); + System.out.println(solution.fullJustify(new String[]{"a"}, 1)); + System.out.println(solution.fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 16)); + } +} 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/_0068/Solution.java b/src/com/blankj/hard/_0068/Solution.java new file mode 100644 index 00000000..14b3a98f --- /dev/null +++ b/src/com/blankj/hard/_0068/Solution.java @@ -0,0 +1,61 @@ +package com.blankj.hard._068; + +import java.util.ArrayList; +import java.util.List; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2017/11/01
+ *     desc  :
+ * 
+ */ +public class Solution { + + public List fullJustify(String[] words, int maxWidth) { + int len = words.length; + List ans = new ArrayList<>(); + StringBuilder spaces = new StringBuilder(); + for (int i = 0; i < maxWidth; ++i) { + spaces.append(" "); + } + int curLen = -1, start = 0; + for (int i = 0; i < len; ++i) { + if (curLen + words[i].length() + 1 <= maxWidth) { + curLen += words[i].length() + 1; + } else { + StringBuilder sub = new StringBuilder(words[start]); + int rest = maxWidth - curLen; + int l = i - start - 1; + if (l <= 0) { + sub.append(spaces.substring(0, rest)); + } else { + int m = rest / l + 1; + int mod = rest % l; + for (int j = start + 1; j < i; ++j) { + if (mod-- > 0) { + sub.append(spaces.substring(0, m + 1)).append(words[j]); + } else { + sub.append(spaces.substring(0, m)).append(words[j]); + } + } + } + ans.add(sub.toString()); + start = i; + curLen = words[i].length(); + } + } + StringBuilder sub = new StringBuilder(words[start]); + for (int i = start + 1; i < len; ++i) { + sub.append(" ").append(words[i]); + } + ans.add(sub + spaces.substring(0, maxWidth - sub.length())); + return ans; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 16)); + } +} diff --git a/src/com/blankj/hard/_044/Solution.java b/src/com/blankj/hard/_044/Solution.java deleted file mode 100644 index 3fa17b75..00000000 --- a/src/com/blankj/hard/_044/Solution.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.blankj.hard._044; - -/** - *
- *     author: Blankj
- *     blog  : http://blankj.com
- *     time  : 2017/10/16
- *     desc  :
- * 
- */ -public class Solution { -// public boolean isMatch(String s, String p) { -// if (p.length() == 0) return s.length() == 0; -// int si = 0, pi = 0, match = 0, star = -1; -// int sl = s.length(), pl = p.length(); -// char[] sc = s.toCharArray(), pc = p.toCharArray(); -// while (si < sl) { -// if (pi < pl && (pc[pi] == sc[si] || pc[pi] == '?')) { -// si++; -// pi++; -// } else if (pi < pl && pc[pi] == '*') { -// star = pi++; -// match = si; -// } else if (star != -1) { -// si = ++match; -// pi = star + 1; -// } else return false; -// } -// while (pi < pl && pc[pi] == '*') pi++; -// return pi == pl; -// } - - public boolean isMatch(String s, String p) { - if (p.length() == 0) return s.length() == 0; - int sl = s.length(), pl = p.length(); - boolean[][] dp = new boolean[sl + 1][pl + 1]; - char[] sc = s.toCharArray(), pc = p.toCharArray(); - dp[0][0] = true; - for (int i = 1; i <= pl; ++i) { - if (pc[i - 1] == '*') dp[0][i] = dp[0][i - 1]; - } - for (int i = 1; i <= sl; ++i) { - for (int j = 1; j <= pl; ++j) { - if (pc[j - 1] != '*') { - dp[i][j] = dp[i - 1][j - 1] && (sc[i - 1] == pc[j - 1] || pc[j - 1] == '?'); - } else { - dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; - } - } - } - return dp[sl][pl]; - } - - public static void main(String[] args) { - Solution solution = new Solution(); - System.out.println(solution.isMatch("aa", "a")); // false - System.out.println(solution.isMatch("aa", "aa")); // true - System.out.println(solution.isMatch("aaa", "aa")); // false - System.out.println(solution.isMatch("aa", "*")); // true - System.out.println(solution.isMatch("aa", "a*")); // true - System.out.println(solution.isMatch("ab", "?*")); // true - System.out.println(solution.isMatch("aab", "c*a*b"));// false - } -} 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/_0005/Solution.java b/src/com/blankj/medium/_0005/Solution.java new file mode 100644 index 00000000..5e35da9f --- /dev/null +++ b/src/com/blankj/medium/_0005/Solution.java @@ -0,0 +1,72 @@ +package com.blankj.medium._005; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2017/11/04
+ *     desc  :
+ * 
+ */ +public class Solution { +// int st, end; +// +// public String longestPalindrome(String s) { +//// st = 0; +//// end = 0; +// int len = s.length(); +// if (len <= 1) return s; +// char[] chars = s.toCharArray(); +// for (int i = 0; i < len; i++) { +// helper(chars, i, i); +// helper(chars, i, i + 1); +// } +// return s.substring(st, end + 1); +// } +// +// private void helper(char[] chars, int l, int r) { +// while (l >= 0 && r < chars.length && chars[l] == chars[r]) { +// --l; +// ++r; +// } +// if (end - st < r - l - 2) { +// st = l + 1; +// end = r - 1; +// } +// } + +// public String longestPalindrome(String s) { +// int len = s.length(); +// if (len <= 1) return s; +// int st = 0, end = 0; +// char[] chars = s.toCharArray(); +// boolean[][] dp = new boolean[len][len]; +// for (int i = 0; i < len; i++) { +// dp[i][i] = true; +// for (int j = 0; j < i; j++) { +// if (j + 1 == i) { +// dp[j][i] = chars[j] == chars[i]; +// } else { +// dp[j][i] = dp[j + 1][i - 1] && chars[j] == chars[i]; +// } +// if (dp[j][i] && i - j > end - st) { +// st = j; +// end = i; +// } +// } +// } +// return s.substring(st, end + 1); +// } + + public String longestPalindrome(String s) { + + return s; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.longestPalindrome("babad")); + System.out.println(solution.longestPalindrome("cbbd")); + + } +} diff --git a/src/com/blankj/medium/_0006/Solution.java b/src/com/blankj/medium/_0006/Solution.java new file mode 100644 index 00000000..0def8017 --- /dev/null +++ b/src/com/blankj/medium/_0006/Solution.java @@ -0,0 +1,63 @@ +package com.blankj.medium._006; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2017/12/11
+ *     desc  :
+ * 
+ */ +class Solution { + +// public String convert(String s, int numRows) { +// if (numRows <= 1) return s; +// int len = s.length(); +// char[] chars = s.toCharArray(); +// int cycle = 2 * (numRows - 1); +// StringBuilder sb = new StringBuilder(); +// for (int j = 0; j < len; j += cycle) { +// sb.append(chars[j]); +// } +// for (int i = 1; i < numRows - 1; i++) { +// int step = 2 * i; +// for (int j = i; j < len; j += step) { +// sb.append(chars[j]); +// step = cycle - step; +// } +// } +// for (int j = numRows - 1; j < len; j += cycle) { +// sb.append(chars[j]); +// } +// return sb.toString(); +// } + + public String convert(String s, int numRows) { + if (numRows <= 1) return s; + int len = s.length(); + char[] chars = s.toCharArray(); + StringBuilder[] sbs = new StringBuilder[numRows]; + for (int i = 0; i < numRows; i++) { + sbs[i] = new StringBuilder(); + } + int i = 0; + while (i < len) { + for (int j = 0; j < numRows && i < len; ++j) { + sbs[j].append(chars[i++]); + } + for (int j = numRows - 2; j >= 1 && i < len; --j) { + sbs[j].append(chars[i++]); + } + } + for (i = 1; i < numRows; i++) { + sbs[0].append(sbs[i]); + } + return sbs[0].toString(); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.convert("PAYPALISHIRING", 3));// PAHNAPLSIIGYIR + System.out.println(solution.convert("ABCD", 4)); + } +} 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/_0011/Solution.java b/src/com/blankj/medium/_0011/Solution.java new file mode 100644 index 00000000..89ee60ca --- /dev/null +++ b/src/com/blankj/medium/_0011/Solution.java @@ -0,0 +1,29 @@ +package com.blankj.medium._011; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2017/04/23
+ *     desc  :
+ * 
+ */ +public class Solution { + public int maxArea(int[] height) { + int l = 0, r = height.length - 1; + int max = 0, h = 0; + while (l < r) { + h = Math.min(height[l], height[r]); + max = Math.max(max, (r - l) * h); + while (height[l] <= h && l < r) ++l; + while (height[r] <= h && l < r) --r; + } + return max; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.maxArea(new int[]{1, 2, 4, 3})); // 4 + System.out.println(solution.maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));// 49 + } +} \ No newline at end of file diff --git a/src/com/blankj/medium/_0012/Solution.java b/src/com/blankj/medium/_0012/Solution.java new file mode 100644 index 00000000..d3f57fff --- /dev/null +++ b/src/com/blankj/medium/_0012/Solution.java @@ -0,0 +1,25 @@ +package com.blankj.medium._012; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2018/01/25
+ *     desc  :
+ * 
+ */ +public class Solution { + public String intToRoman(int num) { + String M[] = {"", "M", "MM", "MMM"}; + String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.intToRoman(621));// DCXXI + System.out.println(solution.intToRoman(348));// CCCXLVIII + } +} diff --git a/src/com/blankj/medium/_015/Solution.java b/src/com/blankj/medium/_0015/Solution.java similarity index 56% rename from src/com/blankj/medium/_015/Solution.java rename to src/com/blankj/medium/_0015/Solution.java index 33b79a46..b4af0e08 100644 --- a/src/com/blankj/medium/_015/Solution.java +++ b/src/com/blankj/medium/_0015/Solution.java @@ -14,22 +14,29 @@ */ public class Solution { public List> threeSum(int[] nums) { - Arrays.sort(nums); List> list = new ArrayList<>(); - int i = 0; - while (i < nums.length - 2) { + int len = nums.length; + if (len < 3) return list; + Arrays.sort(nums); + int max = nums[len - 1]; + if (max < 0) return list; + for (int i = 0; i < len - 2; ) { if (nums[i] > 0) break; - int left = i + 1, right = nums.length - 1; + if (nums[i] + 2 * max < 0) { + while (nums[i] == nums[++i] && i < len - 2) ; + continue; + } + int left = i + 1, right = len - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { - list.add(Arrays.asList(nums[i], nums[left++], nums[right--])); - while (left < right && nums[left] == nums[left - 1]) ++left; - while (left < right && nums[right] == nums[right + 1]) --right; + list.add(Arrays.asList(nums[i], nums[left], nums[right])); + while (nums[left] == nums[++left] && left < right) ; + while (nums[right] == nums[--right] && left < right) ; } else if (sum < 0) ++left; else --right; } - while (nums[i] == nums[++i] && i < nums.length - 2) ; + while (nums[i] == nums[++i] && i < len - 2) ; } return list; } diff --git a/src/com/blankj/medium/_0016/Solution.java b/src/com/blankj/medium/_0016/Solution.java new file mode 100644 index 00000000..9d9ce040 --- /dev/null +++ b/src/com/blankj/medium/_0016/Solution.java @@ -0,0 +1,39 @@ +package com.blankj.medium._016; + +import java.util.Arrays; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2018/01/25
+ *     desc  :
+ * 
+ */ +public class Solution { + public int threeSumClosest(int[] nums, int target) { + int delta = 0x7fffffff, res = 0; + Arrays.sort(nums); + int len = nums.length - 2; + for (int i = 0; i < len; i++) { + int left = i + 1, right = nums.length - 1; + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + int curDelta = Math.abs(sum - target); + if (curDelta == 0) return sum; + if (curDelta < delta) { + delta = curDelta; + res = sum; + } + if (sum > target) --right; + else ++left; + } + } + return res; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1)); + } +} 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/_0018/Solution.java b/src/com/blankj/medium/_0018/Solution.java new file mode 100644 index 00000000..19886674 --- /dev/null +++ b/src/com/blankj/medium/_0018/Solution.java @@ -0,0 +1,105 @@ +package com.blankj.medium._018; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2018/01/30
+ *     desc  :
+ * 
+ */ +public class Solution { +// public List> fourSum(int[] nums, int target) { +// List> res = new ArrayList<>(); +// int len = nums.length; +// if (len < 4) return res; +// Arrays.sort(nums); +// int max = nums[len - 1]; +// if (4 * max < target) return res; +// for (int i = 0; i < len - 3;) { +// if (nums[i] * 4 > target) break; +// if (nums[i] + 3 * max < target) { +// while (nums[i] == nums[++i] && i < len - 3) ; +// continue; +// } +// +// for (int j = i + 1; j < len - 2;) { +// int subSum = nums[i] + nums[j]; +// if (nums[i] + nums[j] * 3 > target) break; +// if (subSum + 2 * max < target) { +// while (nums[j] == nums[++j] && j < len - 2) ; +// continue; +// } +// +// int left = j + 1, right = len - 1; +// while (left < right) { +// int sum = subSum + nums[left] + nums[right]; +// if (sum == target) { +// res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); +// while (nums[left] == nums[++left] && left < right); +// while (nums[right] == nums[--right] && left < right); +// } else if (sum < target) ++left; +// else --right; +// } +// while (nums[j] == nums[++j] && j < len - 2) ; +// } +// while (nums[i] == nums[++i] && i < len - 3) ; +// } +// return res; +// } + + public List> fourSum(int[] nums, int target) { + Arrays.sort(nums); + int len = nums.length; + if (len < 4) return Collections.emptyList(); + int max = nums[len - 1]; + if (4 * max < target) return Collections.emptyList(); + return kSum(nums, 0, 4, target); + } + + private List> kSum(int[] nums, int start, int k, int target) { + List> res = new ArrayList<>(); + if (k == 2) { + int left = start, right = nums.length - 1; + while (left < right) { + int sum = nums[left] + nums[right]; + if (sum == target) { + List twoSum = new LinkedList<>(); + twoSum.add(nums[left]); + twoSum.add(nums[right]); + res.add(twoSum); + while (nums[left] == nums[++left] && left < right) ; + while (nums[right] == nums[--right] && left < right) ; + } else if (sum < target) ++left; + else --right; + } + } else { + int i = start, end = nums.length - (k - 1), max = nums[nums.length - 1]; + while (i < end) { + if (nums[i] * k > target) return res; + if (nums[i] + (k - 1) * max < target) { + while (nums[i] == nums[++i] && i < end) ; + continue; + } + List> temp = kSum(nums, i + 1, k - 1, target - nums[i]); + for (List t : temp) { + t.add(0, nums[i]); + } + res.addAll(temp); + while (nums[i] == nums[++i] && i < end) ; + } + } + return res; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0)); + } +} 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/_0022/Solution.java b/src/com/blankj/medium/_0022/Solution.java new file mode 100644 index 00000000..fe47c46d --- /dev/null +++ b/src/com/blankj/medium/_0022/Solution.java @@ -0,0 +1,53 @@ +package com.blankj.medium._022; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2018/01/30
+ *     desc  :
+ * 
+ */ +public class Solution { +// public List generateParenthesis(int n) { +// List list = new ArrayList<>(); +// helper(list, "", 0, n); +// return list; +// } +// +// private void helper(List list, String str, int rightNeed, int leftRest) { +// if (rightNeed == 0 && leftRest == 0) { +// list.add(str); +// return; +// } +// if (rightNeed > 0) helper(list, str + ")", rightNeed - 1, leftRest); +// if (leftRest > 0) helper(list, str + "(", rightNeed + 1, leftRest - 1); +// } + + public List generateParenthesis(int n) { + HashMap> hashMap = new HashMap<>(); + hashMap.put(0, Collections.singletonList("")); + for (int i = 1; i <= n; i++) { + List list = new ArrayList<>(); + for (int j = 0; j < i; j++) { + for (String fj : hashMap.get(j)) { + for (String fi_j_1 : hashMap.get(i - j - 1)) { + list.add("(" + fj + ")" + fi_j_1);// calculate f(i) + } + } + } + hashMap.put(i, list); + } + return hashMap.get(n); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.generateParenthesis(3)); + } +} diff --git a/src/com/blankj/medium/_0024/Solution.java b/src/com/blankj/medium/_0024/Solution.java new file mode 100644 index 00000000..77f7e44c --- /dev/null +++ b/src/com/blankj/medium/_0024/Solution.java @@ -0,0 +1,39 @@ +package com.blankj.medium._024; + +import com.blankj.structure.ListNode; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2018/01/31
+ *     desc  :
+ * 
+ */ +public class Solution { +// public ListNode swapPairs(ListNode head) { +// if (head == null || head.next == null) return head; +// ListNode node = head.next; +// head.next = swapPairs(node.next); +// node.next = head; +// return node; +// } + + public ListNode swapPairs(ListNode head) { + ListNode preHead = new ListNode(0), cur = preHead; + preHead.next = head; + while (cur.next != null && cur.next.next != null) { + ListNode temp = cur.next.next; + cur.next.next = temp.next; + temp.next = cur.next; + cur.next = temp; + cur = cur.next.next; + } + return preHead.next; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + ListNode.print(solution.swapPairs(ListNode.createTestData("[1,2,3,4]"))); + } +} diff --git a/src/com/blankj/medium/_0029/Solution.java b/src/com/blankj/medium/_0029/Solution.java new file mode 100644 index 00000000..2802ace9 --- /dev/null +++ b/src/com/blankj/medium/_0029/Solution.java @@ -0,0 +1,35 @@ +package com.blankj.medium._029; + +/** + *
+ *     author: Blankj
+ *     blog  : http://blankj.com
+ *     time  : 2018/01/31
+ *     desc  :
+ * 
+ */ +public class Solution { + public int divide(int dividend, int divisor) { + if (dividend == Integer.MIN_VALUE && divisor == -1) { + return Integer.MAX_VALUE; + } + long dvd = Math.abs((long) dividend); + long dvr = Math.abs((long) divisor); + int res = 0; + while (dvd >= dvr) { + long temp = dvr, multiple = 1; + while (dvd >= temp << 1) { + temp <<= 1; + multiple <<= 1; + } + dvd -= temp; + res += multiple; + } + return (dividend < 0) ^ (divisor < 0) ? -res : res; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.divide(-2147483648, 1)); + } +} 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)); + } +}