diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2304249 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Created by .ignore support plugin (hsz.mobi) +out +#.idea +#*.iml +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + diff --git a/.idea/.name b/.idea/.name deleted file mode 100644 index 612003b..0000000 --- a/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -LeetCode \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 96cc43e..ab52643 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -1,22 +1,16 @@ - - - - - - - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml deleted file mode 100644 index e7bedf3..0000000 --- a/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..a444e6c --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..6560a98 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,36 @@ + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..712ab9d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/leetcode.iml b/.idea/leetcode.iml new file mode 100644 index 0000000..c05462b --- /dev/null +++ b/.idea/leetcode.iml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/leetcode/editor.xml b/.idea/leetcode/editor.xml new file mode 100644 index 0000000..63b52e6 --- /dev/null +++ b/.idea/leetcode/editor.xml @@ -0,0 +1,65 @@ + + + + + + \ No newline at end of file diff --git a/.idea/libraries/R_User_Library.xml b/.idea/libraries/R_User_Library.xml new file mode 100644 index 0000000..2778a36 --- /dev/null +++ b/.idea/libraries/R_User_Library.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 02642ab..5b2bcaf 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,19 +1,13 @@ - - + + - - - - - - - - - - - + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml index be74181..9dde46f 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -2,136 +2,294 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..4b16f3e --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,1115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1538116956860 + + + 1560552440693 + + + 1560553720936 + + + 1560578905864 + + + 1560740668169 + + + 1560770441688 + + + 1560826447783 + + + 1560861999518 + + + 1560952045089 + + + 1561124592731 + + + 1561243847752 + + + 1561271447940 + + + 1561275450672 + + + 1561275723339 + + + 1561275871683 + + + 1561346644159 + + + 1561383166917 + + + 1561501704159 + + + 1561557291820 + + + 1561558937387 + + + 1561559322984 + + + 1561588132148 + + + 1561589039263 + + + 1561589568459 + + + 1561726238525 + + + 1561813424767 + + + 1561874014119 + + + 1561875043413 + + + 1561876074854 + + + 1561989828558 + + + 1562096652490 + + + 1562098060496 + + + 1562099083958 + + + 1562156421698 + + + 1562158877596 + + + 1562160452469 + + + 1562201817392 + + + 1562412581818 + + + 1562414319581 + + + 1562418777061 + + + 1562469798363 + + + 1562474246972 + + + 1562590389745 + + + 1562591647675 + + + 1562677843655 + + + 1562681707711 + + + 1562736646315 + + + 1562737206620 + + + 1562738633183 + + + 1562853795057 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + file://$PROJECT_DIR$/【237】【Delete Node in a Linked List】/src/Solution.java + 19 + + + file://$PROJECT_DIR$/【278】【First Bad Version】/src/Solution.java + 20 + + + file://$PROJECT_DIR$/【080】【Remove Duplicates from Sorted Array II】/src/Solution.java + 14 + + + + file://$PROJECT_DIR$/[004][Median of Two Sorted Arrays]/src/Solution.java + 53 + + + file://$PROJECT_DIR$/[128][Longest Consecutive Sequence]/src/Solution.java + 52 + + + file://$PROJECT_DIR$/[031][Next Permutation]/src/Solution.java + 37 + + + file://$PROJECT_DIR$/[000][common]/src/MaxSubArray.java + 31 + + + file://$PROJECT_DIR$/[020][Valid Parentheses]/src/Solution.java + 35 + + + file://$PROJECT_DIR$/[075][Sort Colors]/src/Solution.java + 36 + + + file://$PROJECT_DIR$/[074][Search A 2D Matrix]/src/Solution.java + 36 + + + file://$PROJECT_DIR$/[078][Subsets]/src/Solution.java + 62 + + + + file://$PROJECT_DIR$/[131][Palindrome Partitioning]/src/Solution.java + 48 + + + file://$PROJECT_DIR$/[0122][Best Time to Buy and Sell Stock II]/src/Solution2.java + 49 + + + file://$PROJECT_DIR$/[0367][Valid Perfect Square]/src/Solution.java + 20 + + + file://$PROJECT_DIR$/[0383][Ransom Note]/src/Solution.java + 39 + + + file://$PROJECT_DIR$/[0173][Binary Search Tree Iterator]/src/Solution.java + 9 + + + file://$PROJECT_DIR$/[0173][Binary Search Tree Iterator]/src/Solution.java + 17 + + + file://$PROJECT_DIR$/[0173][Binary Search Tree Iterator]/src/Solution.java + 18 + + + file://$PROJECT_DIR$/[0173][Binary Search Tree Iterator]/src/Solution.java + 20 + + + file://$PROJECT_DIR$/[0173][Binary Search Tree Iterator]/src/Solution.java + 22 + + + file://$PROJECT_DIR$/[0173][Binary Search Tree Iterator]/src/Solution.java + 24 + + + file://$PROJECT_DIR$/[0173][Binary Search Tree Iterator]/src/Solution.java + 41 + + + file://$PROJECT_DIR$/[0401][Binary Watch]/src/Solution.java + 36 + + + file://$PROJECT_DIR$/[0429][N-ary Tree Level Order Traversal]/src/Main.java + 37 + + + file://$PROJECT_DIR$/[0429][N-ary Tree Level Order Traversal]/src/Solution.java + 27 + + + file://$PROJECT_DIR$/[0230][Kth Smallest Element in a BST]/src/Main.java + 17 + + + file://$PROJECT_DIR$/[0414][Third Maximum Number]/src/Main.java + 33 + + + file://$PROJECT_DIR$/[0414][Third Maximum Number]/src/Solution.java + 48 + + + file://$PROJECT_DIR$/[0415][Add Strings]/src/Main.java + 23 + + + file://$PROJECT_DIR$/[0476][Number Complement]/src/Main.java + 12 + + + file://$PROJECT_DIR$/[0287][Find the Duplicate Number]/src/Solution.java + 32 + + + file://$PROJECT_DIR$/[0496][Next Greater Element I]/src/Solution.java + 62 + + + file://$PROJECT_DIR$/[0496][Next Greater Element I]/src/Solution.java + 49 + + + file://$PROJECT_DIR$/[0241][Different Ways to Add Parentheses]/src/Solution.java + 76 + + + file://$PROJECT_DIR$/[0241][Different Ways to Add Parentheses]/src/Solution.java + 70 + + + file://$PROJECT_DIR$/[0427][Construct Quad Tree]/src/Solution.java + 44 + + + + file://$PROJECT_DIR$/[0207][Course Schedule]/src/Solution.java + 60 + + + file://$PROJECT_DIR$/[0459][Repeated Substring Pattern]/src/Solution.java + 43 + + + file://$PROJECT_DIR$/[0475][Heaters]/src/Solution.java + 47 + + + file://$PROJECT_DIR$/[0227][Basic Calculator II]/src/Solution.java + 52 + + + file://$PROJECT_DIR$/[0500][Keyboard Row]/src/Solution.java + 13 + + + file://$PROJECT_DIR$/[1089][Duplicate Zeros]/src/Solution.java + 6 + + + file://$PROJECT_DIR$/[0392][Is Subsequence]/src/Solution.java + 65 + + + file://$PROJECT_DIR$/[0441][Arranging Coins]/src/Solution.java + 66 + + + file://$PROJECT_DIR$/[0443][String Compression]/src/Solution.java + 57 + + + file://$PROJECT_DIR$/[0447][Number of Boomerangs]/src/Solution.java + 47 + + + file://$PROJECT_DIR$/[0447][Number of Boomerangs]/src/Solution.java + 65 + + + file://$PROJECT_DIR$/[0507][Perfect Number]/src/Solution.java + 13 + + + file://$PROJECT_DIR$/[0523][K Diff Pairs In An Array]/src/Solution.java + 19 + + + file://$PROJECT_DIR$/[0551][Student Attendance Record I]/src/Solution.java + 12 + + + file://$PROJECT_DIR$/[0566][Reshape the Matrix]/src/SolutionTest.java + 24 + + + file://$PROJECT_DIR$/[0572][Subtree of Another Tree]/src/Solution.java + 23 + + + + file://$PROJECT_DIR$/[0572][Subtree of Another Tree]/src/Solution.java + 32 + + + file://$PROJECT_DIR$/[0572][Subtree of Another Tree]/src/Solution.java + 42 + + + file://$PROJECT_DIR$/[0599][Minimum Index Sum of Two Lists]/src/Solution.java + 23 + + + file://$PROJECT_DIR$/[0605][Can Place Flowers]/src/Solution.java + 18 + + + file://$PROJECT_DIR$/[0643][Maximum Average Subarray I]/src/Solution.java + 19 + + + file://$PROJECT_DIR$/[0653][Two Sum IV - Input is a BST]/src/Solution.java + 49 + + + file://$PROJECT_DIR$/[0661][Image Smoother]/src/SolutionTest.java + 23 + + + file://$PROJECT_DIR$/[0661][Image Smoother]/src/Solution.java + 25 + + + file://$PROJECT_DIR$/[0671][Second Minimum Node In a Binary Tree]/src/Solution.java + 60 + + + file://$PROJECT_DIR$/[081][Search In Rotated Sorted Array II]/src/Solution2.java + 17 + + + + + file://$PROJECT_DIR$/[0095][Unique Binary Search Trees II]/src/Main.java + 16 + + + + + + + + + + \ No newline at end of file diff --git a/[0000][common]/[0000][common].iml b/[0000][common]/[0000][common].iml new file mode 100644 index 0000000..2c1c83e --- /dev/null +++ b/[0000][common]/[0000][common].iml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0000][common]/src/FileRename.java b/[0000][common]/src/FileRename.java new file mode 100644 index 0000000..7631cf7 --- /dev/null +++ b/[0000][common]/src/FileRename.java @@ -0,0 +1,30 @@ +import java.io.File; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-14 10:00 + **/ +public class FileRename { + public static void main(String[] args) { + String pathName = "/Users/wangjunchao/Project/leetcode"; + File path = new File("/Users/wangjunchao/Project/leetcode"); + + File[] files = path.listFiles(); + renameFile(files); + } + + public static void renameFile(File[] files) { + for (File f : files) { + if (f.isDirectory()) { + renameFile(f.listFiles()); + } + } + + for (File f : files) { + String name = f.getName(); + name = name.replaceFirst("\\[", "[0"); + System.out.println(name); + f.renameTo(new File(f.getParent() + "/" + name)); + } + } +} diff --git a/[0000][common]/src/MaxSubArray.java b/[0000][common]/src/MaxSubArray.java new file mode 100644 index 0000000..9a12bb0 --- /dev/null +++ b/[0000][common]/src/MaxSubArray.java @@ -0,0 +1,47 @@ +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-16 11:16 + **/ +public class MaxSubArray { + public int[] solve(int[] array) { + if (array == null || array.length < 1) { + return null; + } + + + // result[0] 最大的子数组和 + // result[1] 最大的子数组的起始位置 + // result[2] 最大的子数组的结束位置 + int[] result = {Integer.MIN_VALUE, -1, -1}; + + int sum = 0; + int begin = 0; + for (int i = 0; i < array.length; i++) { + if (sum >= 0) { + sum += array[i]; + } else { + sum = array[i]; + begin = i; + } + + if (result[0] <= sum) { + result[0] = sum; + result[1] = begin; + result[2] = i; + } + } + + return result; + } + + @Test + public void test1() { + MaxSubArray maxSubArray = new MaxSubArray(); + + System.out.println(Arrays.toString(maxSubArray.solve(new int[]{1, 2, 3, 4, 5, 6}))); + } +} diff --git a/[0000][common]/src/WithException.java b/[0000][common]/src/WithException.java new file mode 100644 index 0000000..3ad6864 --- /dev/null +++ b/[0000][common]/src/WithException.java @@ -0,0 +1,28 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-01 16:15 + **/ +public class WithException { + public static int withException() { + int i = 10; + try { + System.out.println("i in try block is: " + i); + i = i / 0; + return --i; + } catch (Exception e) { + System.out.println("i in catch - form try block is: " + i); + --i; + System.out.println("i in catch block is: " + i); + return --i; + } finally { + System.out.println("i in finally - from try or catch block is -- " + i); + --i; + System.out.println("i in finally block is -- " + i); + return --i; + } + } + + public static void main(String[] args) { + withException(); + } +} diff --git a/[0001][Two Sum]/[0001][Two Sum].iml b/[0001][Two Sum]/[0001][Two Sum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0001][Two Sum]/[0001][Two Sum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0001][Two Sum]/src/Main.java b/[0001][Two Sum]/src/Main.java new file mode 100644 index 0000000..da4a59c --- /dev/null +++ b/[0001][Two Sum]/src/Main.java @@ -0,0 +1,36 @@ +import org.junit.Test; + +/** + * Author: 王俊超 + * Date: 2015-06-18 + * Time: 09:17 + * Declaration: All Rights Reserved !!! + */ +public class Main { + @Test + public void test0() { + int[] result = new Solution().twoSum(new int[]{0, 4, 3, 0}, 0); + + System.out.println("[" + result[0] + " ," + result[1] + "]"); + } + + @Test + public void test1() { + int[] result = new Solution().twoSum(new int[]{3, 2, 4}, 6); + System.out.println("[" + result[0] + " ," + result[1] + "]"); + } + + @Test + public void test2() { + int[] result = new Solution().twoSum(new int[]{3, 2, 4}, 6); + System.out.println("[" + result[0] + " ," + result[1] + "]"); + } + + @Test + public void test3() { + int[] nums = {876, 879, 155, 291, 431, 296, 592, 965, 502, 173, 869, 504, 258, 342, 192, 478, 270, 341, 811, 794, 472, 625, 229, 829, 122, 858, 738, 481, 102, 946, 305, 399, 216, 752, 413, 352, 271, 193, 534, 508, 152, 989, 154, 456, 168, 510, 391, 28, 317, 409, 609, 532, 784, 160, 696, 105, 245, 231, 20, 17, 81, 781, 79, 816, 918, 838, 123, 602, 338, 997, 192, 947, 388, 515, 510, 441, 175, 539, 708, 980, 207, 336, 524, 610, 3, 427, 282, 84, 953, 855, 117, 737, 288, 371, 623, 484, 738, 874, 426, 202, 481, 132, 499, 500, 89, 786, 276, 221, 857, 398, 242, 639, 771, 149, 758, 775, 39, 836, 70, 903, 193, 959, 169, 851, 798, 815, 755, 498, 308, 70, 217, 765, 504, 498, 56, 547, 578, 977, 882, 909, 9, 874, 223, 39, 429, 982, 129, 712, 77, 996, 43, 613, 800, 810, 73, 993, 763, 978, 912, 255, 468, 937, 987, 701, 155, 347, 980, 147, 698, 41, 353, 178, 396, 241, 71, 482, 40, 593, 993, 959, 193, 544, 376, 752, 804, 194, 800, 837, 673, 261, 348, 963, 918, 217, 945, 271, 493, 538, 203, 54, 850, 753, 954, 312, 584, 399, 504, 62, 124, 790, 542, 239, 662, 410, 12, 362, 798, 726, 798, 780, 785, 737, 280, 931, 452, 643, 362, 190, 975, 520, 219, 330, 290, 451, 22, 756, 837, 787, 758, 661, 75, 697, 419, 485, 290, 84, 401, 447, 400, 311, 121, 216, 574, 724, 733, 496, 680, 831, 736, 43, 578, 201, 109, 197, 125, 66, 739, 339, 925, 148, 381, 513, 152, 305, 603, 516, 979, 133, 993, 430, 167, 826, 526, 290, 562, 559, 947, 448, 903, 289, 259, 221, 915, 71, 879, 639, 390, 588, 496, 430, 778, 722, 421, 821, 436, 621, 959, 728, 81, 117, 202, 17, 408, 829, 438, 970, 93, 738, 838, 902, 248, 128, 903, 800, 567, 829, 3, 407, 306, 773, 71, 323, 492, 305, 301, 28, 220, 455, 320, 478, 873, 483, 521, 260, 460, 342, 846, 577, 874, 530, 588, 965, 985, 606, 410, 443, 662, 81, 667, 27, 912, 602, 957, 822, 164, 489, 942, 414, 549, 991, 747, 680, 498, 831, 805, 89, 846, 467, 909, 7, 651, 250, 534, 984, 587, 348, 150, 329, 194, 20, 519, 250, 232, 224, 378, 539, 83, 177, 872, 130, 419, 387, 654, 917, 259, 447, 979, 184, 965, 51, 349, 422, 983, 682, 172, 177, 177, 484, 652, 930, 495, 65, 511, 318, 621, 297, 803, 476, 370, 826, 328, 150, 354, 393, 900, 340, 73, 781, 70, 260, 293, 862, 335, 395, 51, 326, 363, 78, 968, 446, 565, 683, 654, 767, 719, 324, 2, 617, 451, 56, 789, 464, 119, 53, 269, 369, 137, 612, 54, 217, 719, 823, 601, 663, 310, 594, 301, 636, 22, 333, 351, 126, 810, 812, 827, 634, 441, 534, 434, 967, 637, 795, 335, 965, 876, 778, 987, 217, 451, 264, 341, 566, 656, 612, 413, 682, 429, 161, 801, 167, 309, 846, 754, 541, 9, 711, 707, 848, 989, 580, 20, 431, 163, 252, 200, 54, 56, 666, 425, 592, 513, 230, 894, 20, 260, 282, 297, 129, 414, 326, 577, 184, 698, 620, 138, 131, 236, 848, 995, 879, 354, 107, 67, 92, 260, 531, 757, 640, 305, 848, 959, 416, 109, 513, 769, 131, 501, 197, 225, 358, 67, 663, 761, 742, 83, 648, 230, 59, 873, 231, 228, 470, 503, 615, 245, 258, 84, 832, 132, 156, 324, 27, 583, 766, 676, 130, 978, 306, 387, 733, 592, 763, 592, 487, 504, 493, 139, 897, 290, 432, 976, 946, 24, 586, 104, 648, 333, 2, 359, 166, 968, 990, 39, 353, 376, 839, 9, 75, 874, 203, 762, 489, 21, 14, 888, 570, 449, 539, 772, 919, 697, 883, 278, 18, 151, 113, 148, 330, 158, 772, 852, 93, 288, 213, 299, 338, 297, 862, 371, 708, 815, 108, 326, 115, 923, 541, 144, 521, 441, 99, 773, 950, 519, 948, 258, 328, 624, 936, 681, 935, 328, 70, 826, 110, 153, 236, 191, 222, 340, 653, 918, 976, 857, 184, 193, 397, 39, 190, 147, 763, 760, 95, 917, 559, 529, 680, 376, 389, 215, 705, 586, 205, 653, 324, 960, 33, 404, 888, 680, 95, 263, 860, 150, 683, 930, 588, 9, 690, 919, 745, 815, 331, 425, 879, 648, 398, 2, 997, 865, 429, 399, 264, 704, 699, 333, 126, 753, 565, 529, 35, 520, 94, 401, 552, 592, 543, 864, 23, 764, 763, 51, 631, 348, 198, 255, 73, 281, 996, 371, 23, 581, 84, 367, 469, 604, 716, 393, 942, 764, 239, 502, 501, 973, 438, 760, 398, 158, 853, 178, 348, 659, 1000, 739, 296, 444, 587, 528, 355, 867, 615, 847, 885, 160, 357, 618, 959, 330, 82, 182, 59, 224, 355, 250, 270, 447, 534, 97, 590, 284, 909, 406, 954, 419, 909, 158, 626, 818, 350, 994, 609, 540, 957, 152, 827, 830, 386, 380, 318, 580, 853, 440, 789, 432, 710, 955, 381, 241, 930, 880, 632, 750, 876, 189, 662, 127, 434, 38, 144, 20, 424, 27, 466, 538, 158, 416, 508, 990, 650, 698, 990, 970, 663, 121, 9, 713, 489, 977, 530, 694, 141, 930, 169, 695, 305, 567, 368, 777, 442, 668, 746, 618, 86, 592, 185, 328, 772, 213, 644, 440, 178, 243, 774, 467, 991, 455, 404, 919, 197, 830, 568, 661, 826, 841, 695, 52, 982, 515, 47, 47, 198, 9, 272, 425, 975, 472, 9, 302, 338, 470, 542, 247, 492, 367, 180, 708, 521, 592, 58, 572, 887, 670, 314, 191, 280, 256, 845, 971, 157, 725, 862, 452, 76, 200, 538, 44, 324, 992, 459, 196, 18, 64, 147, 423, 187, 191, 246, 305, 973, 802, 832, 436, 444, 242, 979, 351, 733, 459, 825, 833, 691, 372, 861, 617, 618, 190, 57, 848, 527, 56, 378, 533, 308, 430, 473, 701, 401, 871, 790, 459, 216, 983, 305, 61, 391, 251, 447, 661, 951, 150, 28, 572, 206, 299, 477, 703, 301, 227, 960, 866, 450, 335, 337, 852, 906, 956, 873, 893, 867, 196, 131, 456, 608, 688, 840, 569, 91, 922, 606, 961, 906, 836, 168, 838, 91, 607, 186, 754, 708, 477, 248, 138, 211, 458, 17, 509, 645, 629, 816, 47, 185, 661, 856, 508, 984, 320, 763, 297, 9, 446, 970, 472, 12, 386, 476, 686, 940, 387, 721, 546, 206, 110, 349, 88, 781, 150, 308, 136, 809, 670, 291, 767, 889, 926, 999, 832, 462, 706, 13, 9, 753, 458, 309, 984, 404, 801, 366, 56, 611, 38, 691, 174, 670, 306, 229, 12, 151, 697, 415, 180, 655, 418, 975, 781, 40, 448, 625, 775, 722, 350, 163, 397, 634, 102, 961, 322, 354, 836, 652, 877, 997, 397, 957, 640, 70, 467, 976, 901, 792, 173, 869, 248, 829, 919, 89, 324, 9, 639, 560, 744, 890, 846, 452, 197, 558, 756, 988, 771, 573, 494, 64, 423, 348, 296, 587, 327, 909, 371, 24, 369, 174, 132, 197, 412, 142, 257, 790, 770, 171, 875, 724, 608, 329, 256, 626, 868, 22, 311, 499, 933, 173, 78, 631, 931, 191, 132, 970, 194, 778, 33, 832, 75, 76, 63, 271, 905, 164, 970, 716, 216, 828, 56, 131, 898, 565, 791, 47, 634, 205, 118, 280, 605, 896, 433, 38, 39, 303, 242, 746, 673, 541, 759, 588, 990, 586, 244, 152, 586, 371, 666, 361, 691, 815, 658, 537, 371, 482, 656, 117, 316, 327, 368, 657, 848, 557, 761, 221, 147, 673, 945, 914, 976, 579, 804, 405, 182, 89, 429, 133, 485, 939, 586, 452, 20, 292, 108, 747, 188, 899, 293, 125, 976, 573, 162, 592, 880, 241, 685, 191, 539, 361, 430, 84, 791, 903, 475, 96, 388, 485, 416, 583, 944, 939, 987, 939, 545, 474, 272, 494, 664, 543, 480, 812, 212, 400, 728, 28, 379, 410, 127, 607, 59, 614, 883, 509, 695, 765, 533, 665, 754, 848, 268, 159, 678, 807, 325, 125, 92, 208, 216, 337, 697, 778, 466, 861, 22, 950, 74, 804, 925, 617, 159, 73, 676, 712, 558, 487, 711, 774, 383, 817, 737, 555, 811, 304, 743, 27, 67, 535, 426, 766, 615, 102, 437, 765, 291, 718, 641, 951, 255, 375, 442, 204, 108, 455, 592, 364, 457, 758, 486, 593, 780, 277, 789, 323, 404, 473, 258, 953, 318, 898, 555, 390, 727, 510, 783, 427, 806, 92, 33, 474, 858, 851, 783, 12, 752, 356, 942, 307, 235, 397, 915, 502, 939}; + int target = 28; + int[] result = new Solution().twoSum(nums, target); + System.out.println("[" + result[0] + " ," + result[1] + "]"); + } +} diff --git a/[0001][Two Sum]/src/Solution.java b/[0001][Two Sum]/src/Solution.java new file mode 100644 index 0000000..707bcc7 --- /dev/null +++ b/[0001][Two Sum]/src/Solution.java @@ -0,0 +1,74 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Author: 王俊超 + * Date: 2015-06-17 + * Time: 20:27 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + + /** + *
+     * Given an array of integers, find two numbers such that they add up to a specific target number.
+     * The function twoSum should return indices of the two numbers such that they add up to the target,
+     * where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
+     * are not zero-based.
+     * You may assume that each input would have exactly one solution.
+     *
+     * Input: numbers={2, 7, 11, 15}, target=9
+     * Output: index1=1, index2=2
+     *
+     * 题目大意
+     * 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
+     * 要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。
+     * 请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。你可以假设每一个输入肯定只有一个结果。
+     *
+     * 解题思路
+     * 创建一个辅助类数组,对辅助类进行排序,使用两个指针,开始时分别指向数组的两端,看这两个下标对应的值是否
+     * 等于目标值,如果等于就从辅助类中找出记录的下标,构造好返回结果,返回。如果大于就让右边的下标向左移,
+     * 进入下一次匹配,如果小于就让左边的下标向右移动,进入下一次匹配,直到所有的数据都处理完
+     * 
+ * + * @param nums + * @param target + * @return + */ + + public int[] twoSum(int[] nums, int target) { + int[] result = {0, 0}; + + // 因为无素可能会重复,用于记录元素出现的下标 + Map> map = new HashMap<>(nums.length); + + for (int i = 0; i < nums.length; i++) { + if (map.containsKey(nums[i])) { + map.get(nums[i]).add(i); + } else { + List list = new ArrayList<>(); + list.add(i); + map.put(nums[i], list); + } + } + + for (int num : nums) { + int gap = target - num; + if (map.containsKey(gap)) { + // 同样的元素最多只可以有两个 + if (gap == num && map.get(num).size() >= 2) { + List list = map.get(num); + result[0] = Math.min(list.get(0), list.get(1)); + result[1] = Math.max(list.get(0), list.get(1)); + } else if (gap != num) { + result[0] = Math.min(map.get(num).get(0), map.get(gap).get(0)); + result[1] = Math.max(map.get(num).get(0), map.get(gap).get(0)); + } + } + } + + return result; + } +} diff --git a/[0001][Two Sum]/src/Solution2.java b/[0001][Two Sum]/src/Solution2.java new file mode 100644 index 0000000..37103d1 --- /dev/null +++ b/[0001][Two Sum]/src/Solution2.java @@ -0,0 +1,94 @@ +import java.util.Arrays; + +/** + * Author: 王俊超 + * Date: 2015-06-17 + * Time: 20:27 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + private static class Node implements Comparable { + int val; + int idx; + + public Node() { + } + + public Node(int val, int idx) { + this.val = val; + this.idx = idx; + } + + @Override + public int compareTo(Node o) { + if (o == null) { + return -1; + } + return this.val - o.val; + } + } + + + /** + *
+     * Given an array of integers, find two numbers such that they add up to a specific target number.
+     * The function twoSum should return indices of the two numbers such that they add up to the target,
+     * where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
+     * are not zero-based.
+     * You may assume that each input would have exactly one solution.
+     *
+     * Input: numbers={2, 7, 11, 15}, target=9
+     * Output: index1=1, index2=2
+     *
+     * 题目大意
+     * 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
+     * 要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。
+     * 请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。你可以假设每一个输入肯定只有一个结果。
+     *
+     * 解题思路
+     * 创建一个辅助类数组,对辅助类进行排序,使用两个指针,开始时分别指向数组的两端,看这两个下标对应的值是否
+     * 等于目标值,如果等于就从辅助类中找出记录的下标,构造好返回结果,返回。如果大于就让右边的下标向左移,
+     * 进入下一次匹配,如果小于就让左边的下标向右移动,进入下一次匹配,直到所有的数据都处理完
+     * 
+ * + * @param nums + * @param target + * @return + */ + + public int[] twoSum(int[] nums, int target) { + int[] result = {0, 0}; + + Node[] tmp = new Node[nums.length]; + for (int i = 0; i < nums.length; i++) { + tmp[i] = new Node(nums[i], i); + } + + // 先排序,然后左右夹逼,排序O(n log n),左右夹逼O(n),最终O(n log n)。但是注 + // 意,这题需要返回的是下标,而不是数字本身,因此这个方法不好。 + Arrays.sort(tmp); + + int lo = 0; + int hi = nums.length - 1; + + + while (lo < hi) { + if (tmp[lo].val + tmp[hi].val == target) { + + if (tmp[lo].idx > tmp[hi].idx) { + result[0] = tmp[hi].idx + 1; + result[1] = tmp[lo].idx + 1; + } else { + result[0] = tmp[lo].idx + 1; + result[1] = tmp[hi].idx + 1; + } + break; + } else if (tmp[lo].val + tmp[hi].val > target) { + hi--; + } else { + lo++; + } + } + return result; + } +} diff --git a/[0002][Add Two Numbers]/[0002][Add Two Numbers].iml b/[0002][Add Two Numbers]/[0002][Add Two Numbers].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0002][Add Two Numbers]/[0002][Add Two Numbers].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0002][Add Two Numbers]/[0002][AddTwoNumbers].iml b/[0002][Add Two Numbers]/[0002][AddTwoNumbers].iml new file mode 100644 index 0000000..bdc5d75 --- /dev/null +++ b/[0002][Add Two Numbers]/[0002][AddTwoNumbers].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/src/ListNode.java" b/[0002][Add Two Numbers]/src/ListNode.java similarity index 100% rename from "\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/src/ListNode.java" rename to [0002][Add Two Numbers]/src/ListNode.java diff --git a/[0002][Add Two Numbers]/src/Solution.java b/[0002][Add Two Numbers]/src/Solution.java new file mode 100644 index 0000000..f785707 --- /dev/null +++ b/[0002][Add Two Numbers]/src/Solution.java @@ -0,0 +1,89 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:04 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * You are given two linked lists representing two non-negative numbers.
+     * 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.
+     * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
+     * Output: 7 -> 0 -> 8
+     *
+     * Ŀ
+     * ǸÿһڵһλǷ洢ģ
+     * һʾλһʾλӺͣʽء
+     *
+     * ˼·
+     * ӵһʼӣٳ10̣ΪһλӵĽλ
+     * ͬʱ¼ΪλĽһֱֱеĽ㶼ꡣ
+     * 
+ * + * @param l1 һ + * @param l2 ڶ + * @return + */ + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + + if (l1 == null) { + return l2; + } + + if (l2 == null) { + return l1; + } + + ListNode p1 = l1; + ListNode p2 = l2; + // ͷ + ListNode root = new ListNode(0); + ListNode r = root; + root.next = l1; + + // ʼλ + int carry = 0; + int sum; + while (p1 != null && p2 != null) { + sum = p1.val + p2.val + carry; + // λĽ + p1.val = sum % 10; + // νλ + carry = sum / 10; + + r.next = p1; + // ָһӵĽ + r = p1; + p1 = p1.next; + p2 = p2.next; + + } + + if (p1 == null) { + r.next = p2; + } else { + r.next = p1; + } + + // һӻнλ + if (carry == 1) { + // ʼʱr.nextǵһҪӵĽ + while (r.next != null && carry != 0) { + sum = r.next.val + carry; + r.next.val = sum % 10; + carry = sum / 10; + r = r.next; + } + + // ˻нλҪһµĽ + if (carry == 1) { + r.next = new ListNode(1); + } + } + + return root.next; + } +} diff --git a/[0003][Longest Substring Without Repeating Characters]/[0003][Longest Substring Without Repeating Characters].iml b/[0003][Longest Substring Without Repeating Characters]/[0003][Longest Substring Without Repeating Characters].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0003][Longest Substring Without Repeating Characters]/[0003][Longest Substring Without Repeating Characters].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0003][Longest Substring Without Repeating Characters]/src/Solution.java b/[0003][Longest Substring Without Repeating Characters]/src/Solution.java new file mode 100644 index 0000000..eac3c22 --- /dev/null +++ b/[0003][Longest Substring Without Repeating Characters]/src/Solution.java @@ -0,0 +1,94 @@ +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Author: + * Date: 2015-06-17 + * Time: 20:46 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a string, find the length of the longest substring without repeating characters.
+     * For example, the longest substring without repeating letters for "abcabcbb" is "abc",
+     * which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
+     *
+     * Ŀ⣺
+     * һַַеظӴ
+     *
+     * ˼·
+     * start¼Ŀʼλ
+     * ַǰַӿʼλstartʼѾֹʱӴʼλ+1mapеhashֵΪǰλá
+     *
+     * ԴеUTF-8ַ
+     * 
+ * + * @param s + * @return + */ + public int lengthOfLongestSubstring(String s) { + // ַ벻Ϸ + if (s == null) { + return 0; + } + + // ǰĿʼλ + int start = 0; + // + int result = 0; + // ʱǣ¼һηʵַλ + Map map = new HashMap<>(s.length()); + + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + // ַѾֹ(ڱǿλ)±start + if (map.containsKey(ch) && map.get(ch) >= start) { + start = map.get(ch) + 1; + } + // ûгֹķظӴij + else { + result = Math.max(result, i - start + 1); + } + + // ·ʼ¼ + map.put(ch, i); + } + return result; + } + + /** + * ֻASCIIַ + */ + public int lengthOfLongestSubstring2(String s) { + // ַ벻Ϸ + if (s == null) { + return 0; + } + + // ַǷֹҼ¼ǵһηʵԪصλ + int[] appear = new int[256]; + // ʼΪ-1 + Arrays.fill(appear, -1); + // ǰĿʼλ + int start = 0; + // + int result = 0; + + for (int i = 0; i < s.length(); i++) { + // ַѾֹ(ڱǿλ)±start + if (appear[s.charAt(i)] >= start) { + start = i + 1; + } + // ûгֹķظӴij + else { + result = Math.max(result, i - start + 1); + } + // ǵiַѾʹǵiλã + appear[s.charAt(i)] = i; + } + + return result; + } +} diff --git a/[0004][Median of Two Sorted Arrays]/[0004][Median of Two Sorted Arrays].iml b/[0004][Median of Two Sorted Arrays]/[0004][Median of Two Sorted Arrays].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0004][Median of Two Sorted Arrays]/[0004][Median of Two Sorted Arrays].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0004][Median of Two Sorted Arrays]/src/Main.java b/[0004][Median of Two Sorted Arrays]/src/Main.java new file mode 100644 index 0000000..06c2105 --- /dev/null +++ b/[0004][Median of Two Sorted Arrays]/src/Main.java @@ -0,0 +1,35 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-14 13:21 + **/ +public class Main { + + @Test + public void test() { + int[] nums1 = {1, 3}; + int[] nums2 = {2}; + Solution solution = new Solution(); + Assert.assertEquals(2, solution.findMedianSortedArrays(nums1, nums2), 0.000001); + } + + @Test + public void test2() { + int[] nums1 = {1, 2}; + int[] nums2 = {3, 4}; + Solution solution = new Solution(); + Assert.assertEquals(2.5, solution.findMedianSortedArrays(nums1, nums2), 0.000001); + } + + @Test + public void test3() { + int[] nums1 = {6}; + int[] nums2 = {1, 2, 3, 4, 5}; + Solution solution = new Solution(); + Assert.assertEquals(3.5, solution.findMedianSortedArrays(nums1, nums2), 0.000001); + } + + +} diff --git a/[0004][Median of Two Sorted Arrays]/src/Solution.java b/[0004][Median of Two Sorted Arrays]/src/Solution.java new file mode 100644 index 0000000..9547a99 --- /dev/null +++ b/[0004][Median of Two Sorted Arrays]/src/Solution.java @@ -0,0 +1,92 @@ +/** + * Author: + * Date: 2015-06-17 + * Time: 20:54 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * 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)).
+     *
+     * Ŀ⣺
+     * 飬λʱ临ӶΪO(log(m+n))
+     *
+     * ˼·
+     * ݹ
+     * 
+ * + * @param nums1 + * @param nums2 + * @return + */ + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int total = nums1.length + nums2.length; + if (total % 2 != 0) { + return findKth(nums1, 0, nums2, 0, total / 2 + 1); + } else { + return (findKth(nums1, 0, nums2, 0, total / 2) + + findKth(nums1, 0, nums2, 0, total / 2 + 1) + ) / 2.0; + } + } + + /** + * ҵkԪأk=1, 2, 3, ... + * + * @param nums1 1 + * @param start1 ʼλ1 + * @param nums2 2 + * @param start2 ʼλ2 + * @param k Ҫҵλλ + * @return + */ + public int findKth(int[] nums1, final int start1, + int[] nums2, final int start2, + final int k) { + // ҪҳСķǰ + if (nums1.length - start1 > nums2.length - start2) { + return findKth(nums2, start2, nums1, start1, k); + } + + // ԪصѾﵽĩβ + if (nums1.length == start1) { + return nums2[start2 + k - 1]; + } + + // һбȽС + if (k == 1) { + return Math.min(nums1[start1], nums2[start2]); + } + + + // num1, nums2иһ൱ÿζҪ1/4 + int half = Math.min(k / 2, nums1.length - start1); + // nums2пҵλ + int ia = half + start1; + // nums2пҵλ + int ib = k - half + start2; + + // nums1[start, ..., ia-1, ia, ..., nums1.length] + // nums2[start, ..., ib-1, ib, ..., nums2.length] + // ˵nums1[start, ..., ia-1]ˣҪҵֵnums1[ia, ..., nums1.length] + // nums2[start, ..., ib-1, ib, ..., nums2.length] + if (nums1[ia - 1] < nums2[ib - 1]) { + // k - (ia - start1) = k - (half + start1 - start1) = k - half + return findKth(nums1, ia, nums2, start2, k - (ia - start1)); + } + + // ˵nums2[start, ..., ib-1]ˣҪҵֵnums2[ib, ..., nums2.length] + // nums1[start, ..., ia-1, ia, ..., nums1.length] + else if (nums1[ia - 1] > nums2[ib - 1]) { + // k - (ib - start2) = k - (k - half + start2 - start2) + return findKth(nums1, start1, nums2, ib, half); + } + // ֵ˵ҵˣ + else { + return nums1[ia - 1]; + } + } +} diff --git a/[0004][Median of Two Sorted Arrays]/src/Solution2.java b/[0004][Median of Two Sorted Arrays]/src/Solution2.java new file mode 100644 index 0000000..601e821 --- /dev/null +++ b/[0004][Median of Two Sorted Arrays]/src/Solution2.java @@ -0,0 +1,79 @@ +/** + * Author: + * Date: 2015-06-17 + * Time: 20:54 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * 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)).
+     *
+     * Ŀ⣺
+     * 飬λʱ临ӶΪO(log(m+n))
+     *
+     * ˼·
+     * ݹ
+     * 
+ * + * @param nums1 + * @param nums2 + * @return + */ + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + + if (nums1 == null) { + nums1 = new int[0]; + } + + if (nums2 == null) { + nums2 = new int[0]; + } + + int len1 = nums1.length; + int len2 = nums2.length; + + if (len1 < len2) { + // ȷһȵڶ鳤ȴ + return findMedianSortedArrays(nums2, nums1); + } + + // С鳤Ϊ0ͷǰһλ + if (len2 == 0) { + return (nums1[(len1 - 1) / 2] + nums1[len1 / 2]) / 2.0; + } + + + int lo = 0; + int hi = len2 * 2; + int mid1; + int mid2; + double l1; + double l2; + double r1; + double r2; + + while (lo <= hi) { + mid2 = (lo + hi) / 2; + mid1 = len1 + len2 - mid2; + + l1 = (mid1 == 0) ? Integer.MIN_VALUE : nums1[(mid1 - 1) / 2]; + l2 = (mid2 == 0) ? Integer.MIN_VALUE : nums2[(mid2 - 1) / 2]; + + r1 = (mid1 == len1 * 2) ? Integer.MAX_VALUE : nums1[mid1 / 2]; + r2 = (mid2 == len2 * 2) ? Integer.MAX_VALUE : nums2[mid2 / 2]; + + if (l1 > r2) { + lo = mid2 + 1; + } else if (l2 > r1) { + hi = mid2 - 1; + } else { + return (Math.max(l1, l2) + Math.min(r1, r2)) / 2; + } + } + + return -1; + } +} diff --git a/[0005][Longest Palindromic Substring Total]/[0005][Longest Palindromic Substring Total].iml b/[0005][Longest Palindromic Substring Total]/[0005][Longest Palindromic Substring Total].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0005][Longest Palindromic Substring Total]/[0005][Longest Palindromic Substring Total].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/src/Main.java" b/[0005][Longest Palindromic Substring Total]/src/Main.java similarity index 100% rename from "\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/src/Main.java" rename to [0005][Longest Palindromic Substring Total]/src/Main.java diff --git a/[0005][Longest Palindromic Substring Total]/src/Solution.java b/[0005][Longest Palindromic Substring Total]/src/Solution.java new file mode 100644 index 0000000..7409c74 --- /dev/null +++ b/[0005][Longest Palindromic Substring Total]/src/Solution.java @@ -0,0 +1,82 @@ +/** + * Author: + * Date: 2015-06-17 + * Time: 21:24 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a string S, find the longest palindromic substring in S.
+     * You may assume that the maximum length of S is 1000, and there
+     * exists one unique longest palindromic substring.
+     *
+     * Ŀ⣺
+     * һַSҳĻӴԼַ󳤶1000
+     * ҴΨһӴ
+     *
+     * ˼·
+     * ̬滮
+     * dp[ i ][ j ]ֵΪtrueʾַs± i  j ַɵӴǻĴôƳ
+     * dp[ i ][ j ] = dp[ i + 1][ j - 1] && s[ i ] == s[ j ]
+     * һҪi+1, j -1п i + 1 = j -1, i +1 = (j - 1) -1
+     * Ҫ׼ϵĹʽ
+     *
+     * a. i + 1 = j -1ijΪ1ʱdp[ i ][ i ] = true;
+     * b. i +1 = (j - 1) -1ijΪ2ʱdp[ i ][ i + 1] = (s[ i ] == s[ i + 1])
+     *
+     * ϷͿдˡҪעǶ̬滮ҪO(n^2)Ŀռ䡣
+     * 
+ * + * @param s + * @return + */ + public String longestPalindrome(String s) { + + if (s == null || s.length() < 2) { + return s; + } + + int maxLength = 0; + String longest = null; + + int length = s.length(); + boolean[][] table = new boolean[length][length]; + + // ַǻ + for (int i = 0; i < length; i++) { + table[i][i] = true; + longest = s.substring(i, i + 1); + maxLength = 1; + } + + // жַǷǻ + for (int i = 0; i < length - 1; i++) { + if (s.charAt(i) == s.charAt(i + 1)) { + table[i][i + 1] = true; + longest = s.substring(i, i + 2); + maxLength = 2; + } + } + + + // 󳤶ȴ2ӴǷǻĴ + for (int len = 3; len <= length; len++) { + for (int i = 0, j; (j = i + len - 1) <= length - 1; i++) { + if (s.charAt(i) == s.charAt(j)) { + table[i][j] = table[i + 1][j - 1]; + if (table[i][j] && maxLength < len) { + longest = s.substring(i, j + 1); + maxLength = len; + } + } else { + table[i][j] = false; + } + } + } + + return longest; + } + + +} diff --git a/[0006][Zig Zag Conversion]/[0006][Zig Zag Conversion].iml b/[0006][Zig Zag Conversion]/[0006][Zig Zag Conversion].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0006][Zig Zag Conversion]/[0006][Zig Zag Conversion].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0006][Zig Zag Conversion]/src/Solution.java b/[0006][Zig Zag Conversion]/src/Solution.java new file mode 100644 index 0000000..0d5a31a --- /dev/null +++ b/[0006][Zig Zag Conversion]/src/Solution.java @@ -0,0 +1,94 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:08 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     *     ԭ
+     * 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
+     * APLSIIG
+     * Y I R
+     * And then read line by line: PAHNAPLSIIGYIR
+     * Write the code that will take a string and make this conversion given a number of rows:
+     * string convert(string text, int nRows);
+     * convert(PAYPALISHIRING,3) should return PAHNAPLSIIGYIR.
+     * Ŀ
+     * һַַָZ
+     *
+     * ˼·
+     * ַһһά飬ټÿַһάеλã
+     * ٶһάеַнղؽ
+     * 
+ * + * @param s + * @param nRows + * @return + */ + public String convert(String s, int nRows) { + + if (s == null || s.length() <= nRows || nRows == 1) { + return s; + } + + int index = s.length(); + int rowLength = 0; // еijȣַ + + int slash = nRows - 2; // һб߳ȥβռõ + + while (index > 0) { + // εһ + index -= nRows; + rowLength++; + + // бŵ + for (int i = 0; i < slash && index > 0; i++) { + rowLength++; + index--; + } + } + + char[] result = new char[nRows * rowLength]; // 飬һڱ滻з + for (int i = 0; i < result.length; i++) { // ʼΪո + result[i] = ' '; + } + + int curColumn = 0; // ǰ + index = 0; + while (index < s.length()) { + // + for (int i = 0; i < nRows && index < s.length(); i++) { + result[rowLength * i + curColumn] = s.charAt(index); + index++; + } + curColumn++; + // б + for (int i = nRows - 2; i > 0 && index < s.length(); i--) { + result[rowLength * i + curColumn] = s.charAt(index); + curColumn++; + index++; + } + } + + // ַнղ + index = 0; + while (index < s.length() && result[index] != ' ') { // ҵһǿոַλ + index++; + } + int next = index + 1; + while (index < s.length()) { + while (next < result.length && result[next] == ' ') { // ҲǿոԪ + next++; + } + result[index] = result[next]; + index++; + next++; + } + return new String(result, 0, index); + } +} diff --git a/[0007][Reverse Integer]/[0007][Reverse Integer].iml b/[0007][Reverse Integer]/[0007][Reverse Integer].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0007][Reverse Integer]/[0007][Reverse Integer].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220007\343\200\221\343\200\220ReverseInteger\343\200\221/src/Solution.java" b/[0007][Reverse Integer]/src/Solution.java similarity index 100% rename from "\343\200\220007\343\200\221\343\200\220ReverseInteger\343\200\221/src/Solution.java" rename to [0007][Reverse Integer]/src/Solution.java diff --git a/[0008][String To Integer (atoi)]/[0008][String To Integer (atoi)].iml b/[0008][String To Integer (atoi)]/[0008][String To Integer (atoi)].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0008][String To Integer (atoi)]/[0008][String To Integer (atoi)].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0008][String To Integer (atoi)]/src/Solution.java b/[0008][String To Integer (atoi)]/src/Solution.java new file mode 100644 index 0000000..5e1e1e1 --- /dev/null +++ b/[0008][String To Integer (atoi)]/src/Solution.java @@ -0,0 +1,104 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:13 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * ʵһatoiַת
+     * Ҫ㣺е
+     *
+     * ˼·
+     * ǰַ+-ûУֲ֣ܱʾС
+     * ͷضӦССֵ
+     * 
+ * + * @param str + * @return + */ + public int atoi(String str) { + + if (str == null || str.length() == 0) { +// throw new NumberFormatException("Invalid input string: " + str); + return 0; + } + + // ַԿոʼ + int start = 0; //ӿʼҵһǿո + boolean positive = true; // ǷΪĬΪtrue + + if (str.charAt(start) == ' ') { + while (str.charAt(start) == ' ') { + start++; + if (start >= str.length()) { // ȫǿո +// throw new NumberFormatException("Invalid input string: " + str); + return 0; + } + } + } + + if (str.charAt(start) == '-') { // һǿհַ- + positive = false; + start++; + } else if (str.charAt(start) == '+') {// һǿհַ+ + start++; + } else if (str.charAt(start) >= '0' && str.charAt(start) <= '9') { // һǿհַ + return cal(str, start, true); + } else { // ׳쳣 +// throw new NumberFormatException("Invalid input string: " + str); + return 0; + } + + + if (start >= str.length()) { // һǿհַ+-Ҳһַ +// throw new NumberFormatException("Invalid input string: " + str); + return 0; + } + + if (str.charAt(start) > '9' || str.charAt(start) < '0') { // +-ӵIJ +// throw new NumberFormatException("Invalid input string: " + str); + return 0; + } else { + return cal(str, start, positive); + } + } + + private int cal(String str, int start, boolean positive) { + + long result = 0; + while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') { + result = result * 10 + (str.charAt(start) - '0'); + + if (positive) { // + if (result > Integer.MAX_VALUE) { +// throw new NumberFormatException("Invalid input string: " + str); + return Integer.MAX_VALUE; + } + + } else { + if (-result < Integer.MIN_VALUE) { +// throw new NumberFormatException("Invalid input string: " + str); + return Integer.MIN_VALUE; + } + } + + start++; + } + + if (positive) { + return (int) result; + } else { + return (int) -result; + } + } +} diff --git a/[0009][Palindrome Number]/[0009][Palindrome Number].iml b/[0009][Palindrome Number]/[0009][Palindrome Number].iml new file mode 100644 index 0000000..73f33e3 --- /dev/null +++ b/[0009][Palindrome Number]/[0009][Palindrome Number].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0009][Palindrome Number]/src/Main.java b/[0009][Palindrome Number]/src/Main.java new file mode 100644 index 0000000..e04c77b --- /dev/null +++ b/[0009][Palindrome Number]/src/Main.java @@ -0,0 +1,13 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-16 11:06 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + System.out.println(solution.isPalindrome(123321)); + } +} diff --git a/[0009][Palindrome Number]/src/Solution.java b/[0009][Palindrome Number]/src/Solution.java new file mode 100644 index 0000000..c2e07ee --- /dev/null +++ b/[0009][Palindrome Number]/src/Solution.java @@ -0,0 +1,46 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:52 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Determine whether an integer is a palindrome. Do this without extra space.
+     *
+     * Ŀ
+     * жһǷǻطҪʹöĿռ䡣
+     *
+     * ˼·
+     * Ϊ˲ʹöĿռ䣬οĽЩⷨisPalindromeûʹö
+     * ȴʹ˷ãһĵĿռ ûдﵽĿҪǼٵʵ֣
+     * ԱȻһĿռʵ֡
+     *  ȣǻ֣ζֽת123321任˵ǻ֡
+     * 
+ * + * @param x + * @return + */ + public boolean isPalindrome(int x) { + + // ǻ + if (x < 0) { + return false; + } + + // תֵΪ˲ʹlong + long reverse = 0; + int tmp = x; + + // תֵ + while (tmp != 0) { + reverse = reverse * 10 + tmp % 10; + tmp /= 10; + } + + // жǷǻ + return x == reverse; + } +} diff --git a/[0010][Regular Expression Matching]/[0010][Regular Expression Matching].iml b/[0010][Regular Expression Matching]/[0010][Regular Expression Matching].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0010][Regular Expression Matching]/[0010][Regular Expression Matching].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/src/Main.java" b/[0010][Regular Expression Matching]/src/Main.java similarity index 100% rename from "\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/src/Main.java" rename to [0010][Regular Expression Matching]/src/Main.java diff --git a/[0010][Regular Expression Matching]/src/Solution.java b/[0010][Regular Expression Matching]/src/Solution.java new file mode 100644 index 0000000..8116492 --- /dev/null +++ b/[0010][Regular Expression Matching]/src/Solution.java @@ -0,0 +1,120 @@ +import java.util.Arrays; + +/** + * Author: + * Date: 2015-06-24 + * Time: 20:42 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * 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
+     *
+     * Ŀ⣺
+     * ʵһʽƥ㷨.ƥһַ*ƥ0߶ǰַ
+     *
+     * Կ˼·
+     * ע
+     *
+     * 
+ * + * @param s + * @param p + * @return + */ + public boolean isMatch(String s, String p) { + boolean[] match = new boolean[s.length() + 1]; + Arrays.fill(match, false); + match[s.length()] = true; + for (int i = p.length() - 1; i >= 0; i--) { + if (p.charAt(i) == '*') { + for (int j = s.length() - 1; j >= 0; j--) { + match[j] = match[j] || match[j + 1] + && (p.charAt(i - 1) == '.' || s.charAt(j) == p.charAt(i - 1)); + } + i--; + } else { + for (int j = 0; j < s.length(); j++) { + match[j] = match[j + 1] + && (p.charAt(i) == '.' || p.charAt(i) == s.charAt(j)); + } + + match[s.length()] = false; + } + } + return match[0]; + } + + // ĴʱȽϳ + public boolean isMatch2(String s, String p) { + // 붼Ϊnull + if (s == null && p == null) { + return true; + } + // һΪnull + else if (s == null || p == null) { + return false; + } + + return isMatch(s, 0, p, 0); + } + + /** + * ʽƥ + * + * @param s ƥ䴮 + * @param sIdx ǰƥλ + * @param p ģʽ + * @param pIdx ģʽƥλ + * @return ƥ + */ + public boolean isMatch(String s, int sIdx, String p, int pIdx) { + // ͬʱԵĩβ + if (s.length() == sIdx && p.length() == pIdx) { + return true; + } + // ƥ䴮ûеĩβģʽѾĩβ + else if (s.length() != sIdx && p.length() == pIdx) { + return false; + } + // + else { + // ǰƥһַ* + if (pIdx < p.length() - 1 && p.charAt(pIdx + 1) == '*') { + // ƥ䴮δҵǰַƥ䣨ַȻ.ţ + if (sIdx < s.length() && (s.charAt(sIdx) == p.charAt(pIdx) || p.charAt(pIdx) == '.')) { + return isMatch(s, sIdx + 1, p, pIdx + 2) // ƥ䴮ǰƶһַֻƥһΣ + || isMatch(s, sIdx + 1, p, pIdx) // ƥ䴮ǰƶһַһƥͬģģʽ + || isMatch(s, sIdx, p, pIdx + 2); // ƥģʽ + } else { + // * + return isMatch(s, sIdx, p, pIdx + 2); + } + } + + // ƥһַ + if (sIdx < s.length() && (s.charAt(sIdx) == p.charAt(pIdx) || p.charAt(pIdx) == '.')) { + return isMatch(s, sIdx + 1, p, pIdx + 1); + } + } + + return false; + } + +} diff --git a/[0011][Container With Most Water]/[0011][Container With Most Water].iml b/[0011][Container With Most Water]/[0011][Container With Most Water].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0011][Container With Most Water]/[0011][Container With Most Water].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0011][Container With Most Water]/src/Solution.java b/[0011][Container With Most Water]/src/Solution.java new file mode 100644 index 0000000..88407f0 --- /dev/null +++ b/[0011][Container With Most Water]/src/Solution.java @@ -0,0 +1,88 @@ +/** + * Author: + * Date: 2015-06-30 + * Time: 07:25 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * 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.
+     *
+     * Ŀ⣺
+     * ȻԼXṹɵˮ
+     *
+     * ˼·
+     * ʹ̰㷨
+     *      1.ȼҵȡݻΪ i, j (ٶi < j)
+     *      ôõݻ C = min( ai , aj ) * ( j- i) 
+     *
+     *      2.ǿôһʣ
+     *          :  j Ҷûһ߻ߣ k |( j < k && ak > aj) 
+     *          ô   ak > aj min(ai, aj, ak) =min(ai, aj) 
+     *          i, kɵݻC' = min(ai, aj) * (k - i) > C
+     *          CֵìܣԵ֤jĺ߲бߵߣ
+     *
+     *          :ͬiҲбߵߣ˵ʲôأ
+     *          Ŀǰõĺѡ Ϊ x, yߣx< y)ôܹõ
+     *          ݻµ߱Ȼ[x, y]ڲ ax' >= ax , ay' >= ay;
+     *
+     *      3.Ǵͷм俿£ͬʱºѡֵʱȴ
+     *      x, yнСı߿ʼ
+     * 
+ * + * @param height + * @return + */ + public int maxArea(int[] height) { + + // У + if (height == null || height.length < 2) { + return 0; + } + + + // ¼Ľ + int result = 0; + + // ߵ + int left = 0; + // ұߵ + int right = height.length - 1; + + while (left < right) { + // 㵱ǰֵ + result = Math.max(result, Math.min(height[left], height[right]) * (right - left)); + // ұ߸ + if (height[left] < height[right]) { + int k = left; + // [left, right - 1]Уңҵһ߶ȱheight[left]ߵλ + while (k < right && height[k] <= height[left]) { + k++; + } + + // [left, right - 1]У¼һԭheight[left]ߵλ + left = k; + } + // ߵ߸ + else { + int k = right; + // [left + 1, right]Уңҵһ߶ȱheight[right]ߵλ + while (k > left && height[k] <= height[right]) { + k--; + } + + // [left, right - 1]У¼һԭheight[right]ߵλ + right = k; + } + } + + return result; + } +} diff --git a/[0011][Container With Most Water]/src/Solution2.java b/[0011][Container With Most Water]/src/Solution2.java new file mode 100644 index 0000000..556a26a --- /dev/null +++ b/[0011][Container With Most Water]/src/Solution2.java @@ -0,0 +1,74 @@ +/** + * Author: + * Date: 2015-06-30 + * Time: 07:25 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * 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.
+     *
+     * Ŀ⣺
+     * ȻԼXṹɵˮ
+     *
+     * ˼·
+     * ʹ̰㷨
+     *      1.ȼҵȡݻΪ i, j (ٶi aj) 
+     *          ô   ak > aj min(ai, aj, ak) =min(ai, aj) 
+     *          i, kɵݻC' = min(ai, aj) * (k - i) > C
+     *          CֵìܣԵ֤jĺ߲бߵߣ
+     *
+     *          :ͬiҲбߵߣ˵ʲôأ
+     *          Ŀǰõĺѡ Ϊ x, yߣx< y)ôܹõ
+     *          ݻµ߱Ȼ[x, y]ڲ ax' >= ax , ay' >= ay;
+     *
+     *      3.Ǵͷм俿£ͬʱºѡֵʱȴ
+     *      x, yнСı߿ʼ
+     * 
+ * + * @param height + * @return + */ + public int maxArea(int[] height) { + + // У + if (height == null || height.length < 2) { + return 0; + } + + + // ¼Ľ + int result = 0; + + // ߵ + int left = 0; + // ұߵ + int right = height.length - 1; + + while (left < right) { + // 㵱ǰֵ + result = Math.max(result, Math.min(height[left], height[right]) * (right - left)); + // ұ߸ + if (height[left] < height[right]) { + left++; + } + // ߵ߸ + else { + right--; + } + } + + return result; + } +} diff --git a/[0012][Integer To Roman]/[0012][Integer To Roman].iml b/[0012][Integer To Roman]/[0012][Integer To Roman].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0012][Integer To Roman]/[0012][Integer To Roman].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0012][Integer To Roman]/src/Main.java b/[0012][Integer To Roman]/src/Main.java new file mode 100644 index 0000000..395df1b --- /dev/null +++ b/[0012][Integer To Roman]/src/Main.java @@ -0,0 +1,39 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 14:03 + **/ +public class Main { + + @Test + public void test1() { + Solution2 solution = new Solution2(); + Assert.assertEquals("III", solution.intToRoman(3)); + } + + @Test + public void test2() { + Solution2 solution = new Solution2(); + Assert.assertEquals("IV", solution.intToRoman(4)); + } + + @Test + public void test3() { + Solution2 solution = new Solution2(); + Assert.assertEquals("IX", solution.intToRoman(9)); + } + + @Test + public void test4() { + Solution2 solution = new Solution2(); + Assert.assertEquals("LVIII", solution.intToRoman(58)); + } + + @Test + public void test5() { + Solution2 solution = new Solution2(); + Assert.assertEquals("MCMXCIV", solution.intToRoman(1994)); + } +} diff --git "a/\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221/src/Solution.java" b/[0012][Integer To Roman]/src/Solution.java similarity index 100% rename from "\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221/src/Solution.java" rename to [0012][Integer To Roman]/src/Solution.java diff --git a/[0012][Integer To Roman]/src/Solution2.java b/[0012][Integer To Roman]/src/Solution2.java new file mode 100644 index 0000000..f13fad7 --- /dev/null +++ b/[0012][Integer To Roman]/src/Solution2.java @@ -0,0 +1,56 @@ +/** + * Author: + * Date: 2015-06-30 + * Time: 14:28 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * Given an integer, convert it to a roman numeral.
+     *
+     * Input is guaranteed to be within the range from 1 to 3999.
+     *
+     * ֵıʾ
+     * λ
+     * (I, 1)  (II, 2)  (III, 3)  (IV, 4)  (V, 5)  (VI, 6)  (VII, 7)  (VIII, 8)  (IX, 9)
+     *
+     * ʮλ
+     * (X, 10)  (XI, 11)  (XII, 12)  (XIII, 13)  (XIV, 14)  (XV, 15)  (XVI, 16)
+     * (XVII, 17)  (XVIII, 18)  (XIX, 19)  (XX, 20)  (XXI, 21)  (XXII, 22)
+     * (XXIX, 29)  (XXX, 30)  (XXXIV, 34)  (XXXV, 35)  (XXXIX, 39)  (XL, 40)
+     * (L, 50)  (LI, 51)  (LV, 55)  (LX, 60)  (LXV, 65)  (LXXX, 80)  (XC, 90)
+     * (XCIII, 93)  (XCV, 95)  (XCVIII, 98)  (XCIX, 99)
+     *
+     * λ
+     * (C, 100)  (CC, 200)  (CCC, 300)  (CD, 400)  (D, 500)  (DC, 600)  (DCC, 700)
+     * (DCCC, 800)  (CM, 900)  (CMXCIX, 999)
+     *
+     * ǧλ
+     * (M, 1000)  (MC, 1100)  (MCD, 1400)  (MD, 1500)  (MDC, 1600)  (MDCLXVI, 1666)
+     * (MDCCCLXXXVIII, 1888)  (MDCCCXCIX, 1899)  (MCM, 1900)  (MCMLXXVI, 1976)
+     * (MCMLXXXIV, 1984)  (MCMXC, 1990)  (MM, 2000)  (MMMCMXCIX, 3999)
+     *
+     * Ŀ⣺
+     * һ֣תһ֣[1, 3999]֮
+     *
+     * 
+ * + * @param num + * @return + */ + public String intToRoman(int num) { + + final int[] radix = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + final String[] symbol = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + String roman = ""; + for (int i = 0; num > 0; ++i) { + int count = num / radix[i]; + num %= radix[i]; + for (; count > 0; --count) { + roman += symbol[i]; + } + } + return roman; + } +} diff --git a/[0013][Roman To Integer]/[0013][Roman To Integer].iml b/[0013][Roman To Integer]/[0013][Roman To Integer].iml new file mode 100644 index 0000000..73f33e3 --- /dev/null +++ b/[0013][Roman To Integer]/[0013][Roman To Integer].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0013][Roman To Integer]/src/Main.java b/[0013][Roman To Integer]/src/Main.java new file mode 100644 index 0000000..5d7ae8a --- /dev/null +++ b/[0013][Roman To Integer]/src/Main.java @@ -0,0 +1,37 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * Author: 王俊超 + * Date: 2015-03-01 + * Time: 16:35 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + + System.out.println(solution.romanToInt("I")); + System.out.println(solution.romanToInt("II")); + System.out.println(solution.romanToInt("III")); + System.out.println(solution.romanToInt("IV")); + System.out.println(solution.romanToInt("V")); + System.out.println(solution.romanToInt("VI")); + + System.out.println(solution.romanToInt("XCVIII")); + System.out.println(solution.romanToInt("XCIX")); + + System.out.println(solution.romanToInt("CM")); + System.out.println(solution.romanToInt("CMXCIX")); + + System.out.println(solution.romanToInt("MDCLXVI")); + System.out.println(solution.romanToInt("MCMLXXVI")); + System.out.println(solution.romanToInt("MMMCMXCIX")); + } + + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(1994, solution.romanToInt("MCMXCIV")); + } +} diff --git a/[0013][Roman To Integer]/src/Solution.java b/[0013][Roman To Integer]/src/Solution.java new file mode 100644 index 0000000..eee8be3 --- /dev/null +++ b/[0013][Roman To Integer]/src/Solution.java @@ -0,0 +1,64 @@ +/** + * Author: 王俊超 + * Date: 2015-03-01 + * Time: 16:09 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * 原题
+     * Given a roman numeral, convert it to an integer.
+     * Input is guaranteed to be within the range from 1 to 3999.
+     *
+     * 题目大意
+     * 给定一个罗马数字,将其转换成对应的整数。
+     * 输入的数字在1-3999之间。
+     *
+     * 解题思路
+     * 从前往后扫描,用一个临时变量记录分段数字。
+     * 如果当前比前一个大,说明这一段的值应该是当前这个值减去上一个值。比如IV = 5 – 1;否
+     * 则,将当前值加入到结果中,然后开始下一段记录。比如VI = 5 + 1, II=1+1
+     * 
+ * + * @param s + * @return + */ + public int romanToInt(String s) { + + int result = 0; + + for (int i = 0; i < s.length(); i++) { + // 当前的值比前一个值大,说明[i-1, i]组成一个值,并且值是s[i-1]-s[i] + if (i > 0 && charToInt(s.charAt(i)) > charToInt(s.charAt(i - 1))) { + // 要减去两倍之前前值才能回到真实值 + result += charToInt(s.charAt(i)) - 2 * charToInt(s.charAt(i - 1)); + } else { + result += charToInt(s.charAt(i)); + } + } + + return result; + } + + private int charToInt(char c) { + switch (c) { + case 'I': + return 1; + case 'V': + return 5; + case 'X': + return 10; + case 'L': + return 50; + case 'C': + return 100; + case 'D': + return 500; + case 'M': + return 1000; + default: + return 0; + } + } +} diff --git a/[0013][Roman To Integer]/src/Solution2.java b/[0013][Roman To Integer]/src/Solution2.java new file mode 100644 index 0000000..9d08f55 --- /dev/null +++ b/[0013][Roman To Integer]/src/Solution2.java @@ -0,0 +1,98 @@ +/** + * Author: 王俊超 + * Date: 2015-03-01 + * Time: 16:09 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * 原题
+     * Given a roman numeral, convert it to an integer.
+     * Input is guaranteed to be within the range from 1 to 3999.
+     *
+     * 题目大意
+     * 给定一个罗马数字,将其转换成对应的整数。
+     * 输入的数字在1-3999之间。
+     *
+     * 解题思路
+     * 根据罗马数字与整数数字对应关系进行加法操作,如果前一个数字比后一个大就相减,否则进行相加。
+     * 
+ * + * @param s + * @return + */ + public int romanToInt(String s) { + + int result = 0; + int prev = 0; // 记录前一个数字的值 + + for (int i = s.length() - 1; i > -1; i--) { + switch (s.charAt(i)) { + case 'I': // 1 + if (1 < prev) { + result -= 1; + } else { + result += 1; + + } + prev = 1; + break; + + case 'V': // 5 + + if (5 < prev) { + result -= 5; + } else { + result += 5; + } + + prev = 5; + + break; + case 'X': // 10 + if (10 < prev) { + result -= 10; + } else { + result += 10; + } + + prev = 10; + break; + case 'L': // 50 + if (50 < prev) { + result -= 50; + } else { + result += 50; + } + + prev = 50; + break; + case 'C': // 100 + if (100 < prev) { + result -= 100; + } else { + result += 100; + } + + prev = 100; + break; + case 'D': // 500 + if (500 < prev) { + result -= 500; + } else { + result += 500; + } + + prev = 500; + break; + case 'M': // 1000 + result += 1000; + prev = 1000; + break; + } + } + + return result; + } +} diff --git a/[0014][Longest Common Prefix]/[0014][Longest Common Prefix].iml b/[0014][Longest Common Prefix]/[0014][Longest Common Prefix].iml new file mode 100644 index 0000000..73f33e3 --- /dev/null +++ b/[0014][Longest Common Prefix]/[0014][Longest Common Prefix].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0014][Longest Common Prefix]/src/Main.java b/[0014][Longest Common Prefix]/src/Main.java new file mode 100644 index 0000000..8b1b6f7 --- /dev/null +++ b/[0014][Longest Common Prefix]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 13:05 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals("fl", solution.longestCommonPrefix(new String[]{"flower", "flow", "flight"})); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals("", solution.longestCommonPrefix(new String[]{"dog", "racecar", "car"})); + } +} diff --git a/[0014][Longest Common Prefix]/src/Solution.java b/[0014][Longest Common Prefix]/src/Solution.java new file mode 100644 index 0000000..05c3523 --- /dev/null +++ b/[0014][Longest Common Prefix]/src/Solution.java @@ -0,0 +1,59 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:19 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Write a function to find the longest common prefix string amongst an array of strings.
+     *
+     * Ŀ
+     * дһҳһִеĹǰ׺
+     *
+     * ˼·
+     * һҳСַȻַַҳ̵ǰ׺
+     * 
+ * + * @param strs + * @return + */ + public String longestCommonPrefix(String[] strs) { + if (strs == null) { + return null; + } + + if (strs.length == 0) { + return ""; + } + + // ¼̵ַij + int min = Integer.MAX_VALUE; + + // Ҷַij + String result = ""; + for (String str : strs) { + + if (str == null || str.length() == 0) { + return ""; + } + + if (min > str.length()) { + min = str.length(); + result = str; + } + } + + for (String s : strs) { + for (int i = 0; i < result.length(); i++) { + if (result.charAt(i) != s.charAt(i)) { + result = result.substring(0, i); + } + } + } + + return result; + } +} diff --git a/[0014][Longest Common Prefix]/src/Solution2.java b/[0014][Longest Common Prefix]/src/Solution2.java new file mode 100644 index 0000000..17eb282 --- /dev/null +++ b/[0014][Longest Common Prefix]/src/Solution2.java @@ -0,0 +1,65 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:19 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * ԭ
+     * Write a function to find the longest common prefix string amongst an array of strings.
+     *
+     * Ŀ
+     * дһҳһִеĹǰ׺
+     *
+     * ˼·
+     * һҳСַȻַַҳ̵ǰ׺
+     * 
+ * + * @param strs + * @return + */ + public String longestCommonPrefix(String[] strs) { + if (strs == null) { + return null; + } + + if (strs.length == 0) { + return ""; + } + + // ¼̵ַij + int min = Integer.MAX_VALUE; + + // Ҷַij + for (String str : strs) { + + if (str == null) { + return null; + } + + if (min > str.length()) { + min = str.length(); + } + } + + int i; // ¼ǰ׺ַ + boolean flag; + for (i = 0; i < min; i++) { + flag = true; + for (int j = 1; j < strs.length; j++) { + if (strs[0].charAt(i) != strs[j].charAt(i)) { + flag = false; + break; + } + } + + if (!flag) { + break; + } + } + + return strs[0].substring(0, i); + } +} diff --git a/[0015][3 Sum]/[0015][3 Sum].iml b/[0015][3 Sum]/[0015][3 Sum].iml new file mode 100644 index 0000000..ec1ca74 --- /dev/null +++ b/[0015][3 Sum]/[0015][3 Sum].iml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0015][3 Sum]/src/Main.java b/[0015][3 Sum]/src/Main.java new file mode 100644 index 0000000..1b6cc33 --- /dev/null +++ b/[0015][3 Sum]/src/Main.java @@ -0,0 +1,53 @@ +import org.junit.Test; + +/** + * Author: + * Date: 2015-06-20 + * Time: 22:56 + * Declaration: All Rights Reserved !!! + */ +public class Main { + + @Test + public void test0() { + Solution solution = new Solution(); + System.out.println(solution.threeSum(new int[]{0, 0, 0})); + } + + @Test + public void test1() { + Solution solution = new Solution(); + System.out.println(solution.threeSum(new int[]{0, 0, 0, 0})); + } + + @Test + public void test2() { + Solution solution = new Solution(); + System.out.println(solution.threeSum(new int[]{1, -1, -1, 0})); + } + + @Test + public void test3() { + Solution solution = new Solution(); + System.out.println(solution.threeSum(new int[]{-2, 0, 1, 1, 2})); + } + + @Test + public void test4() { + Solution solution = new Solution(); + System.out.println(solution.threeSum(new int[]{-1, 0, 1, 2, -1, -4})); + } + + @Test + public void test5() { + Solution solution = new Solution(); + System.out.println(solution.threeSum(new int[]{82597, -9243, 62390, 83030, -97960, -26521, -61011, 83390, -38677, 12333, 75987, 46091, 83794, 19355, -71037, -6242, -28801, 324, 1202, -90885, -2989, -95597, -34333, 35528, 5680, 89093, -90606, 50360, -29393, -27012, 53313, 65213, 99818, -82405, -41661, -3333, -51952, 72135, -1523, 26377, 74685, 96992, 92263, 15929, 5467, -99555, -43348, -41689, -60383, -3990, 32165, 65265, -72973, -58372, 12741, -48568, -46596, 72419, -1859, 34153, 62937, 81310, -61823, -96770, -54944, 8845, -91184, 24208, -29078, 31495, 65258, 14198, 85395, 70506, -40908, 56740, -12228, -40072, 32429, 93001, 68445, -73927, 25731, -91859, -24150, 10093, -60271, -81683, -18126, 51055, 48189, -6468, 25057, 81194, -58628, 74042, 66158, -14452, -49851, -43667, 11092, 39189, -17025, -79173, 13606, 83172, 92647, -59741, 19343, -26644, -57607, 82908, -20655, 1637, 80060, 98994, 39331, -31274, -61523, 91225, -72953, 13211, -75116, -98421, -41571, -69074, 99587, 39345, 42151, -2460, 98236, 15690, -52507, -95803, -48935, -46492, -45606, -79254, -99851, 52533, 73486, 39948, -7240, 71815, -585, -96252, 90990, -93815, 93340, -71848, 58733, -14859, -83082, -75794, -82082, -24871, -15206, 91207, -56469, -93618, 67131, -8682, 75719, 87429, -98757, -7535, -24890, -94160, 85003, 33928, 75538, 97456, -66424, -60074, -8527, -28697, -22308, 2246, -70134, -82319, -10184, 87081, -34949, -28645, -47352, -83966, -60418, -15293, -53067, -25921, 55172, 75064, 95859, 48049, 34311, -86931, -38586, 33686, -36714, 96922, 76713, -22165, -80585, -34503, -44516, 39217, -28457, 47227, -94036, 43457, 24626, -87359, 26898, -70819, 30528, -32397, -69486, 84912, -1187, -98986, -32958, 4280, -79129, -65604, 9344, 58964, 50584, 71128, -55480, 24986, 15086, -62360, -42977, -49482, -77256, -36895, -74818, 20, 3063, -49426, 28152, -97329, 6086, 86035, -88743, 35241, 44249, 19927, -10660, 89404, 24179, -26621, -6511, 57745, -28750, 96340, -97160, -97822, -49979, 52307, 79462, 94273, -24808, 77104, 9255, -83057, 77655, 21361, 55956, -9096, 48599, -40490, -55107, 2689, 29608, 20497, 66834, -34678, 23553, -81400, -66630, -96321, -34499, -12957, -20564, 25610, -4322, -58462, 20801, 53700, 71527, 24669, -54534, 57879, -3221, 33636, 3900, 97832, -27688, -98715, 5992, 24520, -55401, -57613, -69926, 57377, -77610, 20123, 52174, 860, 60429, -91994, -62403, -6218, -90610, -37263, -15052, 62069, -96465, 44254, 89892, -3406, 19121, -41842, -87783, -64125, -56120, 73904, -22797, -58118, -4866, 5356, 75318, 46119, 21276, -19246, -9241, -97425, 57333, -15802, 93149, 25689, -5532, 95716, 39209, -87672, -29470, -16324, -15331, 27632, -39454, 56530, -16000, 29853, 46475, 78242, -46602, 83192, -73440, -15816, 50964, -36601, 89758, 38375, -40007, -36675, -94030, 67576, 46811, -64919, 45595, 76530, 40398, 35845, 41791, 67697, -30439, -82944, 63115, 33447, -36046, -50122, -34789, 43003, -78947, -38763, -89210, 32756, -20389, -31358, -90526, -81607, 88741, 86643, 98422, 47389, -75189, 13091, 95993, -15501, 94260, -25584, -1483, -67261, -70753, 25160, 89614, -90620, -48542, 83889, -12388, -9642, -37043, -67663, 28794, -8801, 13621, 12241, 55379, 84290, 21692, -95906, -85617, -17341, -63767, 80183, -4942, -51478, 30997, -13658, 8838, 17452, -82869, -39897, 68449, 31964, 98158, -49489, 62283, -62209, -92792, -59342, 55146, -38533, 20496, 62667, 62593, 36095, -12470, 5453, -50451, 74716, -17902, 3302, -16760, -71642, -34819, 96459, -72860, 21638, 47342, -69897, -40180, 44466, 76496, 84659, 13848, -91600, -90887, -63742, -2156, -84981, -99280, 94326, -33854, 92029, -50811, 98711, -36459, -75555, 79110, -88164, -97397, -84217, 97457, 64387, 30513, -53190, -83215, 252, 2344, -27177, -92945, -89010, 82662, -11670, 86069, 53417, 42702, 97082, 3695, -14530, -46334, 17910, 77999, 28009, -12374, 15498, -46941, 97088, -35030, 95040, 92095, -59469, -24761, 46491, 67357, -66658, 37446, -65130, -50416, 99197, 30925, 27308, 54122, -44719, 12582, -99525, -38446, -69050, -22352, 94757, -56062, 33684, -40199, -46399, 96842, -50881, -22380, -65021, 40582, 53623, -76034, 77018, -97074, -84838, -22953, -74205, 79715, -33920, -35794, -91369, 73421, -82492, 63680, -14915, -33295, 37145, 76852, -69442, 60125, -74166, 74308, -1900, -30195, -16267, -60781, -27760, 5852, 38917, 25742, -3765, 49097, -63541, 98612, -92865, -30248, 9612, -8798, 53262, 95781, -42278, -36529, 7252, -27394, -5021, 59178, 80934, -48480, -75131, -54439, -19145, -48140, 98457, -6601, -51616, -89730, 78028, 32083, -48904, 16822, -81153, -8832, 48720, -80728, -45133, -86647, -4259, -40453, 2590, 28613, 50523, -4105, -27790, -74579, -17223, 63721, 33489, -47921, 97628, -97691, -14782, -65644, 18008, -93651, -71266, 80990, -76732, -47104, 35368, 28632, 59818, -86269, -89753, 34557, -92230, -5933, -3487, -73557, -13174, -43981, -43630, -55171, 30254, -83710, -99583, -13500, 71787, 5017, -25117, -78586, 86941, -3251, -23867, -36315, 75973, 86272, -45575, 77462, -98836, -10859, 70168, -32971, -38739, -12761, 93410, 14014, -30706, -77356, -85965, -62316, 63918, -59914, -64088, 1591, -10957, 38004, 15129, -83602, -51791, 34381, -89382, -26056, 8942, 5465, 71458, -73805, -87445, -19921, -80784, 69150, -34168, 28301, -68955, 18041, 6059, 82342, 9947, 39795, 44047, -57313, 48569, 81936, -2863, -80932, 32976, -86454, -84207, 33033, 32867, 9104, -16580, -25727, 80157, -70169, 53741, 86522, 84651, 68480, 84018, 61932, 7332, -61322, -69663, 76370, 41206, 12326, -34689, 17016, 82975, -23386, 39417, 72793, 44774, -96259, 3213, 79952, 29265, -61492, -49337, 14162, 65886, 3342, -41622, -62659, -90402, -24751, 88511, 54739, -21383, -40161, -96610, -24944, -602, -76842, -21856, 69964, 43994, -15121, -85530, 12718, 13170, -13547, 69222, 62417, -75305, -81446, -38786, -52075, -23110, 97681, -82800, -53178, 11474, 35857, 94197, -58148, -23689, 32506, 92154, -64536, -73930, -77138, 97446, -83459, 70963, 22452, 68472, -3728, -25059, -49405, 95129, -6167, 12808, 99918, 30113, -12641, -26665, 86362, -33505, 50661, 26714, 33701, 89012, -91540, 40517, -12716, -57185, -87230, 29914, -59560, 13200, -72723, 58272, 23913, -45586, -96593, -26265, -2141, 31087, 81399, 92511, -34049, 20577, 2803, 26003, 8940, 42117, 40887, -82715, 38269, 40969, -50022, 72088, 21291, -67280, -16523, 90535, 18669, 94342, -39568, -88080, -99486, -20716, 23108, -28037, 63342, 36863, -29420, -44016, 75135, 73415, 16059, -4899, 86893, 43136, -7041, 33483, -67612, 25327, 40830, 6184, 61805, 4247, 81119, -22854, -26104, -63466, 63093, -63685, 60369, 51023, 51644, -16350, 74438, -83514, 99083, 10079, -58451, -79621, 48471, 67131, -86940, 99093, 11855, -22272, -67683, -44371, 9541, 18123, 37766, -70922, 80385, -57513, -76021, -47890, 36154, 72935, 84387, -92681, -88303, -7810, 59902, -90, -64704, -28396, -66403, 8860, 13343, 33882, 85680, 7228, 28160, -14003, 54369, -58893, 92606, -63492, -10101, 64714, 58486, 29948, -44679, -22763, 10151, -56695, 4031, -18242, -36232, 86168, -14263, 9883, 47124, 47271, 92761, -24958, -73263, -79661, -69147, -18874, 29546, -92588, -85771, 26451, -86650, -43306, -59094, -47492, -34821, -91763, -47670, 33537, 22843, 67417, -759, 92159, 63075, 94065, -26988, 55276, 65903, 30414, -67129, -99508, -83092, -91493, -50426, 14349, -83216, -76090, 32742, -5306, -93310, -60750, -60620, -45484, -21108, -58341, -28048, -52803, 69735, 78906, 81649, 32565, -86804, -83202, -65688, -1760, 89707, 93322, -72750, 84134, 71900, -37720, 19450, -78018, 22001, -23604, 26276, -21498, 65892, -72117, -89834, -23867, 55817, -77963, 42518, 93123, -83916, 63260, -2243, -97108, 85442, -36775, 17984, -58810, 99664, -19082, 93075, -69329, 87061, 79713, 16296, 70996, 13483, -74582, 49900, -27669, -40562, 1209, -20572, 34660, 83193, 75579, 7344, 64925, 88361, 60969, 3114, 44611, -27445, 53049, -16085, -92851, -53306, 13859, -33532, 86622, -75666, -18159, -98256, 51875, -42251, -27977, -18080, 23772, 38160, 41779, 9147, 94175, 99905, -85755, 62535, -88412, -52038, -68171, 93255, -44684, -11242, -104, 31796, 62346, -54931, -55790, -70032, 46221, 56541, -91947, 90592, 93503, 4071, 20646, 4856, -63598, 15396, -50708, 32138, -85164, 38528, -89959, 53852, 57915, -42421, -88916, -75072, 67030, -29066, 49542, -71591, 61708, -53985, -43051, 28483, 46991, -83216, 80991, -46254, -48716, 39356, -8270, -47763, -34410, 874, -1186, -7049, 28846, 11276, 21960, -13304, -11433, -4913, 55754, 79616, 70423, -27523, 64803, 49277, 14906, -97401, -92390, 91075, 70736, 21971, -3303, 55333, -93996, 76538, 54603, -75899, 98801, 46887, 35041, 48302, -52318, 55439, 24574, 14079, -24889, 83440, 14961, 34312, -89260, -22293, -81271, -2586, -71059, -10640, -93095, -5453, -70041, 66543, 74012, -11662, -52477, -37597, -70919, 92971, -17452, -67306, -80418, 7225, -89296, 24296, 86547, 37154, -10696, 74436, -63959, 58860, 33590, -88925, -97814, -83664, 85484, -8385, -50879, 57729, -74728, -87852, -15524, -91120, 22062, 28134, 80917, 32026, 49707, -54252, -44319, -35139, 13777, 44660, 85274, 25043, 58781, -89035, -76274, 6364, -63625, 72855, 43242, -35033, 12820, -27460, 77372, -47578, -61162, -70758, -1343, -4159, 64935, 56024, -2151, 43770, 19758, -30186, -86040, 24666, -62332, -67542, 73180, -25821, -27826, -45504, -36858, -12041, 20017, -24066, -56625, -52097, -47239, -90694, 8959, 7712, -14258, -5860, 55349, 61808, -4423, -93703, 64681, -98641, -25222, 46999, -83831, -54714, 19997, -68477, 66073, 51801, -66491, 52061, -52866, 79907, -39736, -68331, 68937, 91464, 98892, 910, 93501, 31295, -85873, 27036, -57340, 50412, 21, -2445, 29471, 71317, 82093, -94823, -54458, -97410, 39560, -7628, 66452, 39701, 54029, 37906, 46773, 58296, 60370, -61090, 85501, -86874, 71443, -72702, -72047, 14848, 34102, 77975, -66294, -36576, 31349, 52493, -70833, -80287, 94435, 39745, -98291, 84524, -18942, 10236, 93448, 50846, 94023, -6939, 47999, 14740, 30165, 81048, 84935, -19177, -13594, 32289, 62628, -90612, -542, -66627, 64255, 71199, -83841, -82943, -73885, 8623, -67214, -9474, -35249, 62254, -14087, -90969, 21515, -83303, 94377, -91619, 19956, -98810, 96727, -91939, 29119, -85473, -82153, -69008, 44850, 74299, -76459, -86464, 8315, -49912, -28665, 59052, -69708, 76024, -92738, 50098, 18683, -91438, 18096, -19335, 35659, 91826, 15779, -73070, 67873, -12458, -71440, -46721, 54856, 97212, -81875, 35805, 36952, 68498, 81627, -34231, 81712, 27100, -9741, -82612, 18766, -36392, 2759, 41728, 69743, 26825, 48355, -17790, 17165, 56558, 3295, -24375, 55669, -16109, 24079, 73414, 48990, -11931, -78214, 90745, 19878, 35673, -15317, -89086, 94675, -92513, 88410, -93248, -19475, -74041, -19165, 32329, -26266, -46828, -18747, 45328, 8990, -78219, -25874, -74801, -44956, -54577, -29756, -99822, -35731, -18348, -68915, -83518, -53451, 95471, -2954, -13706, -8763, -21642, -37210, 16814, -60070, -42743, 27697, -36333, -42362, 11576, 85742, -82536, 68767, -56103, -63012, 71396, -78464, -68101, -15917, -11113, -3596, 77626, -60191, -30585, -73584, 6214, -84303, 18403, 23618, -15619, -89755, -59515, -59103, -74308, -63725, -29364, -52376, -96130, 70894, -12609, 50845, -2314, 42264, -70825, 64481, 55752, 4460, -68603, -88701, 4713, -50441, -51333, -77907, 97412, -66616, -49430, 60489, -85262, -97621, -18980, 44727, -69321, -57730, 66287, -92566, -64427, -14270, 11515, -92612, -87645, 61557, 24197, -81923, -39831, -10301, -23640, -76219, -68025, 92761, -76493, 68554, -77734, -95620, -11753, -51700, 98234, -68544, -61838, 29467, 46603, -18221, -35441, 74537, 40327, -58293, 75755, -57301, -7532, -94163, 18179, -14388, -22258, -46417, -48285, 18242, -77551, 82620, 250, -20060, -79568, -77259, 82052, -98897, -75464, 48773, -79040, -11293, 45941, -67876, -69204, -46477, -46107, 792, 60546, -34573, -12879, -94562, 20356, -48004, -62429, 96242, 40594, 2099, 99494, 25724, -39394, -2388, -18563, -56510, -83570, -29214, 3015, 74454, 74197, 76678, -46597, 60630, -76093, 37578, -82045, -24077, 62082, -87787, -74936, 58687, 12200, -98952, 70155, -77370, 21710, -84625, -60556, -84128, 925, 65474, -15741, -94619, 88377, 89334, 44749, 22002, -45750, -93081, -14600, -83447, 46691, 85040, -66447, -80085, 56308, 44310, 24979, -29694, 57991, 4675, -71273, -44508, 13615, -54710, 23552, -78253, -34637, 50497, 68706, 81543, -88408, -21405, 6001, -33834, -21570, -46692, -25344, 20310, 71258, -97680, 11721, 59977, 59247, -48949, 98955, -50276, -80844, -27935, -76102, 55858, -33492, 40680, 66691, -33188, 8284, 64893, -7528, 6019, -85523, 8434, -64366, -56663, 26862, 30008, -7611, -12179, -70076, 21426, -11261, -36864, -61937, -59677, 929, -21052, 3848, -20888, -16065, 98995, -32293, -86121, -54564, 77831, 68602, 74977, 31658, 40699, 29755, 98424, 80358, -69337, 26339, 13213, -46016, -18331, 64713, -46883, -58451, -70024, -92393, -4088, 70628, -51185, 71164, -75791, -1636, -29102, -16929, -87650, -84589, -24229, -42137, -15653, 94825, 13042, 88499, -47100, -90358, -7180, 29754, -65727, -42659, -85560, -9037, -52459, 20997, -47425, 17318, 21122, 20472, -23037, 65216, -63625, -7877, -91907, 24100, -72516, 22903, -85247, -8938, 73878, 54953, 87480, -31466, -99524, 35369, -78376, 89984, -15982, 94045, -7269, 23319, -80456, -37653, -76756, 2909, 81936, 54958, -12393, 60560, -84664, -82413, 66941, -26573, -97532, 64460, 18593, -85789, -38820, -92575, -43663, -89435, 83272, -50585, 13616, -71541, -53156, 727, -27644, 16538, 34049, 57745, 34348, 35009, 16634, -18791, 23271, -63844, 95817, 21781, 16590, 59669, 15966, -6864, 48050, -36143, 97427, -59390, 96931, 78939, -1958, 50777, 43338, -51149, 39235, -27054, -43492, 67457, -83616, 37179, 10390, 85818, 2391, 73635, 87579, -49127, -81264, -79023, -81590, 53554, -74972, -83940, -13726, -39095, 29174, 78072, 76104, 47778, 25797, -29515, -6493, -92793, 22481, -36197, -65560, 42342, 15750, 97556, 99634, -56048, -35688, 13501, 63969, -74291, 50911, 39225, 93702, -3490, -59461, -30105, -46761, -80113, 92906, -68487, 50742, 36152, -90240, -83631, 24597, -50566, -15477, 18470, 77038, 40223, -80364, -98676, 70957, -63647, 99537, 13041, 31679, 86631, 37633, -16866, 13686, -71565, 21652, -46053, -80578, -61382, 68487, -6417, 4656, 20811, 67013, -30868, -11219, 46, 74944, 14627, 56965, 42275, -52480, 52162, -84883, -52579, -90331, 92792, 42184, -73422, -58440, 65308, -25069, 5475, -57996, 59557, -17561, 2826, -56939, 14996, -94855, -53707, 99159, 43645, -67719, -1331, 21412, 41704, 31612, 32622, 1919, -69333, -69828, 22422, -78842, 57896, -17363, 27979, -76897, 35008, 46482, -75289, 65799, 20057, 7170, 41326, -76069, 90840, -81253, -50749, 3649, -42315, 45238, -33924, 62101, 96906, 58884, -7617, -28689, -66578, 62458, 50876, -57553, 6739, 41014, -64040, -34916, 37940, 13048, -97478, -11318, -89440, -31933, -40357, -59737, -76718, -14104, -31774, 28001, 4103, 41702, -25120, -31654, 63085, -3642, 84870, -83896, -76422, -61520, 12900, 88678, 85547, 33132, -88627, 52820, 63915, -27472, 78867, -51439, 33005, -23447, -3271, -39308, 39726, -74260, -31874, -36893, 93656, 910, -98362, 60450, -88048, 99308, 13947, 83996, -90415, -35117, 70858, -55332, -31721, 97528, 82982, -86218, 6822, 25227, 36946, 97077, -4257, -41526, 56795, 89870, 75860, -70802, 21779, 14184, -16511, -89156, -31422, 71470, 69600, -78498, 74079, -19410, 40311, 28501, 26397, -67574, -32518, 68510, 38615, 19355, -6088, -97159, -29255, -92523, 3023, -42536, -88681, 64255, 41206, 44119, 52208, 39522, -52108, 91276, -70514, 83436, 63289, -79741, 9623, 99559, 12642, 85950, 83735, -21156, -67208, 98088, -7341, -27763, -30048, -44099, -14866, -45504, -91704, 19369, 13700, 10481, -49344, -85686, 33994, 19672, 36028, 60842, 66564, -24919, 33950, -93616, -47430, -35391, -28279, 56806, 74690, 39284, -96683, -7642, -75232, 37657, -14531, -86870, -9274, -26173, 98640, 88652, 64257, 46457, 37814, -19370, 9337, -22556, -41525, 39105, -28719, 51611, -93252, 98044, -90996, 21710, -47605, -64259, -32727, 53611, -31918, -3555, 33316, -66472, 21274, -37731, -2919, 15016, 48779, -88868, 1897, 41728, 46344, -89667, 37848, 68092, -44011, 85354, -43776, 38739, -31423, -66330, 65167, -22016, 59405, 34328, -60042, 87660, -67698, -59174, -1408, -46809, -43485, -88807, -60489, 13974, 22319, 55836, -62995, -37375, -4185, 32687, -36551, -75237, 58280, 26942, -73756, 71756, 78775, -40573, 14367, -71622, -77338, 24112, 23414, -7679, -51721, 87492, 85066, -21612, 57045, 10673, -96836, 52461, -62218, -9310, 65862, -22748, 89906, -96987, -98698, 26956, -43428, 46141, 47456, 28095, 55952, 67323, -36455, -60202, -43302, -82932, 42020, 77036, 10142, 60406, 70331, 63836, 58850, -66752, 52109, 21395, -10238, -98647, -41962, 27778, 69060, 98535, -28680, -52263, -56679, 66103, -42426, 27203, 80021, 10153, 58678, 36398, 63112, 34911, 20515, 62082, -15659, -40785, 27054, 43767, -20289, 65838, -6954, -60228, -72226, 52236, -35464, 25209, -15462, -79617, -41668, -84083, 62404, -69062, 18913, 46545, 20757, 13805, 24717, -18461, -47009, -25779, 68834, 64824, 34473, 39576, 31570, 14861, -15114, -41233, 95509, 68232, 67846, 84902, -83060, 17642, -18422, 73688, 77671, -26930, 64484, -99637, 73875, 6428, 21034, -73471, 19664, -68031, 15922, -27028, 48137, 54955, -82793, -41144, -10218, -24921, -28299, -2288, 68518, -54452, 15686, -41814, 66165, -72207, -61986, 80020, 50544, -99500, 16244, 78998, 40989, 14525, -56061, -24692, -94790, 21111, 37296, -90794, 72100, 70550, -31757, 17708, -74290, 61910, 78039, -78629, -25033, 73172, -91953, 10052, 64502, 99585, -1741, 90324, -73723, 68942, 28149, 30218, 24422, 16659, 10710, -62594, 94249, 96588, 46192, 34251, 73500, -65995, -81168, 41412, -98724, -63710, -54696, -52407, 19746, 45869, 27821, -94866, -76705, -13417, -61995, -71560, 43450, 67384, -8838, -80293, -28937, 23330, -89694, -40586, 46918, 80429, -5475, 78013, 25309, -34162, 37236, -77577, 86744, 26281, -29033, -91813, 35347, 13033, -13631, -24459, 3325, -71078, -75359, 81311, 19700, 47678, -74680, -84113, 45192, 35502, 37675, 19553, 76522, -51098, -18211, 89717, 4508, -82946, 27749, 85995, 89912, -53678, -64727, -14778, 32075, -63412, -40524, 86440, -2707, -36821, 63850, -30883, 67294, -99468, -23708, 34932, 34386, 98899, 29239, -23385, 5897, 54882, 98660, 49098, 70275, 17718, 88533, 52161, 63340, 50061, -89457, 19491, -99156, 24873, -17008, 64610, -55543, 50495, 17056, -10400, -56678, -29073, -42960, -76418, 98562, -88104, -96255, 10159, -90724, 54011, 12052, 45871, -90933, -69420, 67039, 37202, 78051, -52197, -40278, -58425, 65414, -23394, -1415, 6912, -53447, 7352, 17307, -78147, 63727, 98905, 55412, -57658, -32884, -44878, 22755, 39730, 3638, 35111, 39777, 74193, 38736, -11829, -61188, -92757, 55946, -71232, -63032, -83947, 39147, -96684, -99233, 25131, -32197, 24406, -55428, -61941, 25874, -69453, 64483, -19644, -68441, 12783, 87338, -48676, 66451, -447, -61590, 50932, -11270, 29035, 65698, -63544, 10029, 80499, -9461, 86368, 91365, -81810, -71914, -52056, -13782, 44240, -30093, -2437, 24007, 67581, -17365, -69164, -8420, -69289, -29370, 48010, 90439, 13141, 69243, 50668, 39328, 61731, 78266, -81313, 17921, -38196, 55261, 9948, -24970, 75712, -72106, 28696, 7461, 31621, 61047, 51476, 56512, 11839, -96916, -82739, 28924, -99927, 58449, 37280, 69357, 11219, -32119, -62050, -48745, -83486, -52376, 42668, 82659, 68882, 38773, 46269, -96005, 97630, 25009, -2951, -67811, 99801, 81587, -79793, -18547, -83086, 69512, 33127, -92145, -88497, 47703, 59527, 1909, 88785, -88882, 69188, -46131, -5589, -15086, 36255, -53238, -33009, 82664, 53901, 35939, -42946, -25571, 33298, 69291, 53199, 74746, -40127, -39050, 91033, 51717, -98048, 87240, 36172, 65453, -94425, -63694, -30027, 59004, 88660, 3649, -20267, -52565, -67321, 34037, 4320, 91515, -56753, 60115, 27134, 68617, -61395, -26503, -98929, -8849, -63318, 10709, -16151, 61905, -95785, 5262, 23670, -25277, 90206, -19391, 45735, 37208, -31992, -92450, 18516, -90452, -58870, -58602, 93383, 14333, 17994, 82411, -54126, -32576, 35440, -60526, -78764, -25069, -9022, -394, 92186, -38057, 55328, -61569, 67780, 77169, 19546, -92664, -94948, 44484, -13439, 83529, 27518, -48333, 72998, 38342, -90553, -98578, -76906, 81515, -16464, 78439, 92529, 35225, -39968, -10130, -7845, -32245, -74955, -74996, 67731, -13897, -82493, 33407, 93619, 59560, -24404, -57553, 19486, -45341, 34098, -24978, -33612, 79058, 71847, 76713, -95422, 6421, -96075, -59130, -28976, -16922, -62203, 69970, 68331, 21874, 40551, 89650, 51908, 58181, 66480, -68177, 34323, -3046, -49656, -59758, 43564, -10960, -30796, 15473, -20216, 46085, -85355, 41515, -30669, -87498, 57711, 56067, 63199, -83805, 62042, 91213, -14606, 4394, -562, 74913, 10406, 96810, -61595, 32564, 31640, -9732, 42058, 98052, -7908, -72330, 1558, -80301, 34878, 32900, 3939, -8824, 88316, 20937, 21566, -3218, -66080, -31620, 86859, 54289, 90476, -42889, -15016, -18838, 75456, 30159, -67101, 42328, -92703, 85850, -5475, 23470, -80806, 68206, 17764, 88235, 46421, -41578, 74005, -81142, 80545, 20868, -1560, 64017, 83784, 68863, -97516, -13016, -72223, 79630, -55692, 82255, 88467, 28007, -34686, -69049, -41677, 88535, -8217, 68060, -51280, 28971, 49088, 49235, 26905, -81117, -44888, 40623, 74337, -24662, 97476, 79542, -72082, -35093, 98175, -61761, -68169, 59697, -62542, -72965, 59883, -64026, -37656, -92392, -12113, -73495, 98258, 68379, -21545, 64607, -70957, -92254, -97460, -63436, -8853, -19357, -51965, -76582, 12687, -49712, 45413, -60043, 33496, 31539, -57347, 41837, 67280, -68813, 52088, -13155, -86430, -15239, -45030, 96041, 18749, -23992, 46048, 35243, -79450, 85425, -58524, 88781, -39454, 53073, -48864, -82289, 39086, 82540, -11555, 25014, -5431, -39585, -89526, 2705, 31953, -81611, 36985, -56022, 68684, -27101, 11422, 64655, -26965, -63081, -13840, -91003, -78147, -8966, 41488, 1988, 99021, -61575, -47060, 65260, -23844, -21781, -91865, -19607, 44808, 2890, 63692, -88663, -58272, 15970, -65195, -45416, -48444, -78226, -65332, -24568, 42833, -1806, -71595, 80002, -52250, 30952, 48452, -90106, 31015, -22073, 62339, 63318, 78391, 28699, 77900, -4026, -76870, -45943, 33665, 9174, -84360, -22684, -16832, -67949, -38077, -38987, -32847, 51443, -53580, -13505, 9344, -92337, 26585, 70458, -52764, -67471, -68411, -1119, -2072, -93476, 67981, 40887, -89304, -12235, 41488, 1454, 5355, -34855, -72080, 24514, -58305, 3340, 34331, 8731, 77451, -64983, -57876, 82874, 62481, -32754, -39902, 22451, -79095, -23904, 78409, -7418, 77916})); + } + + + @Test + public void test6() { + Solution solution = new Solution(); + System.out.println(solution.threeSum(new int[]{-1, 0, 1, 2, -1, -4})); + } +} diff --git a/[0015][3 Sum]/src/Solution.java b/[0015][3 Sum]/src/Solution.java new file mode 100644 index 0000000..5595514 --- /dev/null +++ b/[0015][3 Sum]/src/Solution.java @@ -0,0 +1,81 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-20 + * Time: 21:46 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * 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:
+     * Elements in a triplet (a,b,c) must be in non-descending order. (ie, a  b  c)
+     * 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)
+     *
+     * Ŀ⣺
+     *
+     * 
+ * + * @param nums + * @return + */ + public List> threeSum(int[] nums) { + List> result = new LinkedList<>(); + + if (nums == null || nums.length < 3) { + return result; + } + + Arrays.sort(nums); + int target = 0; + + int a = 0; + while (a < nums.length - 2) { + int b = a + 1; + int c = nums.length - 1; + while (b < c) { + if (nums[a] + nums[b] + nums[c] < target) { + do { + ++b; + } while (b < c && nums[b] == nums[b - 1]); + } else if (nums[a] + nums[b] + nums[c] > target) { + do { + --c; + } while (b < c && nums[c] == nums[c + 1]); + } else { + List idxs = new ArrayList<>(); + idxs.add(nums[a]); + idxs.add(nums[b]); + idxs.add(nums[c]); + result.add(idxs); + + do { + ++b; + } while (b < c && nums[b] == nums[b - 1]); + do { + --c; + } while (b < c && nums[c] == nums[c + 1]); + } + } + + // nums[a-1]Ѿѡˣѡ + do { + ++a; + } while (a < nums.length - 2 && nums[a - 1] == nums[a]); + } + return result; + } + +} diff --git a/[0015][3 Sum]/src/Solution2.java b/[0015][3 Sum]/src/Solution2.java new file mode 100644 index 0000000..f840265 --- /dev/null +++ b/[0015][3 Sum]/src/Solution2.java @@ -0,0 +1,119 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-20 + * Time: 21:46 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * 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:
+     * Elements in a triplet (a,b,c) must be in non-descending order. (ie, a  b  c)
+     * 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)
+     *
+     * Ŀ⣺
+     * һnԪص飬ǷabcԪأʹõa+b+c=0ҳзԪ
+     *
+     * ע⣺
+     *   - ԪеԪرǷǵݼ
+     *   - ܰظԪ
+     *
+     * ˼·
+     *  2sum Ļ3sum⣬3sumĿtargetÿδѡһk
+     * ʣµĿtarget-k2sum⡣ҪעиСtrickǴѡ
+     * iʱֻҪֵдӵi+1һΧ2sum⡣
+     *
+     * ѡһ͵ڶΪA[],ܹnԪA1A2....AnȻѡA1ʱ
+     * [A2~An]Ŀλtarget-A12sum⣬Ҫ֤ǵѡA2ʱֻҪ
+     * [A3~An]мĿλtarget-A22sum⣬[A1,A3~An]У֤£
+     * [A1,A3~An]Ŀλtarget-A22sumУA1 + m = target-A2mΪA3~An
+     * ijA2 + m = target-A1պǡ[A3~An],Ŀλtarget-A12sum⡱
+     * һ⡣൱ڶ3sumA1+A2+m = targetظˡΪ˱ظ㣬
+     * [A1A3~An]У԰A1ȥĿtarget-A22sum⡣
+     *
+     * ڱҪӽ⣬ֻҪ浱ǰԼǰĿľ룬µĽӽ½⡣
+     * 㷨ӶΪOn^2;
+     * 
+ * + * @param nums + * @return + */ + public List> threeSum(int[] nums) { + List> result = new LinkedList<>(); + + if (nums != null && nums.length > 2) { + // ȶ + Arrays.sort(nums); + // iʾȡiΪ + for (int i = 0; i < nums.length - 2; ) { + // ڶܵʼλ + int j = i + 1; + // ǽλ + int k = nums.length - 1; + + while (j < k) { + // ҵĽ + if (nums[j] + nums[k] == -nums[i]) { + // ӵ + List list = new ArrayList<>(3); + list.add(nums[i]); + list.add(nums[j]); + list.add(nums[k]); + result.add(list); + + // ƶһλãһ + k--; + j++; + + // ҵһ֮ǰͬ± + while (j < k && nums[j] == nums[j - 1]) { + j++; + } + // ҵһ֮ǰͬ± + while (j < k && nums[k] == nums[k + 1]) { + k--; + } + } + // ʹ0 + else if (nums[j] + nums[k] > -nums[i]) { + k--; + // ҵһ֮ǰͬ± + while (j < k && nums[k] == nums[k + 1]) { + k--; + } + } + // С0 + else { + j++; + // ҵһ֮ǰͬ± + while (j < k && nums[j] == nums[j - 1]) { + j++; + } + } + } + + // ָһҪ + i++; + // ҵһ֮ǰͬ± + while (i < nums.length - 2 && nums[i] == nums[i - 1]) { + i++; + } + } + } + + return result; + } +} diff --git a/[0015][3 Sum]/src/Solution3.java b/[0015][3 Sum]/src/Solution3.java new file mode 100644 index 0000000..b0419b1 --- /dev/null +++ b/[0015][3 Sum]/src/Solution3.java @@ -0,0 +1,68 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: 王俊超 + * Date: 2015-06-20 + * Time: 21:46 + * Declaration: All Rights Reserved !!! + */ +public class Solution3 { + /** + *
+     * 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:
+     * Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
+     * 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)
+     *
+     * 题目大意:
+     *
+     * 
+ * + * @param nums + * @return + */ + public List> threeSum(int[] nums) { + List> result = new LinkedList<>(); + + if (nums == null || nums.length < 3) { + return result; + } + + Arrays.sort(nums); + int target = 0; + for (int a = 0; a < nums.length - 2; ++a) { + + int b = a + 1; + int c = nums.length - 1; + while (b < c) { + if (nums[a] + nums[b] + nums[c] < target) { + ++b; + } else if (nums[a] + nums[b] + nums[c] > target) { + --c; + } else { + List idxs = new ArrayList<>(); + idxs.add(nums[a]); + idxs.add(nums[b]); + idxs.add(nums[c]); + if (!result.contains(idxs)) { + result.add(idxs); + } + ++b; + --c; + } + } + } + return result; + } + +} \ No newline at end of file diff --git a/[0016][3 Sum Closest]/[0016][3 Sum Closest].iml b/[0016][3 Sum Closest]/[0016][3 Sum Closest].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0016][3 Sum Closest]/[0016][3 Sum Closest].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0016][3 Sum Closest]/[0016][3SumClosest].iml b/[0016][3 Sum Closest]/[0016][3SumClosest].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0016][3 Sum Closest]/[0016][3SumClosest].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0016][3 Sum Closest]/src/Main.java b/[0016][3 Sum Closest]/src/Main.java new file mode 100644 index 0000000..86ada0f --- /dev/null +++ b/[0016][3 Sum Closest]/src/Main.java @@ -0,0 +1,12 @@ +/** + * Author: + * Date: 2015-06-21 + * Time: 09:58 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.threeSumClosest(new int[]{0, 1, 2}, 3)); + } +} diff --git a/[0016][3 Sum Closest]/src/Solution.java b/[0016][3 Sum Closest]/src/Solution.java new file mode 100644 index 0000000..42019e7 --- /dev/null +++ b/[0016][3 Sum Closest]/src/Solution.java @@ -0,0 +1,96 @@ +import java.util.Arrays; + +/** + * Author: + * Date: 2015-06-21 + * Time: 09:29 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given an array S of n integers, find three integers in S such that the sum is
+     * closest to a given number, target. Return the sum of the three integers. You
+     * may assume that each input would have exactly one solution.
+     *
+     * For example,
+     * given array S = {-1 2 1 -4}, and target = 1.
+     * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
+     *
+     * Ŀ⣺
+     * nSҵSеӶʹ֮ӽ
+     * ܺ͡Լÿ뽫һȷеĽ
+     *
+     * ˼·
+     * 3sum
+     * 
+ * + * @param nums + * @param target + * @return + */ + public int threeSumClosest(int[] nums, int target) { + + // ¼СIJֵ + long minDiff = Long.MAX_VALUE; + // ¼СֵӦͺ + long result = 0; + // ÿõIJֵ + long diff; + // ÿõĺ + long sum; + + // ȶ + Arrays.sort(nums); + + + // iʾȡiΪ + for (int i = 0; i < nums.length - 2; ) { + // ڶܵʼλ + int j = i + 1; + // ǽλ + int k = nums.length - 1; + + while (j < k) { + // ǰĺ + sum = nums[j] + nums[k] + nums[i]; + // ǰĿ֮IJֵ + diff = Math.abs(target - sum); + + // ֵΪ0ֱӷ + if (diff == 0) { + return (int) sum; + } + + // ǰIJֵ֮ǰ¼IJֵС + if (diff < minDiff) { + // СIJֵ + minDiff = diff; + // СֵӦĺ + result = sum; + + // ϵһԪشʱЧ + } + + // ʹtarget + if (sum > target) { + do { + k--; // ҵֵͬ + } while (j < k && nums[k] == nums[k + 1]); + } + // Сtarget + else { + do { + j++; + } while (j < k && nums[j - 1] == nums[j]); + } + } + + do { + i++; + } while (i < nums.length - 2 && nums[i - 1] == nums[i]); + } + + return (int) result; + } +} diff --git a/[0016][3 Sum Closest]/src/Solution2.java b/[0016][3 Sum Closest]/src/Solution2.java new file mode 100644 index 0000000..1ed9f61 --- /dev/null +++ b/[0016][3 Sum Closest]/src/Solution2.java @@ -0,0 +1,89 @@ +import java.util.Arrays; + +/** + * Author: + * Date: 2015-06-21 + * Time: 09:29 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * Given an array S of n integers, find three integers in S such that the sum is
+     * closest to a given number, target. Return the sum of the three integers. You
+     * may assume that each input would have exactly one solution.
+     *
+     * For example,
+     * given array S = {-1 2 1 -4}, and target = 1.
+     * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
+     *
+     * Ŀ⣺
+     * nSҵSеӶʹ֮ӽ
+     * ܺ͡Լÿ뽫һȷеĽ
+     *
+     * ˼·
+     * 3sum
+     * 
+ * + * @param nums + * @param target + * @return + */ + public int threeSumClosest(int[] nums, int target) { + + // ¼СIJֵ + long minDiff = Long.MAX_VALUE; + // ¼СֵӦͺ + long result = 0; + // ÿõIJֵ + long diff; + // ÿõĺ + long sum; + + // ȶ + Arrays.sort(nums); + + + // iʾȡiΪ + for (int i = 0; i < nums.length - 2; i++) { + // ڶܵʼλ + int j = i + 1; + // ǽλ + int k = nums.length - 1; + + while (j < k) { + // ǰĺ + sum = nums[j] + nums[k] + nums[i]; + // ǰĿ֮IJֵ + diff = Math.abs(target - sum); + + // ֵΪ0ֱӷ + if (diff == 0) { + return (int) sum; + } + + // ǰIJֵ֮ǰ¼IJֵС + if (diff < minDiff) { + // СIJֵ + minDiff = diff; + // СֵӦĺ + result = sum; + + // ϵһԪشʱЧ + } + + + // ʹtarget + if (sum > target) { + k--; + } + // Сtarget + else { + j++; + } + } + } + + return (int) result; + } +} diff --git a/[0017][Letter Combinations Of A Phone Number/[0017][Letter Combinations Of A Phone Number.iml b/[0017][Letter Combinations Of A Phone Number/[0017][Letter Combinations Of A Phone Number.iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0017][Letter Combinations Of A Phone Number/[0017][Letter Combinations Of A Phone Number.iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0017][Letter Combinations Of A Phone Number/src/Main.java b/[0017][Letter Combinations Of A Phone Number/src/Main.java new file mode 100644 index 0000000..d120486 --- /dev/null +++ b/[0017][Letter Combinations Of A Phone Number/src/Main.java @@ -0,0 +1,14 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 19:26 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + System.out.println(solution.letterCombinations("23")); + } +} diff --git a/[0017][Letter Combinations Of A Phone Number/src/Solution.java b/[0017][Letter Combinations Of A Phone Number/src/Solution.java new file mode 100644 index 0000000..d9ec4a0 --- /dev/null +++ b/[0017][Letter Combinations Of A Phone Number/src/Solution.java @@ -0,0 +1,74 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 16:23 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + + private final static String[] S = { + "abc", + "def", + "ghi", + "jkl", + "mno", + "pqrs", + "tuv", + "wxyz", + }; + + + /** + *
+     * ԭ
+     * Given a digit string, return all possible letter combinations that the number could represent.
+     * A mapping of digit to letters (just like on the telephone buttons) is given below.
+     *
+     * Input:Digit string "23"
+     * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
+     *
+     * Note: Although the above answer is in lexicographical order, your answer
+     * could be in any order you want.
+     *
+     * Ŀ
+     * һִַϣֵַӳͼʾ
+     * ע⣺ Ľַ˳еģκ˳򷵻ؽ
+     *
+     * ˼·
+     * һ鱣ֵֺӳϵִ룬ҵӦַϽ
+     * 
+ * + * @param digits + * @return + */ + public List letterCombinations(String digits) { + List result = new LinkedList<>(); + + if (digits == null || digits.length() < 1) { + return result; + } + + StringBuilder builder = new StringBuilder(); + letterCombinations(digits, 0, builder, result); + + return result; + } + + private void letterCombinations(String digits, int index, StringBuilder builder, List result) { + if (index == digits.length()) { + result.add(builder.toString()); + return; + } + + String t = S[digits.charAt(index) - '2']; + + for (int i = 0; i < t.length(); i++) { + builder.append(t.charAt(i)); + letterCombinations(digits, index + 1, builder, result); + builder.deleteCharAt(builder.length() - 1); + } + } +} diff --git a/[0017][Letter Combinations Of A Phone Number/src/Solution2.java b/[0017][Letter Combinations Of A Phone Number/src/Solution2.java new file mode 100644 index 0000000..4dc400d --- /dev/null +++ b/[0017][Letter Combinations Of A Phone Number/src/Solution2.java @@ -0,0 +1,95 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 16:23 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + + private String[] map = { + "abc", + "def", + "ghi", + "jkl", + "mno", + "pqrs", + "tuv", + "wxyz", + }; + private List result; // 洢ս + private char[] chars; // ȥ01ַĽ + private char[] curResult; // 洢м + private int end = 0; // ַеĵһδʹõλ + private int handle = 0; // ǰǵڼַ + + /** + *
+     * ԭ
+     * Given a digit string, return all possible letter combinations that the number could represent.
+     * A mapping of digit to letters (just like on the telephone buttons) is given below.
+     *
+     * Input:Digit string "23"
+     * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
+     *
+     * Note: Although the above answer is in lexicographical order, your answer
+     * could be in any order you want.
+     *
+     * Ŀ
+     * һִַϣֵַӳͼʾ
+     * ע⣺ Ľַ˳еģκ˳򷵻ؽ
+     *
+     * ˼·
+     * һ鱣ֵֺӳϵִ룬ҵӦַϽ
+     * 
+ * + * @param digits + * @return + */ + public List letterCombinations(String digits) { + result = new LinkedList<>(); + + if (digits != null && digits.length() > 0) { + + chars = digits.toCharArray(); + + // ַдȥ01 + // ҵһ01λ + while (end < digits.length() && chars[end] != '0' && chars[end] != '1') { + end++; + } + + handle = end + 1; + while (handle < chars.length) { + if (chars[handle] != '0' && chars[handle] != '1') { + chars[end] = chars[handle]; + end++; + } + handle++; + } + + curResult = new char[end]; + // whileendΪЧַij + handle = 0; // ָһЧַλ + + letterCombinations(); + } + return result; + } + + private void letterCombinations() { + if (handle >= end) { + result.add(new String(curResult)); + } else { + int num = chars[handle] - '2'; + for (int i = 0; i < map[num].length(); i++) { + curResult[handle] = map[num].charAt(i); + handle++; + letterCombinations(); + handle--; + } + } + } +} diff --git "a/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/src/phone-number.png" b/[0017][Letter Combinations Of A Phone Number/src/phone-number.png similarity index 100% rename from "\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/src/phone-number.png" rename to [0017][Letter Combinations Of A Phone Number/src/phone-number.png diff --git a/[0018][4 Sum]/[0018][4 Sum].iml b/[0018][4 Sum]/[0018][4 Sum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0018][4 Sum]/[0018][4 Sum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0018][4 Sum]/src/Solution.java b/[0018][4 Sum]/src/Solution.java new file mode 100644 index 0000000..6d14161 --- /dev/null +++ b/[0018][4 Sum]/src/Solution.java @@ -0,0 +1,105 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 16:28 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given an array S of n integers, are there elements a, b, c, and d in S
+     * such that a + b + c + d = target? Find all unique quadruplets in the array
+     * which gives the sum of target.
+     * Note:
+     * Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a  b  c  d)
+     * The solution set must not contain duplicate quadruplets.
+     *
+     * For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
+     *
+     * A solution set is:
+     * (-1,  0, 0, 1)
+     * (-2, -1, 1, 2)
+     * (-2,  0, 0, 2)
+     *
+     * Ŀ
+     * һ飬ҳa + b + c + d = targetΨһ⡣
+     *
+     * ˼·
+     * ȷadadͬʱظʹáȻȷbcͬҲ
+     * ͬʱظʹáҳĽ⣬ͬʱԱ֤ⲻظ
+     * 
+ * + * @param num + * @param target + * @return + */ + public List> fourSum(int[] num, int target) { + List> result = new LinkedList<>(); + if (num == null || num.length < 4) { + return result; + } + + // + Arrays.sort(num); + + // һ + for (int i = 0; i < num.length - 3; ) { + // ĸ + for (int j = num.length - 1; j > i + 2; j--) { + // ĸʹòظ + if (j < num.length - 1 && num[j] == num[j + 1]) { + continue; + } + + // ڶ + int start = i + 1; + // + int end = j - 1; + int n = target - num[i] - num[j]; + + while (start < end) { + if (num[start] + num[end] == n) { + List four = new ArrayList<>(4); + four.add(num[i]); + four.add(num[start]); + four.add(num[end]); + four.add(num[j]); + + result.add(four); + + do { + start++; + // ֤ٴʹõڶظ + } while (start < end && num[start] == num[start - 1]); + do { + end--; + // ֤ٴʹõظ + } while (start < end && num[end] == num[end + 1]); + } else if (num[start] + num[end] < n) { + do { + start++; + // ֤ٴʹõڶظ + } while (start < end && num[start] == num[start - 1]); + } else { + do { + end--; + // ֤ٴʹõظ + } while (start < end && num[end] == num[end + 1]); + } + } + } + + // ͬΪֻʹһ + do { + i++; + } while (i < num.length - 2 && num[i - 1] == num[i]); + } + return result; + } +} diff --git a/[0019][Remove Nth Node From End Of List]/[0019][Remove Nth Node From End Of List].iml b/[0019][Remove Nth Node From End Of List]/[0019][Remove Nth Node From End Of List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0019][Remove Nth Node From End Of List]/[0019][Remove Nth Node From End Of List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/src/ListNode.java" b/[0019][Remove Nth Node From End Of List]/src/ListNode.java similarity index 100% rename from "\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/src/ListNode.java" rename to [0019][Remove Nth Node From End Of List]/src/ListNode.java diff --git a/[0019][Remove Nth Node From End Of List]/src/Solution.java b/[0019][Remove Nth Node From End Of List]/src/Solution.java new file mode 100644 index 0000000..84fefb7 --- /dev/null +++ b/[0019][Remove Nth Node From End Of List]/src/Solution.java @@ -0,0 +1,60 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:30 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given a linked list, remove the nth node from the end of list and return its head.
+     * For example,
+     *
+     * 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.
+     *
+     * Note:
+     * Given n will always be valid.
+     * Try to do this in one pass.
+     *
+     * Ŀ
+     * ɾĵڣθ㣬ע⣺ģζǺϷһαɲ
+     *
+     * ˼·
+     * һָҵNڵ㣬Ȼһָָͷ㣬Ȼָһߣ
+     * ֱǰһֱָĩβһָǵN+1㣬ɾNͿˡ
+     * 
+ * + * @param head + * @param n + * @return + */ + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode pa = head; + ListNode pb = head; + + // ҵn + for (int i = 0; i < n && pa != null; i++) { + pa = pa.next; + } + + + // ˵Ҫɾһڵ + if (pa == null) { + head = head.next; + return head; + } + + // pbpan-1 + // pa.nextΪnullpbڵn+1λ + while (pa.next != null) { + pa = pa.next; + pb = pb.next; + } + + pb.next = pb.next.next; + + return head; + } +} diff --git a/[0020][Valid Parentheses]/[0020][Valid Parentheses].iml b/[0020][Valid Parentheses]/[0020][Valid Parentheses].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0020][Valid Parentheses]/[0020][Valid Parentheses].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0020][Valid Parentheses]/src/Main.java b/[0020][Valid Parentheses]/src/Main.java new file mode 100644 index 0000000..4fda8c6 --- /dev/null +++ b/[0020][Valid Parentheses]/src/Main.java @@ -0,0 +1,22 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 14:46 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + Assert.assertEquals(true, solution.isValid("()")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + + Assert.assertEquals(false, solution.isValid("(]")); + } +} diff --git a/[0020][Valid Parentheses]/src/Solution.java b/[0020][Valid Parentheses]/src/Solution.java new file mode 100644 index 0000000..86445bc --- /dev/null +++ b/[0020][Valid Parentheses]/src/Solution.java @@ -0,0 +1,55 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * Author: + * Date: 2015-08-21 + * Time: 16:32 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * һֻ(, ), {, }, [ ͡]ַ֤ǷЧġ
+     * űԣҪȷ˳
+     *
+     * ˼·
+     * һջŴдžջžջԪؿǷһţ
+     * ɾ͵Ҵһţƥֱӷؽ
+     * 
+ * + * @param s + * @return + */ + public boolean isValid(String s) { + Deque stack = new LinkedList<>(); + final String left = "([{"; + final String right = ")]}"; + + for (int index = 0; index < s.length(); index++) { + char c = s.charAt(index); + + // žջ + if (left.indexOf(c) > -1) { + stack.push(c); + } else { + // žͿջԪ + // ջΪջջԪزƥͷfalse + if (stack.isEmpty() || right.indexOf(c) != left.indexOf(stack.peek())) { + return false; + } else { + stack.pop(); + } + } + } + + return stack.isEmpty(); + } +} diff --git a/[0020][Valid Parentheses]/src/Solution2.java b/[0020][Valid Parentheses]/src/Solution2.java new file mode 100644 index 0000000..84aaaa5 --- /dev/null +++ b/[0020][Valid Parentheses]/src/Solution2.java @@ -0,0 +1,97 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * Author: + * Date: 2015-08-21 + * Time: 16:32 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * һֻ(, ), {, }, [ ͡]ַ֤ǷЧġ
+     * űԣҪȷ˳
+     *
+     * ˼·
+     * һջŴдžջžջԪؿǷһţ
+     * ɾ͵Ҵһţƥֱӷؽ
+     * 
+ * + * @param s + * @return + */ + public boolean isValid(String s) { + Deque stack = new LinkedList<>(); + int index = 0; + Character top; + while (index < s.length()) { + Character c = s.charAt(index); + switch (c) { + case '(': + case '[': + case '{': + stack.addFirst(c); + break; + case ')': + + if (stack.isEmpty()) { + return false; + } + + top = stack.getFirst(); + if (top == '(') { + stack.removeFirst(); + } else if (top == '[' || top == '{') { + return false; + } else { + stack.addFirst(c); + } + break; + case ']': + + if (stack.isEmpty()) { + return false; + } + + top = stack.getFirst(); + if (top == '[') { + stack.removeFirst(); + } else if (top == '(' || top == '{') { + return false; + } else { + stack.addFirst(c); + } + break; + case '}': + + if (stack.isEmpty()) { + return false; + } + + top = stack.getFirst(); + if (top == '{') { + stack.removeFirst(); + } else if (top == '[' || top == '(') { + return false; + } else { + stack.addFirst(c); + } + break; + default: + return false; + } + + index++; + } + + return stack.isEmpty(); + } +} diff --git a/[0021][Merge Two Sorted Lists]/[0021][Merge Two Sorted Lists].iml b/[0021][Merge Two Sorted Lists]/[0021][Merge Two Sorted Lists].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0021][Merge Two Sorted Lists]/[0021][Merge Two Sorted Lists].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/src/ListNode.java" b/[0021][Merge Two Sorted Lists]/src/ListNode.java similarity index 100% rename from "\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/src/ListNode.java" rename to [0021][Merge Two Sorted Lists]/src/ListNode.java diff --git a/[0021][Merge Two Sorted Lists]/src/Solution.java b/[0021][Merge Two Sorted Lists]/src/Solution.java new file mode 100644 index 0000000..3d7e574 --- /dev/null +++ b/[0021][Merge Two Sorted Lists]/src/Solution.java @@ -0,0 +1,53 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:35 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * ϲһµбµĽԭȵɣ
+     * ҲDzܺϲܰ´Ľ㡣
+     *
+     * ˼·
+     * ʹͷrootиһͷ㣬ʹָͷ㣬
+     * СĽֵĽժӵrootĩβͬʱժͷƶһ㣬
+     * һֱԭһΪգٽʣµĽӵrootĩβ
+     * 󷵻rootһ㣬Ϊµͷ
+     * 
+ * + * @param l1 + * @param l2 + * @return + */ + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + + // һͷ㣬Ҫɾ + ListNode head = new ListNode(0); + ListNode tail = head; + + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + tail.next = l1; + l1 = l1.next; + } else { + tail.next = l2; + l2 = l2.next; + } + + // ƶµβ + tail = tail.next; + } + + tail.next = (l1 != null ? l1 : l2); + + // headһڵǵһݽ + return head.next; + } +} diff --git a/[0022][Generate Parentheses]/[0022][Generate Parentheses].iml b/[0022][Generate Parentheses]/[0022][Generate Parentheses].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0022][Generate Parentheses]/[0022][Generate Parentheses].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/src/Main.java" b/[0022][Generate Parentheses]/src/Main.java similarity index 100% rename from "\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/src/Main.java" rename to [0022][Generate Parentheses]/src/Main.java diff --git a/[0022][Generate Parentheses]/src/Solution.java b/[0022][Generate Parentheses]/src/Solution.java new file mode 100644 index 0000000..ff49de9 --- /dev/null +++ b/[0022][Generate Parentheses]/src/Solution.java @@ -0,0 +1,72 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-22 + * Time: 11:13 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * 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:
+     * "((()))", "(()())", "(())()", "()(())", "()()()"
+     *
+     * Ŀ⣺
+     * nţȷ
+     *
+     * ˼·
+     * õݹ
+     * 
+ * + * @param n + * @return + */ + public List generateParenthesis(int n) { + // Ķ + List result = new ArrayList<>(); + // 0 + if (n > 0) { + // + char[] parentheses = new char[2 * n]; + // + solve(n, n, parentheses, result); + } + return result; + } + + /** + * @param left ʣõ + * @param right ʣõ + * @param parentheses һΪֹʹõ + * @param result Žļ + */ + public void solve(int left, int right, char[] parentheses, List result) { + + // ʣµС0ÿʣµС + if (left < 0 || right < 0 || right < left) { + // ʲô + return; + } + // Ŷʹ + else if (left == 0 && right == 0) { + result.add(new String(parentheses)); + } + // ʹ + else { + // ǰʹõλ + int idx = parentheses.length - left - right; + // ʹ + parentheses[idx] = '('; + // ݹ + solve(left - 1, right, parentheses, result); + // ʹ + parentheses[idx] = ')'; + solve(left, right - 1, parentheses, result); + } + } +} diff --git a/[0023][Merge K Sorted Lists]/[0023][Merge K Sorted Lists].iml b/[0023][Merge K Sorted Lists]/[0023][Merge K Sorted Lists].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0023][Merge K Sorted Lists]/[0023][Merge K Sorted Lists].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/src/ListNode.java" b/[0023][Merge K Sorted Lists]/src/ListNode.java similarity index 100% rename from "\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/src/ListNode.java" rename to [0023][Merge K Sorted Lists]/src/ListNode.java diff --git a/[0023][Merge K Sorted Lists]/src/Solution.java b/[0023][Merge K Sorted Lists]/src/Solution.java new file mode 100644 index 0000000..ef06cbb --- /dev/null +++ b/[0023][Merge K Sorted Lists]/src/Solution.java @@ -0,0 +1,82 @@ +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * Author: + * Date: 2015-06-30 + * Time: 19:21 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Merge k sorted linked lists and return it as one sorted list.
+     * Analyze and describe its complexity.
+     *
+     * Ŀ⣺
+     * ϲkźõĵĵ
+     *
+     * ˼·
+     * ʹһСвȽkĵһѣȡеСأΪСԪأ
+     * ԪصһѣȡСģβֱΪ
+     * 
+ * + * @param lists + * @return + */ + public ListNode mergeKLists(ListNode[] lists) { + + // ΪջûԪ + if (lists == null || lists.length < 1) { + return null; + } + + // ֻһԪ + if (lists.length == 1) { + return lists[0]; + } + + // һСѣʹһڲΪȽ + PriorityQueue queue = new PriorityQueue<>(new Comparator() { + @Override + public int compare(ListNode o1, ListNode o2) { + if (o1 == null) { + return -1; + } + + if (o2 == null) { + return 1; + } + + return o1.val - o2.val; + } + }); + + // ĵһ + for (ListNode node : lists) { + if (node != null) { + queue.add(node); + } + } + + // ͷ㣬ʹ + ListNode head = new ListNode(0); + // ǰĽ + ListNode curr = head; + + while (!queue.isEmpty()) { + ListNode node = queue.remove(); + + // һ㲻Ϊվͽһ + if (node.next != null) { + queue.add(node.next); + } + + curr.next = node; + curr = node; + } + + return head.next; + } + +} diff --git a/[0023][Merge K Sorted Lists]/src/Solution2.java b/[0023][Merge K Sorted Lists]/src/Solution2.java new file mode 100644 index 0000000..c49de5e --- /dev/null +++ b/[0023][Merge K Sorted Lists]/src/Solution2.java @@ -0,0 +1,214 @@ +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Author: + * Date: 2015-06-30 + * Time: 19:21 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * Merge k sorted linked lists and return it as one sorted list.
+     * Analyze and describe its complexity.
+     *
+     * Ŀ⣺
+     * ϲkźõĵĵ
+     *
+     * ˼·
+     * ʹһСвȽkĵһѣȡеСأΪСԪأ
+     * ԪصһѣȡСģβֱΪ
+     * 
+ * + * @param lists + * @return + */ + public ListNode mergeKLists(ListNode[] lists) { + + // ΪջûԪ + if (lists == null || lists.length < 1) { + return null; + } + + // ֻһԪ + if (lists.length == 1) { + return lists[0]; + } + + // һСѣʹһڲΪȽ + MinHeap minHeap = new MinHeap(new Comparator() { + @Override + public int compare(ListNode o1, ListNode o2) { + if (o1 == null) { + return -1; + } + + if (o2 == null) { + return 1; + } + + return o1.val - o2.val; + } + }); + + + // ĵһ + for (ListNode node : lists) { + if (node != null) { + minHeap.add(node); + } + } + + // ͷ㣬ʹ + ListNode head = new ListNode(0); + // ǰĽ + ListNode curr = head; + + while (!minHeap.isEmpty()) { + ListNode node = minHeap.deleteTop(); + + // һ㲻Ϊվͽһ + if (node.next != null) { + minHeap.add(node.next); + } + + curr.next = node; + curr = node; + } + + return head.next; + } + + /** + * С + * + * @param + */ + private static class MinHeap { + // Ԫشŵļ + private List items; + + private Comparator comp; + + /** + * һ׵ʼС32 + */ + public MinHeap(Comparator comp) { + this(32, comp); + } + + /** + * һָʼСĶ + * + * @param size ʼС + */ + public MinHeap(int size, Comparator comp) { + items = new ArrayList<>(size); + this.comp = comp; + } + + /** + * ϵ + * + * @param index Ԫصʼλ + */ + public void siftUp(int index) { + T intent = items.get(index); // ȡʼԪض + + while (index > 0) { // ǸԪ + int parentIndex = (index - 1) / 2; // ҸԪضλ + T parent = items.get(parentIndex); // ȡԪض + if (comp.compare(intent, parent) < 0) { //ƵӽڵȸڵС + items.set(index, parent); // ڵ· + index = parentIndex; // ¼ڵ·ŵλ + } else { // ӽڵ㲻ȸڵС˵·ѾСź˳ˣҪ + break; + } + } + + // indexʱ¼ǵһ·ŵĸڵλãҲ + // ԽʼĵԪֵindexλü + items.set(index, intent); + } + + /** + * µ + * + * @param index ƵԪصʼλ + */ + public void siftDown(int index) { + T intent = items.get(index); // ȡʼԪض + int leftIndex = 2 * index + 1; // // ȡʼԪضӽԪλ + + while (leftIndex < items.size()) { // ӽ + T minChild = items.get(leftIndex); // ȡӽԪض󣬲ҼٶΪӽС + int minIndex = leftIndex; // ӽڵСڵԪصλãٶʼʱΪӽλ + + int rightIndex = leftIndex + 1; // ȡӽλ + if (rightIndex < items.size()) { // ӽ + T rightChild = items.get(rightIndex); // ȡӽԪض + if (comp.compare(rightChild, minChild) < 0) { // ҳӽڵеСӽ + minChild = rightChild; + minIndex = rightIndex; + } + } + + // СӽڵȸڵСҪµ + if (comp.compare(minChild, intent) < 0) { + items.set(index, minChild); // ӽڵ + index = minIndex; // ¼ƽڵλ + leftIndex = index * 2 + 1; // ҵƽڵӽڵλ + } else { // Сӽڵ㲻ȸڵС˵·ѾСź˳ˣҪ + break; + } + } + + // indexʱ¼ǵһƵӽڵλãҲ + // ԽʼĵԪֵindexλü + items.set(index, intent); + } + + /** + * һԪ + * + * @param item ȴӵԪ + */ + public void add(T item) { + items.add(item); // Ԫӵ + siftUp(items.size() - 1); // ѭƣع + } + + /** + * ɾѶԪ + * + * @return ѶԪ + */ + public T deleteTop() { + if (items.isEmpty()) { // ѾΪգͱ쳣 + throw new RuntimeException("The heap is empty."); + } + + T maxItem = items.get(0); // ȡѶԪ + T lastItem = items.remove(items.size() - 1); // ɾһԪ + if (items.isEmpty()) { // ɾԪغΪյ˵ɾԪҲǶѶԪ + return lastItem; + } + + items.set(0, lastItem); // ɾԪطѶ + siftDown(0); // µ + return maxItem; // ضѶԪ + } + + /** + * ж϶ǷΪ + * + * @return trueǿգfalse + */ + public boolean isEmpty() { + return items.isEmpty(); + } + } + +} diff --git a/[0024][Swap Nodes In Pairs]/[0024][Swap Nodes In Pairs].iml b/[0024][Swap Nodes In Pairs]/[0024][Swap Nodes In Pairs].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0024][Swap Nodes In Pairs]/[0024][Swap Nodes In Pairs].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/src/ListNode.java" b/[0024][Swap Nodes In Pairs]/src/ListNode.java similarity index 100% rename from "\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/src/ListNode.java" rename to [0024][Swap Nodes In Pairs]/src/ListNode.java diff --git a/[0024][Swap Nodes In Pairs]/src/Solution.java b/[0024][Swap Nodes In Pairs]/src/Solution.java new file mode 100644 index 0000000..780c049 --- /dev/null +++ b/[0024][Swap Nodes In Pairs]/src/Solution.java @@ -0,0 +1,53 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:37 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given a linked list, swap every two adjacent nodes and return its head.
+     * For example,
+     * Given 1->2->3->4, you should return the list as 2->1->4->3.
+     * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
+     *
+     * Ŀ
+     * һɶԽڵĽ㡣㷨Ӧռ䣬ܸĽֵֻܽ㡣
+     *
+     * ˼·
+     * ʹһͷrootҪнÿλýн
+     * ҰѽĽӵrootϣֱеĽ㶼ꡣ
+     * 
+ * + * @param head + * @return + */ + public ListNode swapPairs(ListNode head) { + // ͷ + ListNode node = new ListNode(0); + node.next = head; + + // pָµβ㣬pָõĽ㣬ӵͷΪѾ + ListNode p = node; + ListNode tmp; + + // ÿв + while (p.next != null && p.next.next != null) { + // ¼һҪдλ + tmp = p.next.next; + // 㽻 + p.next.next = tmp.next; + tmp.next = p.next; + p.next = tmp; + // ָ򷵻µβ + p = tmp.next; + } + + head = node.next; + node.next = null; + + return head; + } +} diff --git a/[0025][Reverse Nodes In K-Group]/[0025][Reverse Nodes In K-Group].iml b/[0025][Reverse Nodes In K-Group]/[0025][Reverse Nodes In K-Group].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0025][Reverse Nodes In K-Group]/[0025][Reverse Nodes In K-Group].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/src/ListNode.java" b/[0025][Reverse Nodes In K-Group]/src/ListNode.java similarity index 100% rename from "\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/src/ListNode.java" rename to [0025][Reverse Nodes In K-Group]/src/ListNode.java diff --git "a/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/src/Main.java" b/[0025][Reverse Nodes In K-Group]/src/Main.java similarity index 100% rename from "\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/src/Main.java" rename to [0025][Reverse Nodes In K-Group]/src/Main.java diff --git "a/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/src/Solution.java" b/[0025][Reverse Nodes In K-Group]/src/Solution.java similarity index 100% rename from "\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/src/Solution.java" rename to [0025][Reverse Nodes In K-Group]/src/Solution.java diff --git a/[0026][Remove Duplicates from Sorted Array]/[0026][Remove Duplicates from Sorted Array].iml b/[0026][Remove Duplicates from Sorted Array]/[0026][Remove Duplicates from Sorted Array].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0026][Remove Duplicates from Sorted Array]/[0026][Remove Duplicates from Sorted Array].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0026][Remove Duplicates from Sorted Array]/src/Solution.java b/[0026][Remove Duplicates from Sorted Array]/src/Solution.java new file mode 100644 index 0000000..9131cb0 --- /dev/null +++ b/[0026][Remove Duplicates from Sorted Array]/src/Solution.java @@ -0,0 +1,54 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:40 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * 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 doesnt matter what you leave beyond the new length.
+     *
+     * Ŀ
+     * һ飬еظԪȥֻͬһҷµԪظ
+     * Ҫһµڳʱڽ
+     *
+     * ˼·
+     * ӵڶԪؿʼΪǰԪأǰԪǰһԪͬɾԪأ
+     * ͬͽƶȷλãԪ˸
+     * 
+ * + * @param A + * @return + */ + public int removeDuplicates(int[] A) { + + if (A == null) { + return 0; + } + + if (A.length < 2) { + return A.length; + } + + // ָһλ + int index = 1; + for (int i = 1; i < A.length; i++) { + // index - 1ʾǰһźõλ + if (A[index - 1] < A[i]) { + A[index] = A[i]; + index++; + } + } + + return index; + } +} diff --git a/[0026][Remove Duplicates from Sorted Array]/src/Solution2.java b/[0026][Remove Duplicates from Sorted Array]/src/Solution2.java new file mode 100644 index 0000000..fc801b2 --- /dev/null +++ b/[0026][Remove Duplicates from Sorted Array]/src/Solution2.java @@ -0,0 +1,57 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:40 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * ԭ
+     * 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 doesnt matter what you leave beyond the new length.
+     *
+     * Ŀ
+     * һ飬еظԪȥֻͬһҷµԪظ
+     * Ҫһµڳʱڽ
+     *
+     * ˼·
+     * ӵڶԪؿʼΪǰԪأǰԪǰһԪͬɾԪأ
+     * ͬͽƶȷλãԪ˸
+     * 
+ * + * @param A + * @return + */ + public int removeDuplicates(int[] A) { + + if (A.length == 0) { + return 0; + } + + int index = 0;//[0,index]ֻ¼гֵİСΨһһѾź + int next = 1; + + // 㷨˼룺index֮ıA[index]ҵƶA[index+1] + // indexƶһλãnextƶһλãұA[index] + + while (next < A.length) { + while (next < A.length && A[index] == A[next]) { // Ҳ + next++; + } + + if (next < A.length) { + index++; + A[index] = A[next]; + next++; + } + } + return index + 1; + } +} diff --git a/[0027][Remove Element]/[0027][Remove Element].iml b/[0027][Remove Element]/[0027][Remove Element].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0027][Remove Element]/[0027][Remove Element].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0027][Remove Element]/src/Solution.java b/[0027][Remove Element]/src/Solution.java new file mode 100644 index 0000000..bfdcaf6 --- /dev/null +++ b/[0027][Remove Element]/src/Solution.java @@ -0,0 +1,52 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:43 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given an array and a value, remove all instances of that value in place and return the new length.
+     *  The order of elements can be changed. It doesnt matter what you leave beyond the new length.
+     *
+     * Ŀ
+     * һһֵɾֵȵԪأҷµijȡ
+     *
+     * ˼·
+     * ֵΪelemԪصλãjұֵΪelemԪصλãȻjλõֵƶiλá
+     * 
+ * + * @param nums + * @param val + * @return + */ + public int removeElement(int[] nums, int val) { + int exchange = 0; // ¼ĴҲͳelemԪֵȵĸ + + // 㷨˼룺iֵΪelemԪصλãjұֵΪelemԪصλã + // ȡȺóΪ1Խ + for (int i = 0, j = nums.length - 1; i <= j; i++) { + // ҵҪԪ + if (nums[i] == val) { + exchange++; + + // 濪ʼǰҵһelemԪ + while (j > i && nums[j] == val) { + // ֵΪelemԪ˵Ҫǽ̿ʡȥ + exchange++; + j--; + } + + // 1ΪelemԪصλãjλõԪطŵiλ + // 2ûҵelemԪصλãiԪֵeʱj=i + // jеֵiûйϵ + nums[i] = nums[j]; + j--; // jѾʹԻҪǰƶһµλ + } + } + + return nums.length - exchange; + } +} diff --git a/[0027][Remove Element]/src/Solution2.java b/[0027][Remove Element]/src/Solution2.java new file mode 100644 index 0000000..e87040c --- /dev/null +++ b/[0027][Remove Element]/src/Solution2.java @@ -0,0 +1,40 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 16:43 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * ԭ
+     * Given an array and a value, remove all instances of that value in place and return the new length.
+     *  The order of elements can be changed. It doesnt matter what you leave beyond the new length.
+     *
+     * Ŀ
+     * һһֵɾֵȵԪأҷµijȡ
+     *
+     * ˼·
+     *
+     * 
+ * + * @param nums + * @param val + * @return + */ + public int removeElement(int[] nums, int val) { + + // [0, ..., index - 1]ʾѾųvalֵ飬indexʾ֮ԷԪصλã + // Ҳʾij + int index = 0; + for (int i = 0; i < nums.length; i++) { + // Ⱦƶ + if (nums[i] != val) { + nums[index] = nums[i]; + ++index; + } + } + + return index; + } +} diff --git a/[0028][Implement-strStr()]/[0028][Implement-strStr()].iml b/[0028][Implement-strStr()]/[0028][Implement-strStr()].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0028][Implement-strStr()]/[0028][Implement-strStr()].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221/src/Solution.java" b/[0028][Implement-strStr()]/src/Solution.java similarity index 100% rename from "\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221/src/Solution.java" rename to [0028][Implement-strStr()]/src/Solution.java diff --git a/[0029][Divide Two Integers]/[0029][Divide Two Integers].iml b/[0029][Divide Two Integers]/[0029][Divide Two Integers].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0029][Divide Two Integers]/[0029][Divide Two Integers].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0029][Divide Two Integers]/[0029][DivideTwoIntegers].iml b/[0029][Divide Two Integers]/[0029][DivideTwoIntegers].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0029][Divide Two Integers]/[0029][DivideTwoIntegers].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/src/Main.java" b/[0029][Divide Two Integers]/src/Main.java similarity index 100% rename from "\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/src/Main.java" rename to [0029][Divide Two Integers]/src/Main.java diff --git "a/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/src/Solution.java" b/[0029][Divide Two Integers]/src/Solution.java similarity index 100% rename from "\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/src/Solution.java" rename to [0029][Divide Two Integers]/src/Solution.java diff --git a/[0030][Substring With Concatenation Of All Words]/[0030][Substring With Concatenation Of All Words].iml b/[0030][Substring With Concatenation Of All Words]/[0030][Substring With Concatenation Of All Words].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0030][Substring With Concatenation Of All Words]/[0030][Substring With Concatenation Of All Words].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0030][Substring With Concatenation Of All Words]/src/Solution.java b/[0030][Substring With Concatenation Of All Words]/src/Solution.java new file mode 100644 index 0000000..83d5e29 --- /dev/null +++ b/[0030][Substring With Concatenation Of All Words]/src/Solution.java @@ -0,0 +1,33 @@ +import java.util.List; + +/** + * Author: + * Date: 2015-07-01 + * Time: 08:23 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * You are given a string, s, and a list of words, words,
+     * that are all of the same length. Find all starting indices
+     * of substring(s) in s that is a concatenation of each word
+     * in words exactly once and without any intervening characters.
+     *
+     * For example, given:
+     * s: "barfoothefoobarman"
+     * words: ["foo", "bar"]
+     * You should return the indices: [0,9].
+     * (order does not matter).
+     * 
+ * + * @param s + * @param words + * @return + */ + public List findSubstring(String s, String[] words) { + + // TODO + return null; + } +} diff --git a/[0031][Next Permutation]/[0031][Next Permutation].iml b/[0031][Next Permutation]/[0031][Next Permutation].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0031][Next Permutation]/[0031][Next Permutation].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0031][Next Permutation]/src/Main.java b/[0031][Next Permutation]/src/Main.java new file mode 100644 index 0000000..1f5a159 --- /dev/null +++ b/[0031][Next Permutation]/src/Main.java @@ -0,0 +1,42 @@ +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-14 21:30 + **/ +public class Main { + + @Test + public void test1() { + Solution solution = new Solution(); + int[] nums = {1, 2, 3}; + solution.nextPermutation(nums); + System.out.println(Arrays.toString(nums)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + int[] nums = {3, 2, 1}; + solution.nextPermutation(nums); + System.out.println(Arrays.toString(nums)); + } + + @Test + public void test3() { + Solution solution = new Solution(); + int[] nums = {1, 1, 5}; + solution.nextPermutation(nums); + System.out.println(Arrays.toString(nums)); + } + + @Test + public void test4() { + Solution solution = new Solution(); + int[] nums = {1, 3, 2}; + solution.nextPermutation(nums); + System.out.println(Arrays.toString(nums)); + } +} diff --git a/[0031][Next Permutation]/src/Solution.java b/[0031][Next Permutation]/src/Solution.java new file mode 100644 index 0000000..90a5a19 --- /dev/null +++ b/[0031][Next Permutation]/src/Solution.java @@ -0,0 +1,82 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-14 21:17 + **/ +public class Solution { + /** + *
+     * 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
+     *
+     * 1.首先从最尾端开始往前寻找一个元素,满足nums[i] < nums[i+1]。
+     * 如果没有找到即i < 0, 说明整个数组是递增的,已经到了最大值,此时只要反转数组即可
+     * 如果i >= 0
+     *
+     * 2.再从最尾端开始往前检验,找出第一个大于nums[i]的元素nums[j] 并且,j >= i
+     * 将nums[i],nums[j]元素对调(swap)。
+     *
+     * 3.再将i位置之后的所有元素颠倒(reverse)排序。
+     * 
+ * + * @param nums + */ + public void nextPermutation(int[] nums) { + int i = nums.length - 2; + // 从后向前查找第一个元素i,并且使用nums[i] >= nums[i+1]不成立。 + while (i >= 0 && nums[i] >= nums[i + 1]) { + i--; + } + + // 此时nums[i+1, ..., last]是递增的 + + + if (i >= 0) { + int j = nums.length - 1; + // 从右开始向左找,找第一个大于等num[i]的元素 + // 如果找到i==j,说明没有找到 + while (j > i && nums[j] <= nums[i]) { + j--; + } + + // 交换两者之间的值,当j == i时,交换也没有问题 + swap(nums, i, j); + + // 将nums[i+1, last]进行反转 + reverse(nums, i + 1); + } else { + // 说明整个序列是非递增的 + // 对子数组进行翻转 + reverse(nums, 0); + } + + + } + + private void reverse(int[] nums, int start) { + int i = start; + int j = nums.length - 1; + while (i < j) { + swap(nums, i, j); + i++; + j--; + } + } + + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/[0032][Longest Valid Parentheses]/[0032][Longest Valid Parentheses].iml b/[0032][Longest Valid Parentheses]/[0032][Longest Valid Parentheses].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0032][Longest Valid Parentheses]/[0032][Longest Valid Parentheses].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/src/Main.java" b/[0032][Longest Valid Parentheses]/src/Main.java similarity index 100% rename from "\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/src/Main.java" rename to [0032][Longest Valid Parentheses]/src/Main.java diff --git a/[0032][Longest Valid Parentheses]/src/Solution.java b/[0032][Longest Valid Parentheses]/src/Solution.java new file mode 100644 index 0000000..ba8947c --- /dev/null +++ b/[0032][Longest Valid Parentheses]/src/Solution.java @@ -0,0 +1,52 @@ +import java.util.Stack; + +/** + * Author: + * Date: 2015-06-25 + * Time: 09:12 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a string containing just the characters '(' and ')',
+     * find the length of the longest valid (well-formed) parentheses substring.
+     *
+     * For "(()", the longest valid parentheses substring is "()", which has length = 2.
+     * Another example is ")()())", where the longest valid parentheses substring is "()()",
+     * which has length = 4.
+     *
+     * Ŀ⣺
+     * һַֻСźţĺϷСŵĿ
+     *
+     * ˼·
+     * ʹջʵ
+     * 
+ * + * @param s + * @return + */ + public int longestValidParentheses(String s) { + // ڼ¼ƥźŵλ + Stack st = new Stack<>(); + int max = 0; + for (int i = 0; i < s.length(); i++) { + + // ǵǰַţҼ¼ջǿգǰһַ + if (s.charAt(i) == ')' && !st.isEmpty() && s.charAt(st.peek()) == '(') { + // ųջ + st.pop(); + // ֵ + // ʱ(ƥ)ѾջջҪôΪգҪô뵱ǰ)) + // Ҫô뵱ǰ)ڶ( + max = Math.max(max, i - ((st.isEmpty()) ? -1 : st.peek())); + } + // ͽַջ + else { + st.push(i); + } + } + + return max; + } +} diff --git a/[0032][Longest Valid Parentheses]/src/Solution2.java b/[0032][Longest Valid Parentheses]/src/Solution2.java new file mode 100644 index 0000000..fb9b995 --- /dev/null +++ b/[0032][Longest Valid Parentheses]/src/Solution2.java @@ -0,0 +1,59 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * Author: + * Date: 2015-06-25 + * Time: 09:12 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * Given a string containing just the characters '(' and ')',
+     * find the length of the longest valid (well-formed) parentheses substring.
+     *
+     * For "(()", the longest valid parentheses substring is "()", which has length = 2.
+     * Another example is ")()())", where the longest valid parentheses substring is "()()",
+     * which has length = 4.
+     *
+     * Ŀ⣺
+     * һַֻСźţĺϷСŵĿ
+     *
+     * ˼·
+     * ʹջʵ
+     * 
+ * + * @param s + * @return + */ + public int longestValidParentheses(String s) { + int result = 0; + int start = 0; + // ¼ŵλ + Deque m = new LinkedList<>(); + for (int i = 0; i < s.length(); ++i) { + // žͼ¼λ + if (s.charAt(i) == '(') { + m.push(i); + } + // + else if (s.charAt(i) == ')') { + // ֮ǰŶѾԣߴû + if (m.isEmpty()) { + // ǰλѾЧˣ¼һλǿʼԵλ + start = i + 1; + } else { + // ջӦ + m.pop(); + // ջΪգ˵startʼһֱƥ䣬ûֶţ + // ǣMath.max(result, i - start + 1) + // ջǿգ˵жţһŵλþm.peek() + // ƥž: Math.max(result, i - m.peek()) + result = m.isEmpty() ? Math.max(result, i - start + 1) : Math.max(result, i - m.peek()); + } + } + } + return result; + } +} diff --git a/[0033][Search In Rotated Sorted Array]/[0033][Search In Rotated Sorted Array].iml b/[0033][Search In Rotated Sorted Array]/[0033][Search In Rotated Sorted Array].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0033][Search In Rotated Sorted Array]/[0033][Search In Rotated Sorted Array].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0033][Search In Rotated Sorted Array]/[0033][SearchInRotatedSortedArray].iml b/[0033][Search In Rotated Sorted Array]/[0033][SearchInRotatedSortedArray].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0033][Search In Rotated Sorted Array]/[0033][SearchInRotatedSortedArray].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0033][Search In Rotated Sorted Array]/src/Main.java b/[0033][Search In Rotated Sorted Array]/src/Main.java new file mode 100644 index 0000000..d522524 --- /dev/null +++ b/[0033][Search In Rotated Sorted Array]/src/Main.java @@ -0,0 +1,13 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-12 23:22 + **/ +public class Main { + public static void main(String[] args) { + int[] nums = {4, 5, 6, 7, 0, 1, 2}; + Solution2 solution = new Solution2(); + + System.out.println(solution.search(nums, 4)); + System.out.println(solution.search(nums, 3)); + } +} diff --git a/[0033][Search In Rotated Sorted Array]/src/Solution.java b/[0033][Search In Rotated Sorted Array]/src/Solution.java new file mode 100644 index 0000000..4f3e4eb --- /dev/null +++ b/[0033][Search In Rotated Sorted Array]/src/Solution.java @@ -0,0 +1,120 @@ +/** + * Author: 王俊超 + * Date: 2015-06-21 + * Time: 14:48 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Suppose a sorted array is rotated at some pivot unknown to you beforehand.
+     * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
+     * You are given a target value to search. If found in the array return its
+     * index, otherwise return -1.
+     *
+     * You may assume no duplicate exists in the array.
+     *
+     * 题目大意:
+     * 假设一个排序的数组以一个未知的的枢轴旋转。(即,0 1 2 4 5 6 7可能成为4 5 6 7 0 1 2)。
+     * 给定一个目标值,在数组中搜寻。如果存在就返回其对应的下标,否则返回-1。
+     * 假设数组中不存在重复值。
+     *
+     * 解题思路:
+     * 找旋转数组最小值的位置minIndex(见LeetCode第153题 ),如果minIndex不为,说明其在分隔成
+     * 两个有序数组,并且前一个中的第一个元素都大于后一个数组的每一个元素,判断target中哪一个数组区
+     * 间中使用二叉搜索算法查找,如果minIndex=0,说明全局有序,对整个数组进行二叉查找,返回查找结果
+     * 
+ * + * @param nums + * @param target + * @return + */ + public int search(int[] nums, int target) { + + if (nums != null && nums.length > 0) { + + // 找最小元素对应的下标 + int minIndex = searchMinIndex(nums, 0, nums.length - 1); + + // 整个数组全局有序 + if (minIndex == 0) { + return binarySearch(nums, 0, nums.length - 1, target); + } + // 有两个局部有序区间, 如 4 5 6 7 8 9 0 1 2 3 + else { + // 恬好和后一个有序区间的最后一个元素相等,返回对应的下标 + if (nums[nums.length - 1] == target) { + return nums.length - 1; + } + // target可能在后一个有序区间中 + else if (nums[nums.length - 1] > target) { + return binarySearch(nums, minIndex, nums.length - 1, target); + } + // target可能是前一个有序区间中 + else { + return binarySearch(nums, 0, minIndex - 1, target); + } + } + } + + return -1; + } + + /** + * 二分搜索 + * + * @param nums 数组 + * @param start 起始位置 + * @param end 结束位置 + * @param target 搜索目标 + * @return 匹配元素的下标 + */ + public int binarySearch(int[] nums, int start, int end, int target) { + + int mid; + while (start <= end) { + mid = start + ((end - start) >> 1); + + if (nums[mid] == target) { + return mid; + } else if (nums[mid] > target) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return -1; + } + + /** + * 找最小元素的下标 + * + * @param nums 数组 + * @param start 起始位置 + * @param end 结束位置 + * @return 最小元素的下标 + */ + public int searchMinIndex(int[] nums, int start, int end) { + + int mid; + while (start < end) { + mid = start + ((end - start) >> 1); + // 后一个数比前个数小就找到了 + if (nums[mid] > nums[mid + 1]) { + return mid + 1; + } + // 说明中间值在第一个有序的数组中 + else if (nums[mid] > nums[start]) { + start = mid; + } + // 说明中间值在第二个有序的数组中 + else { + end = mid; + } + } + + // 说明整个数组是有序的 + return 0; + } +} diff --git a/[0033][Search In Rotated Sorted Array]/src/Solution2.java b/[0033][Search In Rotated Sorted Array]/src/Solution2.java new file mode 100644 index 0000000..59a71a5 --- /dev/null +++ b/[0033][Search In Rotated Sorted Array]/src/Solution2.java @@ -0,0 +1,65 @@ +/** + * Author: 王俊超 + * Date: 2015-06-21 + * Time: 14:48 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * Suppose a sorted array is rotated at some pivot unknown to you beforehand.
+     * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
+     * You are given a target value to search. If found in the array return its
+     * index, otherwise return -1.
+     *
+     * You may assume no duplicate exists in the array.
+     *
+     * 题目大意:
+     * 假设一个排序的数组以一个未知的的枢轴旋转。(即,0 1 2 4 5 6 7可能成为4 5 6 7 0 1 2)。
+     * 给定一个目标值,在数组中搜寻。如果存在就返回其对应的下标,否则返回-1。
+     * 假设数组中不存在重复值。
+     *
+     * 解题思路:
+     * 找旋转数组最小值的位置minIndex(见LeetCode第153题 ),如果minIndex不为,说明其在分隔成
+     * 两个有序数组,并且前一个中的第一个元素都大于后一个数组的每一个元素,判断target中哪一个数组区
+     * 间中使用二叉搜索算法查找,如果minIndex=0,说明全局有序,对整个数组进行二叉查找,返回查找结果
+     * 
+ * + * @param nums + * @param target + * @return + */ + public int search(int[] nums, int target) { + if (nums == null || nums.length == 0) { + return -1; + } + + int left = 0; + int right = nums.length - 1; + int mid; + while (left <= right) { + mid = left + (right - left) / 2; + if (nums[mid] == target) { + return mid; + } + + // 说明first,mid都在同一个递增子序列中 + if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; + } else { + left = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + + return -1; + } + +} diff --git a/[0034][Search For A Range]/[0034][Search For A Range].iml b/[0034][Search For A Range]/[0034][Search For A Range].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0034][Search For A Range]/[0034][Search For A Range].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0034][Search For A Range]/[0034][SearchForARange].iml b/[0034][Search For A Range]/[0034][SearchForARange].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0034][Search For A Range]/[0034][SearchForARange].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221/src/Solution.java" b/[0034][Search For A Range]/src/Solution.java similarity index 100% rename from "\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221/src/Solution.java" rename to [0034][Search For A Range]/src/Solution.java diff --git a/[0035][Search Insert Position]/[0035][Search Insert Position].iml b/[0035][Search Insert Position]/[0035][Search Insert Position].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0035][Search Insert Position]/[0035][Search Insert Position].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0035][Search Insert Position]/[0035][SearchInsertPosition].iml b/[0035][Search Insert Position]/[0035][SearchInsertPosition].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0035][Search Insert Position]/[0035][SearchInsertPosition].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221/src/Solution.java" b/[0035][Search Insert Position]/src/Solution.java similarity index 100% rename from "\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221/src/Solution.java" rename to [0035][Search Insert Position]/src/Solution.java diff --git a/[0036][Valid Sudoku]/[0036][Valid Sudoku].iml b/[0036][Valid Sudoku]/[0036][Valid Sudoku].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0036][Valid Sudoku]/[0036][Valid Sudoku].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0036][Valid Sudoku]/src/Solution.java b/[0036][Valid Sudoku]/src/Solution.java new file mode 100644 index 0000000..80b5bcd --- /dev/null +++ b/[0036][Valid Sudoku]/src/Solution.java @@ -0,0 +1,108 @@ +import java.util.Arrays; + +/** + * Author: + * Date: 2015-08-21 + * Time: 16:59 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
+     * The Sudoku board could be partially filled, where empty cells are filled
+     * with the character '.'.
+     *
+     * A partially filled sudoku which is valid.
+     * Note:
+     * A valid Sudoku board (partially filled) is not necessarily solvable.
+     * Only the filled cells need to be validated.
+     *
+     * Ŀ
+     * ֤һǷϷ̵֤ӶӦҳ档
+     * Dzģյλʹõ档
+     * ע⣺Ϸ̲һҪĿɽģֻҪҪͿԡ
+     *
+     * ˼·
+     * ȶнм飬ٶнм飬飳*ķ
+     * 
+ * + * @param board + * @return + */ + public boolean isValidSudoku(char[][] board) { + // .ASCIIֵ460ASCIIֵ48/ASCIIֵ47 + int number = board[0].length; + int[] record = new int[10 + 2]; //.9ֵݵλ[2, 10] + boolean isValid; + reset(record); + + // нм + for (int i = 0; i < number; i++) { + for (int j = 0; j < number; j++) { + record[board[i][j] - '.']++; + } + + // Ǽʧ + if (!check(record)) { + return false; + } + // ɹ + else { + reset(record); + } + } + + // нм + for (int i = 0; i < number; i++) { + for (int j = 0; j < number; j++) { + record[board[j][i] - '.']++; + } + + if (!check(record)) { // Ǽʧ + return false; + } else { // ɹ + reset(record); + } + } + + // 3*3 + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + + for (int k = i * 3; k < (i + 1) * 3; k++) { + for (int l = j * 3; l < (j + 1) * 3; l++) { + record[board[k][l] - '.']++; + } + } + + if (!check(record)) { // Ǽʧ + return false; + } else { // ɹ + reset(record); + } + } + } + return true; + } + + private void reset(int[] a) { + Arrays.fill(a, 0); + } + + /** + * һУһУ3*3ķǷϷ1-9еָ1ͲϷ + * + * @param a ֤ + * @return ؽ + */ + private boolean check(int[] a) { + for (int i = 2; i < a.length; i++) { + if (a[i] > 1) { + return false; + } + } + return true; + } +} diff --git "a/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/src/sodoku.png" b/[0036][Valid Sudoku]/src/sodoku.png similarity index 100% rename from "\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/src/sodoku.png" rename to [0036][Valid Sudoku]/src/sodoku.png diff --git a/[0037][Sudoku Solver]/[0037][Sudoku Solver].iml b/[0037][Sudoku Solver]/[0037][Sudoku Solver].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0037][Sudoku Solver]/[0037][Sudoku Solver].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0037][Sudoku Solver]/src/Solution.java b/[0037][Sudoku Solver]/src/Solution.java new file mode 100644 index 0000000..8485787 --- /dev/null +++ b/[0037][Sudoku Solver]/src/Solution.java @@ -0,0 +1,56 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:06 + **/ +public class Solution { + public void solveSudoku(char[][] board) { + if (board == null || board.length == 0) { + return; + } + solve(board); + } + + public boolean solve(char[][] board) { + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + if (board[i][j] == '.') { + // 尝试1到9的数字 + for (char c = '1'; c <= '9'; c++) { + if (isValid(board, i, j, c)) { + // 将字符放入单元格 + board[i][j] = c; + + // 如果字符可以放入单元格返回true + if (solve(board)) { + return true; + } else { // 如果字符不能放入单元格就是还原成点号 + board[i][j] = '.'; + } + } + } + return false; + } + } + } + return true; + } + + private boolean isValid(char[][] board, int row, int col, char c) { + for (int i = 0; i < 9; i++) { + // 检查行 + if (board[i][col] != '.' && board[i][col] == c) { + return false; + } + // 检查列 + if (board[row][i] != '.' && board[row][i] == c) { + return false; + } + // 检查3*3的单元格 + if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] != '.' + && board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) { + return false; + } + } + return true; + } +} diff --git a/[0038][Count And Say]/[0038][Count And Say].iml b/[0038][Count And Say]/[0038][Count And Say].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0038][Count And Say]/[0038][Count And Say].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221/src/Solution.java" b/[0038][Count And Say]/src/Solution.java similarity index 100% rename from "\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221/src/Solution.java" rename to [0038][Count And Say]/src/Solution.java diff --git a/[0039][Combination Sum]/[0039][Combination Sum].iml b/[0039][Combination Sum]/[0039][Combination Sum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0039][Combination Sum]/[0039][Combination Sum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0039][Combination Sum]/src/Solution.java b/[0039][Combination Sum]/src/Solution.java new file mode 100644 index 0000000..48c86b6 --- /dev/null +++ b/[0039][Combination Sum]/src/Solution.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:11 + **/ +public class Solution { + public List> combinationSum(int[] nums, int target) { + // 用于保存结果 + List> list = new LinkedList<>(); + Arrays.sort(nums); + backtrack(list, new ArrayList<>(), nums, target, 0); + return list; + } + + // 回溯法 + // list:保存总的结果 + // tempList:保存临时结果 + // nums:输入的数组 + // remain:剩下的值 + // start:可用的值在数组中的起始位置 + private void backtrack(List> list, List tempList, int[] nums, int remain, int start) { + // 不够减 + if (remain < 0) { + return; + } else if (remain == 0) { // 刚好够减 + list.add(new LinkedList<>(tempList)); + } else { + // 从剩下的数中一个一个尝试 + for (int i = start; i < nums.length; i++) { + // 假设这个值是临时结果中的一个值 + tempList.add(nums[i]); + // 处理下一步 + backtrack(list, tempList, nums, remain - nums[i], i); + // 现场还原 + tempList.remove(tempList.size() - 1); + } + } + } +} diff --git a/[0040][Combination Sum II]/[0040][Combination Sum II].iml b/[0040][Combination Sum II]/[0040][Combination Sum II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0040][Combination Sum II]/[0040][Combination Sum II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0040][Combination Sum II]/src/Solution.java b/[0040][Combination Sum II]/src/Solution.java new file mode 100644 index 0000000..c766df0 --- /dev/null +++ b/[0040][Combination Sum II]/src/Solution.java @@ -0,0 +1,44 @@ +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:15 + **/ +public class Solution { + public List> combinationSum2(int[] nums, int target) { + List> list = new LinkedList<>(); + Arrays.sort(nums); + backtrack(list, new LinkedList<>(), nums, target, 0); + return list; + + } + + /** + * @param list 结果集 + * @param tempList 临时结果集 + * @param nums 可选值数组 + * @param remain 剩余值 + * @param start 可选值的起始下标 + */ + private void backtrack(List> list, List tempList, int[] nums, int remain, int start) { + if (remain < 0) { + return; + } else if (remain == 0) { + list.add(new LinkedList<>(tempList)); + } else { + for (int i = start; i < nums.length; i++) { + // 如果上一轮循环没有选nums[i],则本次循环就不能再选nums[i], + // 确保nums[i] 最多只用一次 + if (i > start && nums[i] == nums[i - 1]) { + continue; + } + tempList.add(nums[i]); + // 数值不可以被重用 + backtrack(list, tempList, nums, remain - nums[i], i + 1); + tempList.remove(tempList.size() - 1); + } + } + } +} diff --git a/[0041][First Missing Positive]/[0041][First Missing Positive].iml b/[0041][First Missing Positive]/[0041][First Missing Positive].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0041][First Missing Positive]/[0041][First Missing Positive].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0041][First Missing Positive]/src/Main.java b/[0041][First Missing Positive]/src/Main.java new file mode 100644 index 0000000..3a25e0e --- /dev/null +++ b/[0041][First Missing Positive]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 14:38 + **/ +public class Main { + + @Test + public void test1() { + Solution solution = new Solution(); + int[] arr = {1, 4, 3, 3, 2}; + int result = solution.firstMissingPositive(arr); + System.out.println(Arrays.toString(arr)); + Assert.assertEquals(5, result); + } +} diff --git a/[0041][First Missing Positive]/src/Solution.java b/[0041][First Missing Positive]/src/Solution.java new file mode 100644 index 0000000..d8f7546 --- /dev/null +++ b/[0041][First Missing Positive]/src/Solution.java @@ -0,0 +1,52 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:18 + **/ +public class Solution { + /** + *
+     * Given an unsorted integer array, find the smallest missing positive integer.
+     *
+     * Example 1:
+     *
+     * Input: [1,2,0]
+     * Output: 3
+     * Example 2:
+     *
+     * Input: [3,4,-1,1]
+     * Output: 2
+     * Example 3:
+     *
+     * Input: [7,8,9,11,12]
+     * Output: 1
+     *
+     * 本质上是桶排序(bucket sort),每当A[i]!= i+1 的时候,将A[i] 与A[A[i]-1] 交换,
+     * 直到无法交换为止,终止条件是A[i]== A[A[i]-1]。
+     * 
+ * + * @param nums + * @return + */ + public int firstMissingPositive(int[] nums) { + int n = nums.length; + for (int i = 0; i < n; i++) { + // nums[i] == nums[nums[i] - 1] 说明出现了两个同样的元素或者两个是同一个元素 + while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) { + swap(nums, i, nums[i] - 1); + } + } + for (int i = 0; i < n; i++) { + if (nums[i] != i + 1) { + return i + 1; + } + } + + return n + 1; + } + + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/[0042][Trapping Rain Water]/[0042][Trapping Rain Water].iml b/[0042][Trapping Rain Water]/[0042][Trapping Rain Water].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0042][Trapping Rain Water]/[0042][Trapping Rain Water].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0042][Trapping Rain Water]/src/Solution.java b/[0042][Trapping Rain Water]/src/Solution.java new file mode 100644 index 0000000..597d513 --- /dev/null +++ b/[0042][Trapping Rain Water]/src/Solution.java @@ -0,0 +1,150 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:20 + **/ +class Solution { + + public int trap(int[] height) { + return trap4(height); + } + + /** + *
+     * 对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是min(max_left,max_right) - height。所以,
+     * 1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;
+     * 2. 从右往左扫描一遍,对于每个柱子,求最大右值;
+     * 3. 再扫描一遍,把每个柱子的面积并累加。
+     * 
+ * + * @param height + * @return + */ + public int trap1(int[] height) { + int ans = 0; + int size = height.length; + for (int i = 1; i < size - 1; i++) { + int maxLeft = 0; + int maxRight = 0; + // 找此柱左边最高的柱子 + for (int j = i - 1; j >= 0; j--) { + maxLeft = Math.max(maxLeft, height[j]); + } + // 找此柱子右边最高的柱子 + for (int j = i + 2; j < size; j++) { + maxRight = Math.max(maxRight, height[j]); + } + + // Math.min(maxLeft, maxRight) - height[i] 此柱子可以容纳的水 + ans += Math.min(maxLeft, maxRight) - height[i]; + } + return ans; + } + + int trap2(int[] height) { + if (height == null || height.length == 0) { + return 0; + } + int ans = 0; + int size = height.length; + int[] leftMax = new int[size]; + int[] rightMax = new int[size]; + + + // 对于每个柱子求左右最大值,并保存起来 + for (int i = 1; i < size - 1; i++) { + leftMax[i] = Math.max(height[i], leftMax[i - 1]); + rightMax[size - i - 1] = Math.max(height[size - i], rightMax[size - i]); + } + + + for (int i = 1; i < size - 1; i++) { + ans += Math.min(leftMax[i], rightMax[i]) - height[i]; + } + return ans; + } + + /** + *
+     * 用一个栈辅助,小于栈顶的元素压入,大于等于栈顶就把栈里所有小于或
+     * 等于当前值的元素全部出栈处理掉,计算面积,最后把当前元素入栈
+     *
+     *
+     *
+     *         =
+     *    =   === =
+     *  = == =======
+     * =============
+     * 0123456789012
+     * 
+ * + * @param height + * @return + */ + int trap3(int[] height) { + int ans = 0, current = 0; + Deque st = new LinkedList<>(); + while (current < height.length) { + // 当前元素比栈顶元素大 + while (!st.isEmpty() && height[current] > height[st.getFirst()]) { + int top = st.pop(); + if (st.isEmpty()) { + break; + } + + // 求距离,如上图,比如current=7,此时top=4,top到current距离:current-top-1 + int distance = current - st.peek() - 1; + // top以下的水位已经计算过了,top以上的水位就 + // height[current] - height[top], height[st.peek()] - height[top] + // 较小的值,简化为以下面的表达式 + int boundedHeight = Math.min(height[current], height[st.peek()]) - height[top]; + ans += distance * boundedHeight; + } + + // 当前元素不大于栈顶元素 + st.push(current++); + } + return ans; + } + + /** + *
+     * 1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;
+     * 2. 处理左边一半;
+     * 3. 处理右边一半。
+     * 
+ * + * @param height + * @return + */ + int trap4(int[] height) { + int left = 0; + int right = height.length - 1; + int ans = 0; + int leftMax = 0; + int rightMax = 0; + + while (left < right) { + if (height[left] < height[right]) { + if (height[left] >= leftMax) { + leftMax = height[left]; + } else { + ans += leftMax - height[left]; + } + + ++left; + } else { + if (height[right] >= rightMax) { + rightMax = height[right]; + } else { + ans += rightMax - height[right]; + } + + --right; + } + } + return ans; + } +} diff --git a/[0043][Multiply Strings]/[0043][Multiply Strings].iml b/[0043][Multiply Strings]/[0043][Multiply Strings].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0043][Multiply Strings]/[0043][Multiply Strings].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0043][Multiply Strings]/src/Solution.java b/[0043][Multiply Strings]/src/Solution.java new file mode 100644 index 0000000..04cfb1c --- /dev/null +++ b/[0043][Multiply Strings]/src/Solution.java @@ -0,0 +1,44 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:23 + **/ +public class Solution { + public String multiply(String num1, String num2) { + int m = num1.length(), n = num2.length(); + int[] pos = new int[m + n]; + + int mul; + int index; + int temp; + for (int i = m - 1; i >= 0; i--) { + for (int j = n - 1; j >= 0; j--) { + // 求积 + mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); + // 积的最低位所在的位置 + index = i + j + 1; + + // 最低低求和 + pos[index] += mul; + + // 做进位处理 + while (pos[index] > 9) { + temp = pos[index]; + pos[index] = temp % 10; + --index; + pos[index] += temp / 10; + } + + } + } + + + StringBuilder sb = new StringBuilder(); + + for (int p : pos) { + if (!(sb.length() == 0 && p == 0)) { + sb.append(p); + } + } + return sb.length() == 0 ? "0" : sb.toString(); + } +} diff --git a/[0044][Wildcard Matching]/[0044][Wildcard Matching].iml b/[0044][Wildcard Matching]/[0044][Wildcard Matching].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0044][Wildcard Matching]/[0044][Wildcard Matching].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0044][Wildcard Matching]/src/Solution.java b/[0044][Wildcard Matching]/src/Solution.java new file mode 100644 index 0000000..2f5d7e2 --- /dev/null +++ b/[0044][Wildcard Matching]/src/Solution.java @@ -0,0 +1,54 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:25 + **/ +public class Solution { + public boolean isMatch(String str, String pattern) { + // 匹配串的索引 + int s = 0; + // 模式串的索引 + int p = 0; + // 记录匹配的匹配位置 + int match = 0; + // 星号的起始索引 + int starIdx = -1; + while (s < str.length()) { + // 两个指针都往前推进 + if (p < pattern.length() && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))) { + s++; + p++; + } + // 发现一个*,只前进模式串索引 + else if (p < pattern.length() && pattern.charAt(p) == '*') { + // 记录最后一次发现*的位置 + starIdx = p; + // 记录在匹配串中匹配*时的位置 + match = s; + // 模式串索引向前推进 + p++; + } + // last pattern pointer was *, advancing string pointer + // 最后的模式串索引是*,匹配串索引向前推进。这个条件隐含p >= pattern.length(),再加上starIdx != -1 + // 说明存在*号匹配,在星号匹配的 + else if (starIdx != -1) { + // 记录模式串最后处理的*号的下一个位置 + p = starIdx + 1; + // 记录在匹配串中匹配*时的位置 + match++; + // 匹配串索引向前推进 + s = match; + } + // 当前的模式索引指向的不是*号,最后一个模式索引指向的也不是*号,说明不匹配 + else { + return false; + } + } + + // 检查余下的模式串,模式串必须全都是*号才行 + while (p < pattern.length() && pattern.charAt(p) == '*') { + p++; + } + + return p == pattern.length(); + } +} diff --git a/[0045][Jump Game II]/[0045][Jump Game II].iml b/[0045][Jump Game II]/[0045][Jump Game II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0045][Jump Game II]/[0045][Jump Game II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0045][Jump Game II]/src/Solution.java b/[0045][Jump Game II]/src/Solution.java new file mode 100644 index 0000000..3f11ba2 --- /dev/null +++ b/[0045][Jump Game II]/src/Solution.java @@ -0,0 +1,49 @@ +/** + * 使用贪心算法,每次都移动最远的距离 + * + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:27 + **/ +public class Solution { + + public int jump(int[] nums) { + + if (nums == null || nums.length < 2) { + return 0; + } + + // 记录跳跃次数 + int jump = 0; + // 记录当前可以到达的最远的位置 + int currentMax = 0; + // 下一次可以到达的最远的位置 + int nextMax = 0; + // 记录处理的位置 + int i = 0; + + // 还没有到最未位置,还可以移动 + while (currentMax - i + 1 > 0) { + // 跳数增加 + jump++; + // 找下一次最远可以移动的位置 + for (; i <= currentMax; i++) { + nextMax = Math.max(nextMax, nums[i] + i); + // 如果下一次可以移动到最末的位置,则返回跳数 + if (nextMax >= nums.length - 1) { + return jump; + } + } + + // 本次处理不能使移动位增加,并且不能到达最末位置,说明永远到不了最后的位置 + if (currentMax == nextMax) { + return Integer.MAX_VALUE; + } + + // 更新当前可以移动的最远位置 + currentMax = nextMax; + } + + return 0; + } + +} diff --git a/[0046][Permutations]/[0046][Permutations].iml b/[0046][Permutations]/[0046][Permutations].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0046][Permutations]/[0046][Permutations].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0046][Permutations]/src/Solution.java b/[0046][Permutations]/src/Solution.java new file mode 100644 index 0000000..4f8f1ad --- /dev/null +++ b/[0046][Permutations]/src/Solution.java @@ -0,0 +1,65 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 16:50 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + private List> result; + + /** + *
+     * ԭ
+     * Given a collection of numbers, return all possible permutations.
+     * For example,
+     * [1,2,3] have the following permutations:
+     * [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
+     *
+     * Ŀ
+     * һ飬С
+     *
+     * ˼·
+     * ʹ÷η⡣
+     * 
+ * + * @param num + * @return + */ + public List> permute(int[] num) { + + result = new LinkedList<>(); + if (num != null) { + permute(0, num); + } + + return result; + } + + private void permute(int i, int[] nums) { + + if (i == nums.length) { + List l = new ArrayList<>(); + for (int n : nums) { + l.add(n); + } + result.add(l); + } else { + + for (int j = i; j < nums.length; j++) { + swap(nums, j, i); + permute(i + 1, nums); + swap(nums, j, i); + } + } + } + + private void swap(int[] nums, int x, int y) { + int tmp = nums[x]; + nums[x] = nums[y]; + nums[y] = tmp; + } +} diff --git a/[0047][Permutations II]/[0047][Permutations II].iml b/[0047][Permutations II]/[0047][Permutations II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0047][Permutations II]/[0047][Permutations II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0047][Permutations II]/src/Main.java b/[0047][Permutations II]/src/Main.java new file mode 100644 index 0000000..050363c --- /dev/null +++ b/[0047][Permutations II]/src/Main.java @@ -0,0 +1,14 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 18:01 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] nums = {1, 1, 2}; + System.out.println(solution.permuteUnique(nums)); + } +} diff --git a/[0047][Permutations II]/src/Solution.java b/[0047][Permutations II]/src/Solution.java new file mode 100644 index 0000000..8775cef --- /dev/null +++ b/[0047][Permutations II]/src/Solution.java @@ -0,0 +1,63 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:29 + **/ +public class Solution { + + public List> permuteUnique(int[] nums) { + List> res = new ArrayList<>(); + + if (nums == null || nums.length == 0) { + return res; + } + + boolean[] used = new boolean[nums.length]; + List list = new ArrayList<>(); + + Arrays.sort(nums); + + permuteUnique(nums, used, list, res); + return res; + } + + /** + * 时间复杂度:n! + * + * @param nums + * @param used + * @param list + * @param res + */ + private void permuteUnique(int[] nums, boolean[] used, List list, List> res) { + if (list.size() == nums.length) { + res.add(new ArrayList<>(list)); + return; + } + + for (int i = 0; i < nums.length; i++) { + // 第i个数值已经被使用过 + if (used[i]) { + continue; + } + + // 第i个字符与前一个字符相等,并且第i-1个字符没有使用,说明此次不应该交换 + if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) { + continue; + } + + // 标记第i个字符已经被使用 + used[i] = true; + // 添加到临时结果中 + list.add(nums[i]); + // 下一次处理 + permuteUnique(nums, used, list, res); + // 现场还原 + used[i] = false; + list.remove(list.size() - 1); + } + } +} diff --git a/[0048][Rotate Image]/[0048][Rotate Image].iml b/[0048][Rotate Image]/[0048][Rotate Image].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0048][Rotate Image]/[0048][Rotate Image].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0048][Rotate Image]/src/Solution.java b/[0048][Rotate Image]/src/Solution.java new file mode 100644 index 0000000..bba7234 --- /dev/null +++ b/[0048][Rotate Image]/src/Solution.java @@ -0,0 +1,28 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:31 + **/ +public class Solution { + public void rotate(int[][] matrix) { + int temp; + + // 先做y=x对称转换 + for (int i = 0; i < matrix.length; i++) { + for (int j = i; j < matrix.length; j++) { + temp = matrix[i][j]; + matrix[i][j] = matrix[j][i]; + matrix[j][i] = temp; + } + } + + // 再对行进行垂直转换 + int half = matrix.length / 2; + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < half; j++) { + temp = matrix[i][j]; + matrix[i][j] = matrix[i][matrix.length - 1 - j]; + matrix[i][matrix.length - 1 - j] = temp; + } + } + } +} diff --git a/[0049][Group Anagrams]/[0049][Group Anagrams].iml b/[0049][Group Anagrams]/[0049][Group Anagrams].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0049][Group Anagrams]/[0049][Group Anagrams].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0049][Group Anagrams]/src/Solution.java b/[0049][Group Anagrams]/src/Solution.java new file mode 100644 index 0000000..ef5973e --- /dev/null +++ b/[0049][Group Anagrams]/src/Solution.java @@ -0,0 +1,76 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:33 + **/ +public class Solution { + + public List> groupAnagrams(String[] strs) { + return groupAnagrams2(strs); + } + + /** + * 算法原理:对字符串进行排序,相同类型的字符串排序后的字符串都是一样的 + * + * @param strs + * @return + */ + public List> groupAnagrams1(String[] strs) { + if (strs.length == 0) { + return new ArrayList(); + } + Map ans = new HashMap<>(); + // 处理每一个字符串 + for (String s : strs) { + char[] ca = s.toCharArray(); + // 对象字符串对应的字符数组进行排序,再转成排序后的字符串 + Arrays.sort(ca); + String key = String.valueOf(ca); + // 如果map中不包含已经排序后的字符串,那么就创建一个新容器要放入结果 + if (!ans.containsKey(key)) { + ans.put(key, new ArrayList()); + } + + // 结果放入对应的集合中 + ans.get(key).add(s); + } + return new ArrayList(ans.values()); + } + + /** + * 算法原理:统计每个字符出现的次数,然后使用#字符将每个字符出现的次数拼成一个字符串, + * 相同类型的字符串通过上面的方式拼出来的字符串都是一样的 + * + * @param strs + * @return + */ + public List> groupAnagrams2(String[] strs) { + if (strs.length == 0) { + return new ArrayList(); + } + Map ans = new HashMap<>(); + int[] count = new int[26]; + + for (String s : strs) { + // 清零操作 + Arrays.fill(count, 0); + for (char c : s.toCharArray()) { + count[c - 'a']++; + } + + // 字符串拼接 + StringBuilder sb = new StringBuilder(""); + for (int i = 0; i < 26; i++) { + sb.append('#'); + sb.append(count[i]); + } + String key = sb.toString(); + if (!ans.containsKey(key)) { + ans.put(key, new ArrayList()); + } + ans.get(key).add(s); + } + return new ArrayList(ans.values()); + } +} diff --git a/[0050][Pow(x,n)]/[0050][Pow(x,n)].iml b/[0050][Pow(x,n)]/[0050][Pow(x,n)].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0050][Pow(x,n)]/[0050][Pow(x,n)].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221/src/Solution.java" b/[0050][Pow(x,n)]/src/Solution.java similarity index 100% rename from "\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221/src/Solution.java" rename to [0050][Pow(x,n)]/src/Solution.java diff --git a/[0051][N-Queens]/[0051][N-Queens].iml b/[0051][N-Queens]/[0051][N-Queens].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0051][N-Queens]/[0051][N-Queens].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0051][N-Queens]/src/Solution.java b/[0051][N-Queens]/src/Solution.java new file mode 100644 index 0000000..7d31661 --- /dev/null +++ b/[0051][N-Queens]/src/Solution.java @@ -0,0 +1,69 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:36 + **/ +public class Solution { + public List> solveNQueens(int n) { + List> result = new ArrayList<>(); + + if (n < 1) { + return result; + } + + char[][] board = new char[n][]; + for (int i = 0; i < n; i++) { + board[i] = new char[n]; + Arrays.fill(board[i], '.'); + } + + solveNQueens(board, 0, result); + return result; + } + + private void solveNQueens(char[][] board, int row, List> result) { + if (board.length == row) { + List list = new ArrayList<>(); + for (char[] chs : board) { + list.add(new String(chs)); + } + result.add(list); + } + + for (int col = 0; col < board.length; col++) { + if (canPlace(board, row, col)) { + board[row][col] = 'Q'; + solveNQueens(board, row + 1, result); + board[row][col] = '.'; + } + } + } + + private boolean canPlace(char[][] board, int row, int col) { + // 检测之前的列上是否已经放过皇后 + for (int i = 0; i < row; ++i) { + if (board[i][col] == 'Q') { + return false; + } + } + + // 45度角(左下角)上是否已经存在过皇后 + for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) { + if (board[i][j] == 'Q') { + return false; + } + } + + // 135度角上(左上角)是否已经存在过皇后 + for (int i = row - 1, j = col + 1; i >= 0 && j < board.length; --i, ++j) { + if (board[i][j] == 'Q') { + return false; + } + } + + return true; + } +} diff --git a/[0052][N-Queens II]/[0052][N-Queens II].iml b/[0052][N-Queens II]/[0052][N-Queens II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0052][N-Queens II]/[0052][N-Queens II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0052][N-Queens II]/src/Solution.java b/[0052][N-Queens II]/src/Solution.java new file mode 100644 index 0000000..5638da5 --- /dev/null +++ b/[0052][N-Queens II]/src/Solution.java @@ -0,0 +1,63 @@ +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:38 + **/ +public class Solution { + public int totalNQueens(int n) { + int[] result = {0}; + + if (n < 1) { + return result[0]; + } + + char[][] board = new char[n][]; + for (int i = 0; i < n; i++) { + board[i] = new char[n]; + Arrays.fill(board[i], '.'); + } + + solveNQueens(board, 0, result); + return result[0]; + } + + private void solveNQueens(char[][] board, int row, int[] result) { + if (board.length == row) { + result[0]++; + } + + for (int col = 0; col < board.length; col++) { + if (canPlace(board, row, col)) { + board[row][col] = 'Q'; + solveNQueens(board, row + 1, result); + board[row][col] = '.'; + } + } + } + + private boolean canPlace(char[][] board, int row, int col) { + // 检测之前的列上是否已经放过皇后 + for (int i = 0; i < row; ++i) { + if (board[i][col] == 'Q') { + return false; + } + } + + // 45度角(左下角)上是否已经存在过皇后 + for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) { + if (board[i][j] == 'Q') { + return false; + } + } + + // 135度角上(左上角)是否已经存在过皇后 + for (int i = row - 1, j = col + 1; i >= 0 && j < board.length; --i, ++j) { + if (board[i][j] == 'Q') { + return false; + } + } + + return true; + } +} \ No newline at end of file diff --git a/[0053][Maximum Subarray]/[0053][Maximum Subarray].iml b/[0053][Maximum Subarray]/[0053][Maximum Subarray].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0053][Maximum Subarray]/[0053][Maximum Subarray].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0053][Maximum Subarray]/src/Solution.java b/[0053][Maximum Subarray]/src/Solution.java new file mode 100644 index 0000000..4b97536 --- /dev/null +++ b/[0053][Maximum Subarray]/src/Solution.java @@ -0,0 +1,75 @@ +/** + * Author: + * Date: 2015-06-22 + * Time: 12:05 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given an integer array nums, find the contiguous subarray (containing at least one number)
+     * which has the largest sum and return its sum.
+     *
+     * Example:
+     *
+     * 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.
+     *
+     * Ŀ⣺
+     * ĺ
+     * ˼·
+     * ̬滮⣬֪ǰkԪصкΪmaxSubѾ¼ˣԼһʱsum
+     * ˵k+1Ԫأƣk+1Ԫ֮ǰĺС0ģ
+     * ôk+1ԪشӶȥûй׵ģԿ԰sum 0
+     *
+     * Ǵͷβʱ򣬶һмѡأֻ
+     * ѡ1֮ǰSubArray2. ԼһSubArrayʲôʱأ
+     * ֮ǰSubArray ʹ0 ĻΪԺй׵ġ
+     * ѡ֮ǰSubArray
+     * ֮ǰSubArray Ϊ0 С0 ĻΪԺûйף
+     * кģС0 ʱѡֿʼһSubArray
+     * ״̬Ϊf[j]ʾS[j] βкͣ״̬תƷ£
+     * f[j] = max {f[j - 1] + S[j]; S[j]} ; 1 <= j <= n
+     * target = max {f[j]}; 1 <= j <= n
+     * £
+     * һS[j] ǰijЩһУкΪf[j - 1] + S[j]
+     * S[j] ֳΪһΣнһS[j]кΪS[j]
+     *
+     * 
+ * + * @param nums + * @return + */ + public int maxSubArray(int[] nums) { + // У + if (nums == null || nums.length < 1) { + throw new IllegalArgumentException(); + } + + int max = Integer.MIN_VALUE; + int curSum = 0; + + for (int i : nums) { + // ǰС0ͽǰֵcurSum + if (curSum <= 0) { + curSum = i; + } + // ۼ + else { + curSum += i; + } + + // ϴֵ + if (max < curSum) { + max = curSum; + } + } + + return max; + } +} diff --git a/[0054][Spiral Matrix]/[0054][Spiral Matrix].iml b/[0054][Spiral Matrix]/[0054][Spiral Matrix].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0054][Spiral Matrix]/[0054][Spiral Matrix].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0054][Spiral Matrix]/[0054][SpiralMatrix].iml b/[0054][Spiral Matrix]/[0054][SpiralMatrix].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0054][Spiral Matrix]/[0054][SpiralMatrix].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221/src/Solution.java" b/[0054][Spiral Matrix]/src/Solution.java similarity index 100% rename from "\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221/src/Solution.java" rename to [0054][Spiral Matrix]/src/Solution.java diff --git a/[0055][Jump Game]/[0055][Jump Game].iml b/[0055][Jump Game]/[0055][Jump Game].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0055][Jump Game]/[0055][Jump Game].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0055][Jump Game]/src/Solution.java b/[0055][Jump Game]/src/Solution.java new file mode 100644 index 0000000..73b2d82 --- /dev/null +++ b/[0055][Jump Game]/src/Solution.java @@ -0,0 +1,72 @@ +/** + * Author: 王俊超 + * Date: 2015-06-19 + * Time: 19:29 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given an array of non-negative integers, you are initially positioned at the
+     * first index of the array.
+     *
+     * Each element in the array represents your maximum jump length at that position.
+     *
+     * Determine if you are able to reach the last index.
+     *
+     * For example:
+     * A = [2,3,1,1,4], return true.
+     * A = [3,2,1,0,4], return false.
+     *
+     * 题目大意:
+     * 给定的非负整数的数组,则最初定位在数组的第一个位置。数组中的每个元素都代表你的最大跳跃长度在那个位置。
+     * 决定你是否能到达最后一个索引。
+     *
+     * 
+ * + * @param nums + * @return + */ + public boolean canJump(int[] nums) { + return canJump2(nums); + } + + public boolean canJump1(int[] nums) { + if (nums == null || nums.length < 2) { + return true; + } + + // 最后可以移动的位置 + int lastPos = 0; + + // 处理每一个位置 + for (int i = 0; i < nums.length; i++) { + // i不能比lastPos大,否则说明不能走到i,走不到i也就不能走到最后 + // 如果在i位置可以移动的距离比已经记录到的最大距离还要大,那么更新最大的移动距离 + if (i <= lastPos && i + nums[i] > lastPos) { + lastPos = i + nums[i]; + } else if (i > lastPos) { + return false; + } + } + + // 最后的位置必然可以达到最后 + return lastPos >= nums.length - 1; + } + + /** + * 逆向,从最高层下楼梯,一层一层下降,看最后能不能下降到第0 层。 + * + * @param nums + * @return + */ + public boolean canJump2(int[] nums) { + int lastPos = nums.length - 1; + for (int i = nums.length - 1; i >= 0; i--) { + if (i + nums[i] >= lastPos) { + lastPos = i; + } + } + return lastPos == 0; + } +} diff --git a/[0056][Merge Intervals]/[0056][Merge Intervals].iml b/[0056][Merge Intervals]/[0056][Merge Intervals].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0056][Merge Intervals]/[0056][Merge Intervals].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/src/Interval.java" b/[0056][Merge Intervals]/src/Interval.java similarity index 100% rename from "\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/src/Interval.java" rename to [0056][Merge Intervals]/src/Interval.java diff --git a/[0056][Merge Intervals]/src/Solution.java b/[0056][Merge Intervals]/src/Solution.java new file mode 100644 index 0000000..7f0df6a --- /dev/null +++ b/[0056][Merge Intervals]/src/Solution.java @@ -0,0 +1,63 @@ +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-23 + * Time: 19:39 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * 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].
+     *
+     * Ŀ⣬
+     * һ伯ϣϲص
+     *
+     * ˼·
+     * ȶ򣬰ʼһһкϲ
+     * 
+ * + * @param intervals + * @return + */ + public List merge(List intervals) { + List result = new LinkedList<>(); + + if (intervals == null || intervals.size() < 1) { + return result; + } + + // ȶʹһڲ + Collections.sort(intervals, new Comparator() { + @Override + public int compare(Interval o1, Interval o2) { + return o1.start - o2.start; + } + }); + + // 󣬺һԪأΪnextstartһDzСǰһΪprevstartģ + // ӵ䣬next.startprev.end˵ǷֿģҪ + // һµ䣬˵next.start[prev.start, prev.end]ڣֻҪ + // next.endǷǴprev.endھҪϲ䣨 + Interval prev = null; + for (Interval item : intervals) { + + if (prev == null || prev.end < item.start) { + result.add(item); + prev = item; + } else if (prev.end < item.end) { + prev.end = item.end; + } + } + + return result; + } +} diff --git a/[0057][Insert Interval]/[0057][Insert Interval].iml b/[0057][Insert Interval]/[0057][Insert Interval].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0057][Insert Interval]/[0057][Insert Interval].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/src/Interval.java" b/[0057][Insert Interval]/src/Interval.java similarity index 100% rename from "\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/src/Interval.java" rename to [0057][Insert Interval]/src/Interval.java diff --git a/[0057][Insert Interval]/src/Solution.java b/[0057][Insert Interval]/src/Solution.java new file mode 100644 index 0000000..7486cdb --- /dev/null +++ b/[0057][Insert Interval]/src/Solution.java @@ -0,0 +1,74 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-24 + * Time: 19:33 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a set of non-overlapping intervals, insert a new interval into the intervals
+     * (merge if necessary).
+     *
+     * 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].
+     *
+     * 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].
+     *
+     * Ŀ⣺
+     * һϵзǸǵ䣬һµ䣬бҪʱϲ
+     * 俪ʼʼʱкϲ
+     *
+     * ˼·
+     * ԭȲСͲص²䣬
+     * Сԭ䣬Ȳ䣬Ӵ
+     * 
+ * + * @param intervals + * @param newInterval + * @return + */ + public List insert(List intervals, Interval newInterval) { + + // ļ + List result = new LinkedList<>(); + + // 뼯ǿ + if (intervals != null) { + // Ԫ + for (Interval item : intervals) { + // newInterval == null ʾѾ + // ȲС + if (newInterval == null || item.end < newInterval.start) { + result.add(item); + } + // ȲУͬʱ + else if (item.start > newInterval.end) { + result.add(newInterval); + result.add(item); + newInterval = null; + } + // ص² + else { + newInterval.start = Math.min(newInterval.start, item.start); + newInterval.end = Math.max(newInterval.end, item.end); + } + } + } + + // ǿ˵仹δ + if (newInterval != null) { + result.add(newInterval); + } + + return result; + } +} diff --git a/[0058][Length Of Last Word]/[0058][Length Of Last Word].iml b/[0058][Length Of Last Word]/[0058][Length Of Last Word].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0058][Length Of Last Word]/[0058][Length Of Last Word].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221/src/Solution.java" b/[0058][Length Of Last Word]/src/Solution.java similarity index 100% rename from "\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221/src/Solution.java" rename to [0058][Length Of Last Word]/src/Solution.java diff --git a/[0059][Spiral Matrix II]/[0059][Spiral Matrix II].iml b/[0059][Spiral Matrix II]/[0059][Spiral Matrix II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0059][Spiral Matrix II]/[0059][Spiral Matrix II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0059][Spiral Matrix II]/[0059][SpiralMatrixII].iml b/[0059][Spiral Matrix II]/[0059][SpiralMatrixII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0059][Spiral Matrix II]/[0059][SpiralMatrixII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221/src/Solution.java" b/[0059][Spiral Matrix II]/src/Solution.java similarity index 100% rename from "\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221/src/Solution.java" rename to [0059][Spiral Matrix II]/src/Solution.java diff --git a/[0060][Permutation Sequence]/[0060][Permutation Sequence].iml b/[0060][Permutation Sequence]/[0060][Permutation Sequence].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0060][Permutation Sequence]/[0060][Permutation Sequence].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0060][Permutation Sequence]/src/Solution.java b/[0060][Permutation Sequence]/src/Solution.java new file mode 100644 index 0000000..3bc2edf --- /dev/null +++ b/[0060][Permutation Sequence]/src/Solution.java @@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:45 + **/ +public class Solution { + /** + *
+     * 利用康托编码的思路,假设有n 个不重复的元素,第k 个排列是a1; a2; a3; :::; an,那么a1 是
+     * 哪一个位置呢?
+     * 我们把a1 去掉,那么剩下的排列为a2; a3; :::; an, 共计n-1 个元素,n-1 个元素共有(n-1)!
+     * 个排列,于是就可以知道a1 = k/(n - 1)!。
+     * 同理,a2; a3; :::; an 的值推导如下:
+     * k2 = k%(n - 1)!
+     * a2 = k2/(n - 2)!
+     * ...
+     * k(n-1) = k(n-2)%2!
+     * a(n-1) = k(n-1)/1!
+     * an = 0
+     * 
+ * + * @param n + * @param k + * @return + */ + public String getPermutation(int n, int k) { + + StringBuilder sb = new StringBuilder(); + List num = new ArrayList<>(); + // 用于计录最大的阶乘数 + int fact = 1; + for (int i = 1; i <= n; i++) { + fact *= i; + num.add(i); + } + + // l = k - 1;为了方便从0开始计数 + int index; + for (int i = 0, l = k - 1; i < n; i++) { + // 从最大的阶乘数开始减少 + // fact的值说明,如果从 __1____ -> _2____ 至少要经过fact次变换 + fact /= (n - i); + // 计算剩下的数据中的索引 + // 说明类似 __1____ -> _2____ 的变化可以做 index 次,0表示不用变 + index = (l / fact); + // 将索引值添加到结果中 + // 每做一次__1____ -> _2____ 的变化,表示在num中取后一个更大的值 + sb.append(num.remove(index)); + // 余下要处理的数 + l -= index * fact; + } + + return sb.toString(); + } +} diff --git a/[0061][Rotate List]/[0061][Rotate List].iml b/[0061][Rotate List]/[0061][Rotate List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0061][Rotate List]/[0061][Rotate List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/src/ListNode.java" b/[0061][Rotate List]/src/ListNode.java similarity index 100% rename from "\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/src/ListNode.java" rename to [0061][Rotate List]/src/ListNode.java diff --git a/[0061][Rotate List]/src/Solution.java b/[0061][Rotate List]/src/Solution.java new file mode 100644 index 0000000..9f4e91d --- /dev/null +++ b/[0061][Rotate List]/src/Solution.java @@ -0,0 +1,34 @@ +/** + * Author: + * Date: 2015-07-21 + * Time: 18:46 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + public ListNode rotateRight(ListNode head, int n) { + + if (head == null || n < 1) { + return head; + } + + int length = 1; + ListNode p = head; + while (p.next != null) { + p = p.next; + length++; + } + + // ҪĽڵΪheadǰһڵ + n = length - n % length; + + // β + p.next = head; + for (int i = 0; i < n; i++) { + p = p.next; + } + + head = p.next; + p.next = null; + return head; + } +} diff --git a/[0061][Rotate List]/src/Solution2.java b/[0061][Rotate List]/src/Solution2.java new file mode 100644 index 0000000..00ca18f --- /dev/null +++ b/[0061][Rotate List]/src/Solution2.java @@ -0,0 +1,62 @@ +/** + * Author: + * Date: 2015-07-21 + * Time: 18:46 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + public ListNode rotateRight(ListNode head, int n) { + + if (head == null || n < 1) { + return head; + } + + ListNode root = new ListNode(0); + root.next = head; + ListNode p = root; + ListNode q = root; + + // תλÿܱ + int count = 0; + for (int i = 0; i <= n; i++) { + p = p.next; + count++; + if (p == null) { + // гͷݸ + count--; + // ʵҪλõλ + n = n % count; + // Ϊ¿ʼλ׼ + i = 0; + p = head; + } + } + + // ҵһҪĽǰ + // qΪһҪĽǰ + while (p != null) { + p = p.next; + q = q.next; + + } + + p = q; + q = root; + // ҪλƵĽ + if (p != null && p.next != null) { + ListNode node; + while (p.next != null) { + // ժ + node = p.next; + p.next = node.next; + // Ͻ + node.next = q.next; + q.next = node; + // һƶĽڵ + q = node; + } + } + + return root.next; + } +} diff --git a/[0062][Unique Paths]/[0062][Unique Paths].iml b/[0062][Unique Paths]/[0062][Unique Paths].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0062][Unique Paths]/[0062][Unique Paths].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0062][Unique Paths]/[0062][UniquePaths].iml b/[0062][Unique Paths]/[0062][UniquePaths].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0062][Unique Paths]/[0062][UniquePaths].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0062][Unique Paths]/src/Solution.java b/[0062][Unique Paths]/src/Solution.java new file mode 100644 index 0000000..43be774 --- /dev/null +++ b/[0062][Unique Paths]/src/Solution.java @@ -0,0 +1,63 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:30 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * A robot is located at the top-left corner of a m x n grid
+     * (marked Start in the diagram below).
+     * The robot can only move either down or right at any point in time.
+     * The robot is trying to reach the bottom-right corner of the grid
+     * (marked Finish in the diagram below).
+     * How many possible unique paths are there?
+     *
+     * Above is a 3 x 7 grid. How many possible unique paths are there?
+     * Note: m and n will be at most 100.
+     *
+     * Ŀ
+     * һһm*nķϽǡ
+     * ֻһһ񣬻Ҫ½ǵķ
+     * һжΨһ·
+     * ע⣺ͣ󲻳100
+     *
+     * ˼·
+     * ͵Ķ̬滮⣬ʹö̬滮ķ⡣
+     * һm*nA
+     * AеԪС
+     * 1x=0y=0ʱA[x][y] = 1
+     * 2x>=1y>=1ʱA[x][y] = A[x-1][y]+A[x][y-1]
+     * 3ĽA[m-1][n-1]
+     * 
+ * + * @param m + * @param n + * @return + */ + public int uniquePaths(int m, int n) { + int[][] result = new int[m][n]; + + // һеĽ + for (int i = 0; i < m; i++) { + result[i][0] = 1; + } + + // һеĽ + for (int i = 1; i < n; i++) { + result[0][i] = 1; + } + + // λõĽ + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + result[i][j] = result[i - 1][j] + result[i][j - 1]; + } + } + + // Ľ + return result[m - 1][n - 1]; + } +} diff --git a/[0063][Unique Paths II]/[0063][Unique Paths II].iml b/[0063][Unique Paths II]/[0063][Unique Paths II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0063][Unique Paths II]/[0063][Unique Paths II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0063][Unique Paths II]/[0063][UniquePathsII].iml b/[0063][Unique Paths II]/[0063][UniquePathsII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0063][Unique Paths II]/[0063][UniquePathsII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221/src/Solution.java" b/[0063][Unique Paths II]/src/Solution.java similarity index 100% rename from "\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221/src/Solution.java" rename to [0063][Unique Paths II]/src/Solution.java diff --git a/[0064][Minimum Path Sum]/[0064][Minimum Path Sum].iml b/[0064][Minimum Path Sum]/[0064][Minimum Path Sum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0064][Minimum Path Sum]/[0064][Minimum Path Sum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0064][Minimum Path Sum]/[0064][MinimumPathSum].iml b/[0064][Minimum Path Sum]/[0064][MinimumPathSum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0064][Minimum Path Sum]/[0064][MinimumPathSum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/src/Main.java" b/[0064][Minimum Path Sum]/src/Main.java similarity index 100% rename from "\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/src/Main.java" rename to [0064][Minimum Path Sum]/src/Main.java diff --git "a/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/src/Solution.java" b/[0064][Minimum Path Sum]/src/Solution.java similarity index 100% rename from "\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/src/Solution.java" rename to [0064][Minimum Path Sum]/src/Solution.java diff --git a/[0065][Valid Number]/[0065][Valid Number].iml b/[0065][Valid Number]/[0065][Valid Number].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0065][Valid Number]/[0065][Valid Number].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0065][Valid Number]/src/Main.java b/[0065][Valid Number]/src/Main.java new file mode 100644 index 0000000..c039e9e --- /dev/null +++ b/[0065][Valid Number]/src/Main.java @@ -0,0 +1,95 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 13:32 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.isNumber("0")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.isNumber(" 0.1 ")); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber("abc")); + } + + @Test + public void test4() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber("1 a")); + } + + @Test + public void test41() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.isNumber("2e10")); + } + + @Test + public void test42() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.isNumber(" -90e3 ")); + } + + @Test + public void test5() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber(" 1e")); + } + + @Test + public void test6() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber("e3")); + } + + + @Test + public void test7() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.isNumber(" 6e-1")); + } + + @Test + public void test8() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber(" 99e2.5 ")); + } + + + @Test + public void test9() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.isNumber("53.5e93")); + } + + @Test + public void test10() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber(" --6 ")); + } + + @Test + public void test11() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber("-+3")); + } + + @Test + public void test12() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isNumber("95a54e53")); + } + +} diff --git a/[0065][Valid Number]/src/Solution.java b/[0065][Valid Number]/src/Solution.java new file mode 100644 index 0000000..3f6d642 --- /dev/null +++ b/[0065][Valid Number]/src/Solution.java @@ -0,0 +1,100 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 13:20 + **/ +public class Solution { + + /** + * 序数就分别为0, 1, 2, 3, 4, 5, 6 + */ + private enum InputType { + INVALID, + SPACE, + SIGN, + DIGIT, + DOT, + EXPONENT + } + + // 状态转表 TODO 每个状态是什么意思? + private final static int[][] TRANSITION_TABLE = { + {-1, 0, 3, 1, 2, -1}, // next states for state 0 + {-1, 8, -1, 1, 4, 5}, // next states for state 1 + {-1, -1, -1, 4, -1, -1},// next states for state 2 + {-1, -1, -1, 1, 2, -1,},// next states for state 3 + {-1, 8, -1, 4, -1, 5},// next states for state 4 + {-1, -1, 6, 7, -1, -1},// next states for state 5 + {-1, -1, -1, 7, -1, -1},// next states for state 6 + {-1, 8, -1, 7, -1, -1},// next states for state 7 + {-1, 8, -1, -1, -1, -1},// next states for state 8 + }; + + /** + *
+     * Validate if a given string can be interpreted as a decimal number.
+     *
+     * Some examples:
+     * "0" => true
+     * " 0.1 " => true
+     * "abc" => false
+     * "1 a" => false
+     * "2e10" => true
+     * " -90e3   " => true
+     * " 1e" => false
+     * "e3" => false
+     * " 6e-1" => true
+     * " 99e2.5 " => false
+     * "53.5e93" => true
+     * " --6 " => false
+     * "-+3" => false
+     * "95a54e53" => false
+     *
+     * Note: It is intended for the problem statement to be ambiguous. You should gather all requirements
+     * up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
+     *
+     * Numbers 0-9
+     * Exponent - "e"
+     * Positive/negative sign - "+"/"-"
+     * Decimal point - "."
+     * Of course, the context of these characters also matters in the input.
+     * 
+ * + * @param s + * @return + */ + public boolean isNumber(String s) { + int state = 0; + for (int i = 0; i < s.length(); i++) { + InputType inputType = InputType.INVALID; + if (Character.isSpaceChar(s.charAt(i))) { + inputType = InputType.SPACE; + } else if (s.charAt(i) == '+' || s.charAt(i) == '-') { + inputType = InputType.SIGN; + } else if (Character.isDigit(s.charAt(i))) { + inputType = InputType.DIGIT; + } else if (s.charAt(i) == '.') { + inputType = InputType.DOT; + } else if (s.charAt(i) == 'e' || s.charAt(i) == 'E') { + inputType = InputType.EXPONENT; + } + // Get next state from current state and input symbol + state = TRANSITION_TABLE[state][inputType.ordinal()]; + + // Invalid input + if (state == -1) { + return false; + } + } + // If the current state belongs to one of the accepting (final) states, + // then the number is valid + return state == 1 || state == 4 || state == 7 || state == 8; + } + + private boolean isDigit(char charAt) { + return charAt >= '0' && charAt <= '9'; + } + + private boolean isSpace(char charAt) { + return charAt == ' '; + } +} diff --git a/[0066][Plus One]/[0066][Plus One].iml b/[0066][Plus One]/[0066][Plus One].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0066][Plus One]/[0066][Plus One].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0066][Plus One]/src/Solution.java b/[0066][Plus One]/src/Solution.java new file mode 100644 index 0000000..efc7195 --- /dev/null +++ b/[0066][Plus One]/src/Solution.java @@ -0,0 +1,55 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:32 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given a non-negative number represented as an array of digits, plus one to the number.
+     * The digits are stored such that the most significant digit is at the head of the list.
+     *
+     * Ŀ
+     * һʾһмһ
+     * ÿһλ洢һλϡ±ӴСʾλӵλλ
+     *
+     * ˼·
+     * ֱ⣬һλ־carryֵΪ1ʾ1λʼtmp = a[x] + carry
+     * a[x] = tmp%10carry = tmp/10carryΪ0һλٽвֱеλcarray
+     * Ϊ0˳carrayΪ0˵Ҫչһλ
+     * 
+ * + * @param digits + * @return + */ + public int[] plusOne(int[] digits) { + + // λ־һλĽλ־ + int carry = 1; + int tmp; + for (int i = digits.length - 1; i >= 0; i--) { + tmp = digits[i]; + // 㵱ǰλֵ + digits[i] = (tmp + carry) % 10; + // µĽλ + carry = (tmp + carry) / 10; + + // ûнλ˾Ϳ˳ + if (carry == 0) { + break; + } + } + + // һλ + if (carry == 1) { + int[] result = new int[digits.length + 1]; + System.arraycopy(digits, 0, result, 1, digits.length); + result[0] = carry; + return result; + } else { + return digits; + } + } +} diff --git a/[0067][Add Binary]/[0067][Add Binary].iml b/[0067][Add Binary]/[0067][Add Binary].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0067][Add Binary]/[0067][Add Binary].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221/src/Solution.java" b/[0067][Add Binary]/src/Solution.java similarity index 100% rename from "\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221/src/Solution.java" rename to [0067][Add Binary]/src/Solution.java diff --git a/[0069][Sqrt(x)]/[0069][Sqrt(x)].iml b/[0069][Sqrt(x)]/[0069][Sqrt(x)].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0069][Sqrt(x)]/[0069][Sqrt(x)].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0069][Sqrt(x)]/src/Solution.java b/[0069][Sqrt(x)]/src/Solution.java new file mode 100644 index 0000000..d1cc9c3 --- /dev/null +++ b/[0069][Sqrt(x)]/src/Solution.java @@ -0,0 +1,87 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-23 15:09 + **/ +public class Solution { + /** + *
+     * 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.
+     * 
+ * + * @param x + * @return + */ + public int mySqrt(int x) { + return mySqrt2(x); + } + + /** + * 使用二分法 + *
+     * 思路:要实现一个sqrt函数,可以使用二分法,首先确定一个范围[begin, end],这个范围的中间数mid,
+     * 看mid的平方是否等于x,如果相等,则返回mid,如果不等则缩小[begin,end]的范围,为原来的一半。这
+     * 里的初始范围可以是[1, x],也可以是更精确一些的[1, (x/2) + 1]。(因 (x/2) + 1 的平方等于
+     * x+1+(x^2/4),它一定大于x,所以,x的平方根一定在[1, (x/2) + 1]范围内)
+     *
+     * 
+ * + * @param x + * @return + */ + public int mySqrt1(int x) { + if (x == 0) { + return 0; + } + int left = 1; + int right = x; + while (true) { + int mid = left + (right - left) / 2; + if (mid > x / mid) { + right = mid - 1; + } else { + if (mid + 1 > x / (mid + 1)) { + return mid; + } + left = mid + 1; + } + } + } + + /** + * 使用牛顿法 + *
+     * x^2 = a的解,也就是函数f(x) = x^2 – a与x轴的交点。可以在x轴上先任选一点x0,则点(x0, f(x0))
+     * 在f(x)上的切线,与x轴的交点为x1,它们满足切线的方程:f(x0)=(x0-x1)f’(x0),可得x1更接近最终的
+     * 结果,解方程得到:
+     * 切线方程:y = 2x0(x - x0) + x0^2 - a,令y=0 -> x = (x0 + (a/x0))/2,即为x1的值
+     *
+     * x1 = (x0 + (a/x0))/2。以x1为新的x0,按照切线的方法依次迭代下去,最终求得符合精确度要求的结果值。
+     * 
+ * + * @param x + * @return + */ + public int mySqrt2(int x) { + long r = x; + while (r * r > x) { + r = (r + x / r) / 2; + } + return (int) r; + } +} diff --git a/[0070][Climbing Stairs]/[0070][Climbing Stairs].iml b/[0070][Climbing Stairs]/[0070][Climbing Stairs].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0070][Climbing Stairs]/[0070][Climbing Stairs].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0070][Climbing Stairs]/src/Solution.java b/[0070][Climbing Stairs]/src/Solution.java new file mode 100644 index 0000000..a475bb0 --- /dev/null +++ b/[0070][Climbing Stairs]/src/Solution.java @@ -0,0 +1,48 @@ +/** + * Author: + * Date: 2015-07-25 + * Time: 09:10 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * f(n) ʾn ¥ݵIJͬΪn ¥ݣѡ
+     * - ӵn - 1 ǰ1 
+     * - ӵn - 1 ǰ2 
+     * ˣf(n) = f(n - 1) + f(n - 2)
+     * 
+ * + * @param n + * @return + */ + public int climbStairs(int n) { + + int result = 0; + + // ֻһ + if (n == 1) { + result = 1; + } + // ֻ + else if (n == 2) { + result = 2; + } + // ¥ݽ2 + else if (n > 2) { + // еĽⷨ + int[] ways = new int[n]; + + ways[0] = 1; + ways[1] = 2; + + for (int i = 2; i < ways.length; i++) { + ways[i] = ways[i - 1] + ways[i - 2]; + } + + result = ways[ways.length - 1]; + } + + return result; + } +} diff --git a/[0071][Simplify Path]/[0071][Simplify Path].iml b/[0071][Simplify Path]/[0071][Simplify Path].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0071][Simplify Path]/[0071][Simplify Path].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0071][Simplify Path]/src/Solution.java b/[0071][Simplify Path]/src/Solution.java new file mode 100644 index 0000000..c17fc59 --- /dev/null +++ b/[0071][Simplify Path]/src/Solution.java @@ -0,0 +1,32 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 15:50 + **/ +public class Solution { + public String simplifyPath(String path) { + String[] ss = path.split("/"); + List result = new LinkedList<>(); + + for (String part : ss) { + if (".".equals(part)) { + continue; + } else if ("..".equals(part)) { + if (result.size() > 0) { + result.remove(result.size() - 1); + } + } else if (!"".equals(part.trim())) { + result.add(part); + } + } + + StringBuilder builder = new StringBuilder(); + for (String part : result) { + builder.append("/").append(part); + } + + return builder.length() == 0 ? "/" : builder.toString(); + } +} diff --git a/[0073][Set Matrix Zeroes]/[0073][Set Matrix Zeroes].iml b/[0073][Set Matrix Zeroes]/[0073][Set Matrix Zeroes].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0073][Set Matrix Zeroes]/[0073][Set Matrix Zeroes].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0073][Set Matrix Zeroes]/[0073][SetMatrixZeroes].iml b/[0073][Set Matrix Zeroes]/[0073][SetMatrixZeroes].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0073][Set Matrix Zeroes]/[0073][SetMatrixZeroes].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0073][Set Matrix Zeroes]/src/Solution.java b/[0073][Set Matrix Zeroes]/src/Solution.java new file mode 100644 index 0000000..e0d6ab2 --- /dev/null +++ b/[0073][Set Matrix Zeroes]/src/Solution.java @@ -0,0 +1,58 @@ +/** + * Author: + * Date: 2015-07-25 + * Time: 09:27 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + public void setZeroes(int[][] matrix) { + // һбõı־ + boolean rowFlag = false; + // һбõı־ + boolean colFlag = false; + + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] == 0) { + // ǵһҪ + if (i == 0) { + rowFlag = true; + } + + // ǵһҪ + if (j == 0) { + colFlag = true; + } + + // ڱҪΪ0к + matrix[0][j] = 0; + matrix[i][0] = 0; + } + } + } + + // ԵڶеڶпʼԪ0 + for (int i = 1; i < matrix.length; i++) { + for (int j = 1; j < matrix[0].length; j++) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + + // õһΪ0 + if (rowFlag) { + for (int j = 0; j < matrix[0].length; j++) { + matrix[0][j] = 0; + } + } + + // õһΪ0 + if (colFlag) { + for (int i = 0; i < matrix.length; i++) { + matrix[i][0] = 0; + } + } + + } +} diff --git a/[0074][Search A 2D Matrix]/[0074][Search A 2D Matrix].iml b/[0074][Search A 2D Matrix]/[0074][Search A 2D Matrix].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0074][Search A 2D Matrix]/[0074][Search A 2D Matrix].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0074][Search A 2D Matrix]/[0074][SearchA2DMatrix].iml b/[0074][Search A 2D Matrix]/[0074][SearchA2DMatrix].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0074][Search A 2D Matrix]/[0074][SearchA2DMatrix].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0074][Search A 2D Matrix]/src/Main.java b/[0074][Search A 2D Matrix]/src/Main.java new file mode 100644 index 0000000..4206b6b --- /dev/null +++ b/[0074][Search A 2D Matrix]/src/Main.java @@ -0,0 +1,16 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 16:11 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + int[][] matrix = {{1, 3}}; + Assert.assertEquals(true, solution.searchMatrix(matrix, 3)); + } +} diff --git a/[0074][Search A 2D Matrix]/src/Solution.java b/[0074][Search A 2D Matrix]/src/Solution.java new file mode 100644 index 0000000..4942ee4 --- /dev/null +++ b/[0074][Search A 2D Matrix]/src/Solution.java @@ -0,0 +1,62 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:36 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
+     * Integers in each row are sorted from left to right.
+     * The first integer of each row is greater than the last integer of the previous row.
+     * For example,
+     * Consider the following matrix:Given target = 3, return true.
+     *
+     * [
+     *  [1,   3,  5,  7],
+     *  [10, 11, 16, 20],
+     *  [23, 30, 34, 50]
+     * ]
+     *
+     * Ŀ
+     * һάʵһ㷨ھʵֿkھk
+     * ʣÿһÿһжźģÿһеĵһһеһ
+     *
+     * ˼·
+     * ⷨһö鿴㷨ҵڵУö㷨ڵСҵͷtrue򷵻false
+     * 
+ * + * @param matrix + * @param target + * @return + */ + public boolean searchMatrix(int[][] matrix, int target) { + + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return false; + } + + int row = matrix.length; + int column = matrix[0].length; + int low = 0; + int high = row * column - 1; + int mid; + + // ҽڵ + while (low <= high) { + mid = low + (high - low) / 2; + int value = matrix[mid / column][mid % column]; + if (value == target) { + return true; + } else if (value < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return false; + } +} diff --git a/[0074][Search A 2D Matrix]/src/Solution2.java b/[0074][Search A 2D Matrix]/src/Solution2.java new file mode 100644 index 0000000..0a5ed46 --- /dev/null +++ b/[0074][Search A 2D Matrix]/src/Solution2.java @@ -0,0 +1,88 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:36 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * ԭ
+     * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
+     * Integers in each row are sorted from left to right.
+     * The first integer of each row is greater than the last integer of the previous row.
+     * For example,
+     * Consider the following matrix:Given target = 3, return true.
+     *
+     * [
+     *  [1,   3,  5,  7],
+     *  [10, 11, 16, 20],
+     *  [23, 30, 34, 50]
+     * ]
+     *
+     * Ŀ
+     * һάʵһ㷨ھʵֿkھk
+     * ʣÿһÿһжźģÿһеĵһһеһ
+     *
+     * ˼·
+     * ⷨһö鿴㷨ҵڵУö㷨ڵСҵͷtrue򷵻false
+     * 
+ * + * @param matrix + * @param target + * @return + */ + public boolean searchMatrix(int[][] matrix, int target) { + + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return false; + } + + int row = matrix.length; + int column = matrix[0].length; + int low = 0; + int high = row - 1; + int mid = 0; + + // ҽڵ + while (low <= high) { + mid = low + (high - low) / 2; + + if (target < matrix[mid][column - 1]) { + high = mid - 1; + } else if (target > matrix[mid][column - 1]) { + low = mid + 1; + } else { + return true; + } + } + + // ڵλ + int targetRow = mid; + if (matrix[mid][column - 1] < target) { + targetRow++; + } + + // Ŀг޽ + if (targetRow >= row) { + return false; + } + + low = 0; + high = column - 1; + // ڵУҵtrueûзfalse + while (low <= high) { + mid = low + (high - low) / 2; + + if (target < matrix[targetRow][mid]) { + high = mid - 1; + } else if (target > matrix[targetRow][mid]) { + low = mid + 1; + } else { + return true; + } + } + + return false; + } +} diff --git a/[0075][Sort Colors]/[0075][Sort Colors].iml b/[0075][Sort Colors]/[0075][Sort Colors].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0075][Sort Colors]/[0075][Sort Colors].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0075][Sort Colors]/[0075][SortColors].iml b/[0075][Sort Colors]/[0075][SortColors].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0075][Sort Colors]/[0075][SortColors].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0075][Sort Colors]/src/Main.java b/[0075][Sort Colors]/src/Main.java new file mode 100644 index 0000000..a29defe --- /dev/null +++ b/[0075][Sort Colors]/src/Main.java @@ -0,0 +1,33 @@ +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 14:52 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] colors = {2, 0, 2, 1, 1, 0}; + solution.sortColors(colors); + System.out.println(Arrays.toString(colors)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + int[] colors = {2, 0, 1}; + solution.sortColors(colors); + System.out.println(Arrays.toString(colors)); + } + + @Test + public void test3() { + Solution solution = new Solution(); + int[] colors = {0}; + solution.sortColors(colors); + System.out.println(Arrays.toString(colors)); + } +} diff --git a/[0075][Sort Colors]/src/Solution.java b/[0075][Sort Colors]/src/Solution.java new file mode 100644 index 0000000..2f930cc --- /dev/null +++ b/[0075][Sort Colors]/src/Solution.java @@ -0,0 +1,68 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:37 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given an array with n objects colored red, white or blue, sort them so that objects
+     * of the same color are adjacent, with the colors in the order red, white and blue.
+     * Here, we will use the integers 0, 1, and 2 to represent the color red, white,
+     * and blue respectively.
+     * Note:
+     * You are not suppose to use the librarys sort function for this problem.
+     *
+     * Ŀ
+     * һ飬Ǻɫɫɫɫ򣬺죬ף
+     * ʹ012ֱ죬ף
+     * ע⣺ʹÿ⺯
+     *
+     * ˼·
+     * һֱ012ֵĴٽ鸳ֵ
+     * 
+ * + * @param nums + */ + public void sortColors(int[] nums) { + + if (nums == null) { + return; + } + + int[] count = new int[3]; + + for (int n : nums) { + count[n]++; + } + + int start = 0; + int end = 0; + for (int i = 0; i < count.length; i++) { + if (i == 0) { + start = 0; + } else { + start += count[i - 1]; + } + end += count[i]; + for (int j = start; j < end; j++) { + nums[j] = i; + } + } + + // ϶ĸĽ +// for (int i = 0; i < count[0]; i++) { +// nums[i] = 0; +// } +// +// for (int i = count[0]; i < count[0] + count[1]; i++) { +// nums[i] = 1; +// } +// +// for (int i = count[0] + count[1]; i < nums.length; i++) { +// nums[i] = 2; +// } + } +} diff --git a/[0075][Sort Colors]/src/Solution2.java b/[0075][Sort Colors]/src/Solution2.java new file mode 100644 index 0000000..ac7b270 --- /dev/null +++ b/[0075][Sort Colors]/src/Solution2.java @@ -0,0 +1,71 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:37 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * ԭ
+     * Given an array with n objects colored red, white or blue, sort them so that objects
+     * of the same color are adjacent, with the colors in the order red, white and blue.
+     * Here, we will use the integers 0, 1, and 2 to represent the color red, white,
+     * and blue respectively.
+     * Note:
+     * You are not suppose to use the librarys sort function for this problem.
+     *
+     * Ŀ
+     * һ飬Ǻɫɫɫɫ򣬺죬ף
+     * ʹ012ֱ죬ף
+     * ע⣺ʹÿ⺯
+     *
+     * ˼·
+     * ɨ裬¼1ĸĺ͡ɨԵó1Ŀt2Ŀ(sum-t)/2
+     * Եó0ĿӸ012Ŀٶֵ
+     * 
+ * + * @param A + */ + public void sortColors(int[] A) { + + if (A == null) { + return; + } + + // ͳ1ĸ + int count = 0; + + // ͳĺ + int sum = 0; + + for (int i : A) { + if (i == 1) { + count++; + } + + sum += i; + } + + // 2Ŀ + sum = (sum - count) / 2; + + // 1ʼֵλ + count = A.length - count - sum; + + // 2ʼֵλ + sum = A.length - sum; + + for (int i = 0; i < count; i++) { + A[i] = 0; + } + + for (int i = count; i < sum; i++) { + A[i] = 1; + } + + for (int i = sum; i < A.length; i++) { + A[i] = 2; + } + } +} diff --git a/[0077][Combinations]/[0077][Combinations].iml b/[0077][Combinations]/[0077][Combinations].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0077][Combinations]/[0077][Combinations].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0077][Combinations]/src/Main.java b/[0077][Combinations]/src/Main.java new file mode 100644 index 0000000..e4021a1 --- /dev/null +++ b/[0077][Combinations]/src/Main.java @@ -0,0 +1,15 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 19:04 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + System.out.println(solution.combine(4, 2)); + } + +} diff --git a/[0077][Combinations]/src/Solution.java b/[0077][Combinations]/src/Solution.java new file mode 100644 index 0000000..7d055e8 --- /dev/null +++ b/[0077][Combinations]/src/Solution.java @@ -0,0 +1,62 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 19:39 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + + /** + *
+     * ԭ
+     * Given two integers n and k, return all possible combinations of k numbers out of 1  n.
+     * For example,
+     * If n = 4 and k = 2, a solution is:
+     *
+     * [
+     *  [2,4],
+     *  [3,4],
+     *  [2,3],
+     *  [1,2],
+     *  [1,3],
+     *  [1,4],
+     * ]
+     *
+     * Ŀ
+     * nk1-nkϡ
+     *
+     * ˼·
+     * ʹùŻ㷨
+     * 
+ * + * @param n + * @param k + * @return + */ + public List> combine(int n, int k) { + List> result = new LinkedList<>(); + List current = new LinkedList<>(); + + dfs(1, n, k, current, result); + + return result; + } + + private void dfs(int start, int end, int k, List current, List> result) { + if (k == current.size()) { + result.add(new LinkedList<>(current)); + return; + } + + for (int i = start; i <= end; i++) { + current.add(i); + dfs(i + 1, end, k, current, result); + current.remove((Integer) i); + } + } + + +} diff --git a/[0077][Combinations]/src/Solution2.java b/[0077][Combinations]/src/Solution2.java new file mode 100644 index 0000000..8e1fb2f --- /dev/null +++ b/[0077][Combinations]/src/Solution2.java @@ -0,0 +1,80 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 19:39 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + private List> result; + private List l; + + /** + *
+     * ԭ
+     * Given two integers n and k, return all possible combinations of k numbers out of 1  n.
+     * For example,
+     * If n = 4 and k = 2, a solution is:
+     *
+     * [
+     *  [2,4],
+     *  [3,4],
+     *  [2,3],
+     *  [1,2],
+     *  [1,3],
+     *  [1,4],
+     * ]
+     *
+     * Ŀ
+     * nk1-nkϡ
+     *
+     * ˼·
+     * õݹη⣬롣
+     * 
+ * + * @param n + * @param k + * @return + */ + public List> combine(int n, int k) { + result = new LinkedList<>(); + + if (n > 0 && k > 0 && n >= k) { + l = new LinkedList<>(); + combine(1, n, k); + } + + return result; + } + + /** + * + * + * @param start ѡʼλ + * @param end ѡĽλ + * @param num [start, end]ѡĿ + */ + private void combine(int start, int end, int num) { + + if (num == 0) { + List tmp = new ArrayList<>(); + for (Integer i : l) { + tmp.add(i); + } + + result.add(tmp); + return; + } + + // һѡֵ + int endFirst = end - num + 1; + for (int i = start; i <= endFirst; i++) { + l.add(i); + combine(i + 1, end, num - 1); + l.remove(new Integer(i)); + } + } +} diff --git a/[0078][Subsets]/[0078][Subsets].iml b/[0078][Subsets]/[0078][Subsets].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0078][Subsets]/[0078][Subsets].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0078][Subsets]/src/Main.java b/[0078][Subsets]/src/Main.java new file mode 100644 index 0000000..9295524 --- /dev/null +++ b/[0078][Subsets]/src/Main.java @@ -0,0 +1,16 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 16:27 + **/ +public class Main { + @Test + public void test1() { + int[] nums = {1, 2, 3}; + + Solution solution = new Solution(); + + System.out.println(solution.subsets(nums)); + } +} diff --git a/[0078][Subsets]/src/Solution.java b/[0078][Subsets]/src/Solution.java new file mode 100644 index 0000000..9db75ec --- /dev/null +++ b/[0078][Subsets]/src/Solution.java @@ -0,0 +1,71 @@ +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 19:41 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + + /** + *
+     * ԭ
+     * Given a set of distinct integers, nums, return all possible subsets.
+     * Note:
+     * Elements in a subset must be in non-descending order.
+     * The solution set must not contain duplicate subsets.
+     * For example,
+     * If nums = [1,2,3], a solution is:
+     *
+     * [
+     *  [3],
+     *  [1],
+     *  [2],
+     *  [1,2,3],
+     *  [1,3],
+     *  [2,3],
+     *  [1,2],
+     *  []
+     * ]
+     *
+     * Ŀ
+     * һֵͬ飬Ӽ
+     *
+     * ˼·
+     * ȶеԪؽȻʹùŻ
+     * 
+ * + * @param nums + * @return + */ + public List> subsets(int[] nums) { + List> result = new LinkedList<>(); + List curr = new LinkedList<>(); + if (nums != null) { + // S + Arrays.sort(nums); + dfs(nums, 0, result, curr); + } + + return result; + } + + private void dfs(int[] nums, int index, List> result, List curr) { + + + // ӵУ˵һµĽ + result.add(new LinkedList<>(curr)); + + + for (int j = index; j < nums.length; j++) { + // Ԫ + curr.add(nums[j]); + dfs(nums, j + 1, result, curr); + // ԭ + curr.remove((Integer) nums[j]); + } + } +} diff --git a/[0078][Subsets]/src/Solution2.java b/[0078][Subsets]/src/Solution2.java new file mode 100644 index 0000000..ce86399 --- /dev/null +++ b/[0078][Subsets]/src/Solution2.java @@ -0,0 +1,123 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 19:41 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + private List> result; + private List l; + private int[] set; + private int num; // setлҪѡԪظ + + /** + *
+     * ԭ
+     * Given a set of distinct integers, nums, return all possible subsets.
+     * Note:
+     * Elements in a subset must be in non-descending order.
+     * The solution set must not contain duplicate subsets.
+     * For example,
+     * If nums = [1,2,3], a solution is:
+     *
+     * [
+     *  [3],
+     *  [1],
+     *  [2],
+     *  [1,2,3],
+     *  [1,3],
+     *  [2,3],
+     *  [1,2],
+     *  []
+     * ]
+     *
+     * Ŀ
+     * һֵͬ飬Ӽ
+     *
+     * ˼·
+     * ȶеԪؽȻõݹη⡣
+     * 
+ * + * @param S + * @return + */ + public List> subsets(int[] S) { + result = new LinkedList<>(); + + if (S != null) { + l = new ArrayList<>(); + + // S + quickSort(S, 0, S.length - 1); + + set = S; + for (int i = 0; i <= S.length; i++) { + num = i; + subset(0); + } + } + + // գӿ + set = null; + l = null; + + return result; + } + + /** + * ԪظnumӼ + * + * @param start ʣҪѡnumԪУһС± + */ + public void subset(int start) { + if (num == 0) { + List tmp = new ArrayList<>(); + for (Integer i : l) { + tmp.add(i); + } + + result.add(tmp); + return; + } + + int endFirst = set.length - num; // ʣҪѡnumԪУһ± + for (int i = start; i <= endFirst; i++) { + l.add(set[i]); + num--; + subset(i + 1); + num++; + l.remove(new Integer(set[i])); + } + } + + private void quickSort(int[] arr, int lo, int hi) { + if (lo < hi) { + int mid = getMid(arr, lo, hi); + quickSort(arr, lo, mid - 1); + quickSort(arr, mid + 1, hi); + } + } + + private int getMid(int[] arr, int lo, int hi) { + int tmp = arr[lo]; + while (lo < hi) { + while (lo < hi && arr[hi] > tmp) { + hi--; + } + arr[lo] = arr[hi]; + + while (lo < hi && arr[lo] < tmp) { + lo++; + } + + arr[hi] = arr[lo]; + } + + arr[lo] = tmp; + return lo; + } +} diff --git a/[0078][Subsets]/src/Solution3.java b/[0078][Subsets]/src/Solution3.java new file mode 100644 index 0000000..4ad1f20 --- /dev/null +++ b/[0078][Subsets]/src/Solution3.java @@ -0,0 +1,86 @@ +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-08-21 + * Time: 19:41 + * Declaration: All Rights Reserved !!! + */ +public class Solution3 { + + /** + *
+     * ԭ
+     * Given a set of distinct integers, nums, return all possible subsets.
+     * Note:
+     * Elements in a subset must be in non-descending order.
+     * The solution set must not contain duplicate subsets.
+     * For example,
+     * If nums = [1,2,3], a solution is:
+     *
+     * [
+     *  [3],
+     *  [1],
+     *  [2],
+     *  [1,2,3],
+     *  [1,3],
+     *  [2,3],
+     *  [1,2],
+     *  []
+     * ]
+     *
+     * Ŀ
+     * һֵͬ飬Ӽ
+     *
+     * ˼·
+     * ȶеԪؽȻõݹη⡣
+     * 
+ * + * @param nums + * @return + */ + public List> subsets(int[] nums) { + List> result = new LinkedList<>(); + List curr = new LinkedList<>(); + if (nums != null) { + + // S + Arrays.sort(nums); + // iʾӼԪظ + for (int i = 0; i <= nums.length; i++) { + subset(nums, 0, i, result, curr); + } + } + + return result; + } + + /** + * ԪnӼ + * + * @param nums Ԫؼ + * @param idx ȡԪصʼλ + * @param n Ԫظ + * @param result + * @param curr ʱ + */ + private void subset(int[] nums, int idx, int n, List> result, List curr) { + + // Ѿĩβˣ˵һ + if (n == 0) { + result.add(new LinkedList<>(curr)); + return; + } + + // ûд꣬ݹ鴦һԪ + for (int i = idx; i < nums.length - n + 1; i++) { + curr.add(nums[i]); + subset(nums, i + 1, n - 1, result, curr); + curr.remove((Integer) nums[i]); + } + } + + +} diff --git a/[0079][Word Search]/[0079][Word Search].iml b/[0079][Word Search]/[0079][Word Search].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0079][Word Search]/[0079][Word Search].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0079][Word Search]/[0079][WordSearch].iml b/[0079][Word Search]/[0079][WordSearch].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0079][Word Search]/[0079][WordSearch].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0079][Word Search]/src/Main.java b/[0079][Word Search]/src/Main.java new file mode 100644 index 0000000..52d523d --- /dev/null +++ b/[0079][Word Search]/src/Main.java @@ -0,0 +1,14 @@ +/** + * Author: ������ + * Date: 2015-06-20 + * Time: 08:02 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.exist(new char[][]{ + "abc".toCharArray(), "aed".toCharArray(), "afg".toCharArray() + }, "abcdefg")); + } +} diff --git a/[0079][Word Search]/src/Solution.java b/[0079][Word Search]/src/Solution.java new file mode 100644 index 0000000..ad373b1 --- /dev/null +++ b/[0079][Word Search]/src/Solution.java @@ -0,0 +1,113 @@ +/** + * Author: + * Date: 2015-06-20 + * Time: 07:19 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a 2D board and a word, find if the word exists in the grid.
+     *
+     * The word can be constructed from letters of sequentially adjacent cell,
+     * where "adjacent" cells are those horizontally or vertically neighboring.
+     * The same letter cell may not be used more than once.
+     *
+     * For example,
+     * Given board =
+     * [
+     *      ["ABCE"],
+     *      ["SFCS"],
+     *      ["ADEE"]
+     * ]
+     * word = "ABCCED", -> returns true,
+     * word = "SEE", -> returns true,
+     * word = "ABCB", -> returns false.
+     *
+     * Ŀ⣺
+     * һboardַ󣬿Դһ㿪ʼҵķʽߣÿֻһΣ
+     * һ·߹ַڸַôtrue
+     *
+     * ˼·
+     * ÿһΪ㣬ʹûݷ
+     * 
+ * + * @param board + * @param word + * @return + */ + public boolean exist(char[][] board, String word) { + // עǼٶIJǺϷ + + // ʱǾ󣬳ʼֵĬϻΪfalse + boolean[][] visited = new boolean[board.length][board[0].length]; + + // ÿһλΪҵһ·ֹͣ + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + if (search(board, visited, i, j, word, new int[]{0})) { + return true; + } + } + } + + return false; + } + + /** + * @param board ַ + * @param visited ʱǾ + * @param row ʵк + * @param col ʵк + * @param word ƥַ + * @param idx ƥλãȡǸºֵԱ + * @return + */ + private boolean search(char[][] board, boolean[][] visited, int row, int col, String word, int[] idx) { + // λõִijȣ˵Ѿҵҵƥ + if (idx[0] == word.length()) { + return true; + } + + boolean hasPath = false; + // ǰλúϷ + if (check(board, visited, row, col, word, idx[0])) { + // λñʹ + visited[row][col] = true; + idx[0]++; + // ϣң£ĸ + hasPath = search(board, visited, row - 1, col, word, idx) // + || search(board, visited, row, col + 1, word, idx) // + || search(board, visited, row + 1, col, word, idx) // + || search(board, visited, row, col - 1, word, idx); // + + + // ûҵ·ͻ + if (!hasPath) { + visited[row][col] = false; + idx[0]--; + } + } + + return hasPath; + } + + /** + * жʵλǷϷ + * + * @param board ַ + * @param visited ʱǾ + * @param row ʵк + * @param col ʵк + * @param word ƥַ + * @param idx ƥλ + * @return + */ + + public boolean check(char[][] board, boolean[][] visited, int row, int col, String word, int idx) { + return row >= 0 && row < board.length // кźϷ + && col >= 0 && col < board[0].length // кźϷ + && !visited[row][col] // ûбʹ + && board[row][col] == word.charAt(idx); // ַ + } +} diff --git a/[0080][Remove Duplicates from Sorted Array II]/[0080][Remove Duplicates from Sorted Array II].iml b/[0080][Remove Duplicates from Sorted Array II]/[0080][Remove Duplicates from Sorted Array II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0080][Remove Duplicates from Sorted Array II]/[0080][Remove Duplicates from Sorted Array II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0080][Remove Duplicates from Sorted Array II]/src/Main.java b/[0080][Remove Duplicates from Sorted Array II]/src/Main.java new file mode 100644 index 0000000..db6c257 --- /dev/null +++ b/[0080][Remove Duplicates from Sorted Array II]/src/Main.java @@ -0,0 +1,15 @@ +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-12 22:29 + **/ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + int[] nums = {1, 1, 1, 2, 2, 3}; + int i = solution.removeDuplicates(nums); + System.out.println(i + ": " + Arrays.toString(nums)); + + } +} diff --git a/[0080][Remove Duplicates from Sorted Array II]/src/Solution.java b/[0080][Remove Duplicates from Sorted Array II]/src/Solution.java new file mode 100644 index 0000000..ecd3151 --- /dev/null +++ b/[0080][Remove Duplicates from Sorted Array II]/src/Solution.java @@ -0,0 +1,24 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-12 22:29 + **/ +public class Solution { + public int removeDuplicates(int[] nums) { + if (nums == null) { + return 0; + } + if (nums.length < 3) { + return nums.length; + } + + int index = 2; + for (int i = 2; i < nums.length; i++) { + if (nums[index - 2] < nums[i]) { + nums[index] = nums[i]; + index++; + } + } + + return index; + } +} diff --git a/[0080][Remove Duplicates from Sorted Array II]/src/Solution2.java b/[0080][Remove Duplicates from Sorted Array II]/src/Solution2.java new file mode 100644 index 0000000..449987a --- /dev/null +++ b/[0080][Remove Duplicates from Sorted Array II]/src/Solution2.java @@ -0,0 +1,25 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-12 22:53 + **/ + +/** + * 删除重复出现的数字,使之最多出现两次 + */ +public class Solution2 { + public int removeDuplicates(int[] nums) { + int i = 0; + + // 处理每一个数字 + for (int n : nums) { + // i < 2 处理前两个数字 + // n > nums[i - 2]说明n不与nums[i - 2]重复,并且因为数组有序,那么必然n > nums[i - 2] + if (i < 2 || n > nums[i - 2]) { + nums[i++] = n; + } + } + + return i; + } +} + diff --git a/[0081][Search In Rotated Sorted Array II]/[0081][Search In Rotated Sorted Array II].iml b/[0081][Search In Rotated Sorted Array II]/[0081][Search In Rotated Sorted Array II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0081][Search In Rotated Sorted Array II]/[0081][Search In Rotated Sorted Array II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0081][Search In Rotated Sorted Array II]/src/Main.java b/[0081][Search In Rotated Sorted Array II]/src/Main.java new file mode 100644 index 0000000..be94e08 --- /dev/null +++ b/[0081][Search In Rotated Sorted Array II]/src/Main.java @@ -0,0 +1,13 @@ +/** + * Author: 王俊超 + * Date: 2015-06-21 + * Time: 16:38 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution2 solution = new Solution2(); + System.out.println(solution.search(new int[]{1, 1, 3, 1}, 3)); + System.out.println(solution.search(new int[]{5, 1, 3}, 3)); + } +} diff --git a/[0081][Search In Rotated Sorted Array II]/src/Solution.java b/[0081][Search In Rotated Sorted Array II]/src/Solution.java new file mode 100644 index 0000000..1c71ba1 --- /dev/null +++ b/[0081][Search In Rotated Sorted Array II]/src/Solution.java @@ -0,0 +1,137 @@ +/** + * Author: + * Date: 2015-06-21 + * Time: 14:46 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Follow up for "Search in Rotated Sorted Array":
+     * What if duplicates are allowed?
+     * Would this affect the run-time complexity? How and why?
+     * Write a function to determine if a given target is in the array
+     *
+     * Ŀ⣺
+     * "תֵ"ĺеֵظ
+     * дһȷһֵǷ
+     * 
+ * + * @param nums + * @param target + * @return + */ + public boolean search(int[] nums, int target) { + if (nums != null && nums.length > 0) { + // СԪضӦ± + int minIndex = findMinIndex(nums); + + // ȫ + if (minIndex == 0) { + return binarySearch(nums, 0, nums.length - 1, target); + } + // ֲ, 4 5 6 7 8 9 0 1 2 3 + else { + // úͺһһԪȣضӦ± + if (nums[nums.length - 1] == target) { + return true; + } + // targetںһ + else if (nums[nums.length - 1] > target) { + return binarySearch(nums, minIndex, nums.length - 1, target); + } + // targetǰһ + else { + return binarySearch(nums, 0, minIndex - 1, target); + } + } + } + + return false; + } + + /** + * + * + * @param nums + * @param start ʼλ + * @param end λ + * @param target Ŀ + * @return trueҵfalseûҵ + */ + public boolean binarySearch(int[] nums, int start, int end, int target) { + + int mid; + while (start <= end) { + mid = start + ((end - start) >> 1); + + if (nums[mid] == target) { + return true; + } else if (nums[mid] > target) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return false; + } + + + public int findMinIndex(int[] nums) { + // У + if (nums == null || nums.length < 1) { + throw new IllegalArgumentException(); + } + + int lo = 0; + int hi = nums.length - 1; + int mid = 0; + + // ųȫ + while (nums[lo] >= nums[hi]) { + // ֻԪأغһ + if (hi - lo == 1) { + mid = hi; + break; + } + + mid = lo + ((hi - lo) >> 1); + + if (nums[mid] == nums[lo] && nums[mid] == nums[hi]) { + // ֻܲ˳ܲlo++hi--ķʽ + // Ϊloǰһһ + // hiҲǺһĵһ + return sequenceSearchMinIndex(nums, lo, hi); + } + + // midǰһ + if (nums[mid] >= nums[lo]) { + lo = mid; + } + // midںһ + else if (nums[mid] <= nums[hi]) { + hi = mid; + } + } + + return mid; + } + + /** + * ˳еСֵ±꣬nums鰴ijת + * + * @param nums + * @param start ʼλ + * @param end λ + * @return Сֵ± + */ + public int sequenceSearchMinIndex(int[] nums, int start, int end) { + for (int i = start; i < end; i++) { + if (nums[i] > nums[i + 1]) { + return i + 1; + } + } + return start; + } +} diff --git a/[0081][Search In Rotated Sorted Array II]/src/Solution2.java b/[0081][Search In Rotated Sorted Array II]/src/Solution2.java new file mode 100644 index 0000000..9e48b6c --- /dev/null +++ b/[0081][Search In Rotated Sorted Array II]/src/Solution2.java @@ -0,0 +1,56 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-13 06:19 + **/ +public class Solution2 { + /** + * 分析 + * 允许重复元素,则上一题中如果A[mid]>=A[left], 那么[left,mid] 为递增序列的假设就不能成立了,比 + * 如[1,3,1,1,1]。 + * 如果A[mid]>=A[left] 不能确定递增,那就把它拆分成两个条件: + * • 若A[mid]>A[left],则区间[left,mid] 一定递增 + * • 若A[mid]==A[left] 确定不了,那就l++,往下看一步即可。 + * + * @param nums + * @param target + * @return + */ + public boolean search(int[] nums, int target) { + if (nums == null || nums.length < 1) { + return false; + } + + int left = 0; + int right = nums.length - 1; + int mid; + while (left <= right) { + mid = left + (right - left) / 2; + if (nums[mid] == target) { + return true; + } + + // [left, mid]区间递增 + if (nums[left] < nums[mid]) { + // target在[nums[left], nums[mid]]之间 + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; + } else { + left = mid + 1; + } + } else if (nums[left] > nums[mid]) { // [mid, right]区间递增 + // target在[nums[mid], nums[right]]之间 + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; + } else { + right = mid - 1; + } + } else { + // 无法区分递增区间,向右移动一个位置 + left++; + } + } + + + return false; + } +} diff --git a/[0082][Remove Duplicates From Sorted List II]/[0082][Remove Duplicates From Sorted List II].iml b/[0082][Remove Duplicates From Sorted List II]/[0082][Remove Duplicates From Sorted List II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0082][Remove Duplicates From Sorted List II]/[0082][Remove Duplicates From Sorted List II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0082][Remove Duplicates From Sorted List II]/[0082][RemoveDuplicatesFromSortedListII].iml b/[0082][Remove Duplicates From Sorted List II]/[0082][RemoveDuplicatesFromSortedListII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0082][Remove Duplicates From Sorted List II]/[0082][RemoveDuplicatesFromSortedListII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/src/ListNode.java" b/[0082][Remove Duplicates From Sorted List II]/src/ListNode.java similarity index 100% rename from "\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/src/ListNode.java" rename to [0082][Remove Duplicates From Sorted List II]/src/ListNode.java diff --git a/[0082][Remove Duplicates From Sorted List II]/src/Solution.java b/[0082][Remove Duplicates From Sorted List II]/src/Solution.java new file mode 100644 index 0000000..8e69cf6 --- /dev/null +++ b/[0082][Remove Duplicates From Sorted List II]/src/Solution.java @@ -0,0 +1,80 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:43 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given a sorted linked list, delete all nodes that have duplicate numbers,
+     * leaving only distinct numbers from the original list.
+     * For example,
+     * Given 1->2->3->3->4->4->5, return 1->2->5.
+     * Given 1->1->1->2->3, return 2->3.
+     *
+     * Ŀ
+     * һźĵɾظԪءֻֻһֵԪء
+     *
+     * ˼·
+     * һrootrootӵԭͷͷ͸ָ룬صԪؽɾ
+     * 
+ * + * @param head + * @return + */ + public ListNode deleteDuplicates(ListNode head) { + + // ͷ + ListNode root = new ListNode(0); + root.next = head; + ListNode p = head; + // ¼һûظԪأʼָͷ + ListNode q = root; + + // Ԫظ + int delta = 0; + + while (p != null && p.next != null) { + // ͬ + if (p.val == p.next.val) { + delta++; + // ƶһ + p = p.next; + } + // 㲻ͬ + else { + // ֵΪp.valĽûظ + if (delta == 0) { + // ӵûиԪ + q.next = p; + // ָһδظԪ + q = p; + // ƶһ + p = p.next; + } + // ֵΪp.valĽظ + else { + // ƶһԪ + p = p.next; + // ȥظԪ + q.next = p.next; + // ԪظΪ0 + delta = 0; + } + } + } + + // һԪǸľȥ + if (delta != 0) { + q.next = null; + } + // ûظͿӵβ + else { + q.next = p; + } + + return root.next; + } +} diff --git a/[0083][Remove Duplicates From Sorted List]/[0083][Remove Duplicates From Sorted List].iml b/[0083][Remove Duplicates From Sorted List]/[0083][Remove Duplicates From Sorted List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0083][Remove Duplicates From Sorted List]/[0083][Remove Duplicates From Sorted List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/src/ListNode.java" b/[0083][Remove Duplicates From Sorted List]/src/ListNode.java similarity index 100% rename from "\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/src/ListNode.java" rename to [0083][Remove Duplicates From Sorted List]/src/ListNode.java diff --git a/[0083][Remove Duplicates From Sorted List]/src/Solution.java b/[0083][Remove Duplicates From Sorted List]/src/Solution.java new file mode 100644 index 0000000..97b28f2 --- /dev/null +++ b/[0083][Remove Duplicates From Sorted List]/src/Solution.java @@ -0,0 +1,55 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:45 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * һɾظԪأֻͬһ
+     *
+     * ˼·
+     * ʹһָָͷһ뵱ǰĽɾֱһͬģָָ
+     * µĽ㣬ظֱеĽ㶼ꡣ
+     * 
+ * + * @param head + * @return + */ + public ListNode deleteDuplicates(ListNode head) { + ListNode point; + // ָ½βʼʱֻһԪأͷ + ListNode tail = head; + + if (head != null) { + // ָͷһԪ + point = head.next; + // δĩβ + while (point != null) { + + // βڵ㲻ͬͽͬĽڵӵtailһλ + if (tail.val != point.val) { + tail.next = point; + // ָβ + tail = tail.next; + } + + // ƶһλ + point = point.next; + } + + // βָ + tail.next = null; + } + + return head; + } +} diff --git a/[0084][Largest Rectangle in Histogram]/[0084][Largest Rectangle in Histogram].iml b/[0084][Largest Rectangle in Histogram]/[0084][Largest Rectangle in Histogram].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0084][Largest Rectangle in Histogram]/[0084][Largest Rectangle in Histogram].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0084][Largest Rectangle in Histogram]/src/Solution.java b/[0084][Largest Rectangle in Histogram]/src/Solution.java new file mode 100644 index 0000000..72f516d --- /dev/null +++ b/[0084][Largest Rectangle in Histogram]/src/Solution.java @@ -0,0 +1,71 @@ +import java.util.Arrays; +import java.util.Deque; +import java.util.LinkedList; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 15:29 + **/ +public class Solution { + /** + *
+     * Given n non-negative integers representing the histogram's bar height where the width
+     * of each bar is 1, find the area of largest rectangle in the histogram.
+     *
+     *
+     *    -
+     *   --
+     *   --
+     *   -- -
+     * - ----
+     * ------
+     * Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
+     * The largest rectangle is shown in the shaded area, which has area = 10 unit.
+     *    -
+     *   ==
+     *   ==
+     *   == -
+     * - ==--
+     * --==--
+     * Example:
+     * Input: [2,1,5,6,2,3]
+     * Output: 10
+     *
+     * https://leetcode.com/problems/largest-rectangle-in-histogram/
+     * 
+ */ + public int largestRectangleArea(int[] heights) { + if (heights == null || heights.length < 1) { + return 0; + } + // 记录位置 + Deque stack = new LinkedList<>(); + + int i = 0; + int result = 0; + + // 复制数组,最后位置补0,方便计算 + int[] h = Arrays.copyOf(heights, heights.length + 1); + + while (i < h.length) { + // 之前的元素小于等于当前元素 + if (stack.isEmpty() || h[stack.peek()] <= h[i]) { + // 当前元素入栈 + stack.push(i); + i++; + } else { + // 栈顶元素位置出栈 + int t = stack.pop(); + // 高度是height[t] + // stack.isEmpty(): 说明栈里的所有元素都比height[i]大,i位置之前有i个元素,序列就是[0 ,1, ..., i-1] + // 所求的长度就是i + // stack不为空,说明计算的位置是[stack.peek(), ..., i-1] 长度 + result = Math.max(result, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1)); + } + } + + + return result; + + } +} diff --git a/[0086][Partition List]/[0086][Partition List].iml b/[0086][Partition List]/[0086][Partition List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0086][Partition List]/[0086][Partition List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0086][Partition List]/[0086][PartitionList].iml b/[0086][Partition List]/[0086][PartitionList].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0086][Partition List]/[0086][PartitionList].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0086][Partition List]/src/ListNode.java b/[0086][Partition List]/src/ListNode.java new file mode 100644 index 0000000..63ee591 --- /dev/null +++ b/[0086][Partition List]/src/ListNode.java @@ -0,0 +1,14 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 17:18 + * Declaration: All Rights Reserved !!! + */ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } +} diff --git a/[0086][Partition List]/src/Solution.java b/[0086][Partition List]/src/Solution.java new file mode 100644 index 0000000..c241a4b --- /dev/null +++ b/[0086][Partition List]/src/Solution.java @@ -0,0 +1,64 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 17:18 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given a linked list and a value x, partition it such that all nodes less
+     * than x come before nodes greater than or equal to x.
+     * You should preserve the original relative order of the nodes in each of
+     * the two partitions.
+     *
+     * For example,
+     * Given 1->4->3->2->5->2 and x = 3,
+     * return 1->2->2->4->3->5.
+     *
+     * Ŀ
+     * һһֵxֳСڵxIJֺʹxIJ֡ͬʱԭ˳
+     *
+     * ˼·
+     * abԭеÿ㣬СڵxĽaĩβǴھͷb
+     * ĩβbͷӵaĩβ
+     * 
+ * + * @param head + * @param x + * @return + */ + public ListNode partition(ListNode head, int x) { + + ListNode le = new ListNode(0); // Сx + ListNode ge = new ListNode(0); // ڵx + ListNode t1 = le; + ListNode t2 = ge; + ListNode p = head; + + while (p != null) { + if (p.val < x) { + t1.next = p; + t1 = p; + } else { + t2.next = p; + t2 = p; + } + p = p.next; + } + + t2.next = null; + + // пt1û + // t1ƶ˵Сڵ + if (t1 != le) { + t1.next = ge.next; + head = le.next; + } else { + head = ge.next; + } + + return head; + } +} diff --git a/[0088][Merge Sorted Array]/[0088][Merge Sorted Array].iml b/[0088][Merge Sorted Array]/[0088][Merge Sorted Array].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0088][Merge Sorted Array]/[0088][Merge Sorted Array].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0088][Merge Sorted Array]/src/Solution.java b/[0088][Merge Sorted Array]/src/Solution.java new file mode 100644 index 0000000..d25ea04 --- /dev/null +++ b/[0088][Merge Sorted Array]/src/Solution.java @@ -0,0 +1,51 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 17:20 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * 飬кϲϲҲģϲnums1С
+     * nums1㹻Ŀռnums2
+     *
+     * ˼·
+     * еһλÿʼкϲнϴƶλãǸ
+     * λֵǰƶһλãٽͬIJֱеԪشꡣ
+     * 
+ * + * @param arr + * @param m + * @param brr + * @param n + */ + public void merge(int arr[], int m, int brr[], int n) { + int pa = m - 1; + int pb = n - 1; + int index = m + n - 1; + + while (pa >= 0 && pb >= 0) { + if (arr[pa] >= brr[pb]) { + arr[index--] = arr[pa--]; + } else { + arr[index--] = brr[pb--]; + } + } + + // ˵paһΪ0 + while (pb >= 0) { + arr[index--] = brr[pb--]; + } + + // pa >= 0˵[0, pa]ûнжϣΪ[0, pa]arrУԲҪƶ + } +} diff --git a/[0089][Gray Code]/[0089][Gray Code].iml b/[0089][Gray Code]/[0089][Gray Code].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0089][Gray Code]/[0089][Gray Code].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0089][Gray Code]/src/Main.java b/[0089][Gray Code]/src/Main.java new file mode 100644 index 0000000..6349221 --- /dev/null +++ b/[0089][Gray Code]/src/Main.java @@ -0,0 +1,18 @@ +import java.util.List; + +/** + * Author: + * Date: 2015-06-22 + * Time: 13:27 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + List result = solution.grayCode(2); + + for (Integer i : result) { + System.out.printf("%s\n", Integer.toBinaryString(i)); + } + } +} diff --git a/[0089][Gray Code]/src/Solution.java b/[0089][Gray Code]/src/Solution.java new file mode 100644 index 0000000..4af4a3c --- /dev/null +++ b/[0089][Gray Code]/src/Solution.java @@ -0,0 +1,82 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-22 + * Time: 13:16 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * The nums[c] is a binary numeral system where two successive values differ in only one bit.
+     * Given a non-negative integer n representing the total number of bits in the code, print the
+     * sequence of gray code. A gray code sequence must begin with 0.
+     *
+     * For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
+     * 00 - 0
+     * 01 - 1
+     * 11 - 3
+     * 10 - 2
+     *
+     * Note:
+     *   - For a given n, a gray code sequence is not uniquely defined.
+     *   - For example, [0,2,3,1] is also a valid gray code sequence according to the above
+     *          definition.
+     *   - For now, the judge is able to judge based on one instance of gray code sequence.
+     *          Sorry about that.
+     *
+     * Ŀ⣺
+     * nΪnĸ
+     *
+     * (Gray Code) Ķοhttp://en.wikipedia.org/wiki/Gray_code
+     * ȻתΪ룺g0 = b0; gi = bi^b(i-1)
+     * ȻλΪλθλΪĸλθλ
+     * λθλơ磬Ȼ1001תΪĹǣ
+     * λȻ󽫵1 λ1 ͵2 λ0 򣬵õ1Ϊĵ2 λ2 λ0 ͵3 λ
+     * 0 򣬵õ0Ϊĵ3 λ3 λ0 ͵4 λ1 򣬵õ1Ϊ
+     * 4 λգΪ1101
+     * תΪȻ룺b0 = g0; bi = gi^b(i-1)
+     * λΪȻλθλΪȻƸλθλ
+     * λθλơ磬1000 תΪȻĹǣ
+     * λ1ΪȻλȻȻĵ1 λ1 ͸ĵ2 λ0 򣬵
+     * 1ΪȻĵ2 λȻĵ2 λ1 ͸ĵ3 λ0 򣬵õ1
+     * ΪȻĵ3 λȻĵ3 λ1 ͸ĵ4 λ0 򣬵õ1Ϊ
+     * Ȼĵ4 λգȻΪ1111
+     * ѧʽn ĸn^(n/2)
+     * Ҫn صи롣
+     * 1򵥵ķѧʽԴ0 ~2^n-1 תΪ롣
+     * 2nصĸ룬Եݹشn - 1 صĸɡ
+     *
+     * ˼·
+     * ݹ
+     *  ַڸǷʵõݹ¹죺
+     *  1λ
+     *  (n+1)λеǰ2^nֵnλ֣˳дǰ׺0
+     *  (n+1)λеĺ2^nֵnλ֣дǰ׺1
+     * 
+ * + * @param n + * @return + */ + public List grayCode(int n) { + List result = new LinkedList<>(); + if (n >= 0) { + // ǰ벿 + result.add(0); + // λֵ0ʱ + int t = 1; + // ÿһѭλi+1λĸ൱ڳΪi+1λĸǰ벿 + for (int i = 0; i < n; i++) { + // ijΪi+1λĺ벿֣ǰ벿ɳΪiλĸ + for (int j = result.size() - 1; j >= 0; j--) { + result.add(result.get(j) ^ t); + } + // λ + t <<= 1; + } + } + return result; + } +} diff --git a/[0090][Subsets II]/[0090][Subsets II].iml b/[0090][Subsets II]/[0090][Subsets II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0090][Subsets II]/[0090][Subsets II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0090][Subsets II]/src/Main.java b/[0090][Subsets II]/src/Main.java new file mode 100644 index 0000000..4af3b37 --- /dev/null +++ b/[0090][Subsets II]/src/Main.java @@ -0,0 +1,21 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 17:33 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] nums = {1, 2, 2}; + System.out.println(solution.subsetsWithDup(nums)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + int[] nums = {1, 2, 2}; + System.out.println(solution.subsetsWithDup(nums)); + } +} diff --git a/[0090][Subsets II]/src/Solution.java b/[0090][Subsets II]/src/Solution.java new file mode 100644 index 0000000..7593613 --- /dev/null +++ b/[0090][Subsets II]/src/Solution.java @@ -0,0 +1,66 @@ +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 16:43 + **/ +public class Solution { + + /** + *
+     * Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
+     *
+     * Note: The solution set must not contain duplicate subsets.
+     *
+     * Example:
+     *
+     * Input: [1,2,2]
+     * Output:
+     * [
+     *   [2],
+     *   [1],
+     *   [1,2,2],
+     *   [2,2],
+     *   [1,2],
+     *   []
+     * ]
+     * 
+ * + * @param nums + * @return + */ + public List> subsetsWithDup(int[] nums) { + List> result = new LinkedList<>(); + List curr = new LinkedList<>(); + if (nums != null) { + // 对S进行排序处理 + Arrays.sort(nums); + dfs(nums, 0, result, curr); + } + + return result; + } + + private void dfs(int[] nums, int index, List> result, List curr) { + + + // 添加到结果中,说明有一种新的结产生 + result.add(new LinkedList<>(curr)); + + + for (int j = index; j < nums.length; j++) { + // 在当前可选择的范围内,相同的只能选择一次 + if (j > index && nums[j] == nums[j - 1]) { + continue; + } + + // 添加元素 + curr.add(nums[j]); + dfs(nums, j + 1, result, curr); + // 还原 + curr.remove((Integer) nums[j]); + } + } +} diff --git a/[0091][Decode Ways]/[0091][Decode Ways].iml b/[0091][Decode Ways]/[0091][Decode Ways].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0091][Decode Ways]/[0091][Decode Ways].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0091][Decode Ways]/src/Main.java b/[0091][Decode Ways]/src/Main.java new file mode 100644 index 0000000..c12f921 --- /dev/null +++ b/[0091][Decode Ways]/src/Main.java @@ -0,0 +1,15 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-25 19:22 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + Assert.assertEquals(3, solution.numDecodings("226")); + } +} diff --git a/[0091][Decode Ways]/src/Solution.java b/[0091][Decode Ways]/src/Solution.java new file mode 100644 index 0000000..7fc1faa --- /dev/null +++ b/[0091][Decode Ways]/src/Solution.java @@ -0,0 +1,51 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-25 19:17 + **/ +public class Solution { + /** + * A message containing letters from A-Z is being encoded to numbers using the following mapping: + *

+ * 'A' -> 1 + * 'B' -> 2 + * ... + * 'Z' -> 26 + * Given a non-empty string containing only digits, determine the total number of ways to decode it. + *

+ * Example 1: + *

+ * Input: "12" + * Output: 2 + * Explanation: It could be decoded as "AB" (1 2) or "L" (12). + * Example 2: + *

+ * Input: "226" + * Output: 3 + * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). + * + * @param s + * @return + */ + public int numDecodings(String s) { + if (s.isEmpty() || s.charAt(0) == '0') { + return 0; + } + int prev = 0; + int cur = 1; + // 长度为n 的字符串,有n+1 个阶梯 + for (int i = 1; i <= s.length(); ++i) { + if (s.charAt(i - 1) == '0') { + cur = 0; + } + if (i < 2 || !(s.charAt(i - 2) == '1' || (s.charAt(i - 2) == '2' && s.charAt(i - 1) <= '6'))) { + prev = 0; + } + + int tmp = cur; + cur = prev + cur; + prev = tmp; + } + return cur; + } + +} \ No newline at end of file diff --git a/[0091][Decode Ways]/src/Solution2.java b/[0091][Decode Ways]/src/Solution2.java new file mode 100644 index 0000000..3c3ccdf --- /dev/null +++ b/[0091][Decode Ways]/src/Solution2.java @@ -0,0 +1,96 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-25 19:17 + **/ +public class Solution2 { + /** + * A message containing letters from A-Z is being encoded to numbers using the following mapping: + *

+ * 'A' -> 1 + * 'B' -> 2 + * ... + * 'Z' -> 26 + * Given a non-empty string containing only digits, determine the total number of ways to decode it. + *

+ * Example 1: + *

+ * Input: "12" + * Output: 2 + * Explanation: It could be decoded as "AB" (1 2) or "L" (12). + * Example 2: + *

+ * Input: "226" + * Output: 3 + * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). + * + * @param s + * @return + */ + public int numDecodings(String s) { + int n = s.length(); + if (n == 0) { + return 0; + } + + int[] memo = new int[n + 1]; + memo[n] = 1; + memo[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; + + for (int i = n - 2; i >= 0; i--) { + if (s.charAt(i) == '0') { + continue; + } else { + memo[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? memo[i + 1] + memo[i + 2] : memo[i + 1]; + } + } + return memo[0]; + } + + // 太慢 + public int numDecodings2(String s) { + // 如是不是纯数字的字符串就返回0 + if (s == null || !s.matches("^\\d+$")) { + return 0; + } + + // 第一位以0开头,没有可以匹配的 + if (s.charAt(0) == '0') { + return 0; + } + + // 如果只一位 + if (s.length() == 1) { + return handle(s); + } + + // 如果有两位 + if (s.length() == 2) { + int v = Integer.parseInt(s); + // 如果拆成个一位的有几种可能 + int r = handle(s.substring(s.length() - 1)); + + // 如是两位组成一个,1~26才可以算一种可能 + if (v > 0 && v < 27) { + r++; + } + return r; + } + + // 字符串长度大于3,f(s)=(0 or 1)*f(s-1) + (0 or 1)*f(s-2) + // 对于f(s-1),如果首位是0,取0 + // 对于f(s-2),如果首位是0或者首两位的值小于1或者大于26,取0 + + int v = numDecodings(s.substring(1)); + int t = Integer.parseInt(s.substring(0, 2)); + + if (t > 0 && t < 27) { + v += numDecodings(s.substring(2)); + } + + return v; + } + + private int handle(String s) { + return Integer.parseInt(s) == 0 ? 0 : 1; + } +} \ No newline at end of file diff --git a/[0092][Reverse Linked List II]/[0092][Reverse Linked List II].iml b/[0092][Reverse Linked List II]/[0092][Reverse Linked List II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0092][Reverse Linked List II]/[0092][Reverse Linked List II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0092][Reverse Linked List II]/src/ListNode.java b/[0092][Reverse Linked List II]/src/ListNode.java new file mode 100644 index 0000000..8f1581b --- /dev/null +++ b/[0092][Reverse Linked List II]/src/ListNode.java @@ -0,0 +1,14 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 17:23 + * Declaration: All Rights Reserved !!! + */ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } +} diff --git a/[0092][Reverse Linked List II]/src/Solution.java b/[0092][Reverse Linked List II]/src/Solution.java new file mode 100644 index 0000000..e1a7587 --- /dev/null +++ b/[0092][Reverse Linked List II]/src/Solution.java @@ -0,0 +1,70 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 17:23 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *

+     * ԭ
+     * Reverse a linked list from position m to n. Do it in-place and in one-pass.
+     * For example:
+     * Given 1->2->3->4->5->NULL, m = 2 and n = 4,
+     * return 1->4->3->2->5->NULL.
+     * Note:
+     * Given m, n satisfy the following condition:
+     * 1  m  n  length of list.
+     *
+     * Ŀ
+     * һmn֮Ԫؽת
+     * nmǺϷģʹԭطнʹóռ䣩
+     *
+     * ˼·
+     * ҵһҪתԪصǰprevټҪзתԪظԪؽͷ巨
+     * prev棬ͬʱϿ
+     * 
+ * + * @param head + * @param m + * @param n + * @return + */ + public ListNode reverseBetween(ListNode head, int m, int n) { + + ListNode root = new ListNode(0); + ListNode p = root; + root.next = head; + + for (int i = 1; i < m && p != null; i++) { + p = p.next; + } + + if (p != null) { + ListNode q = p.next; + ListNode r; + + // mΪΪǴӵһʼ + if (m < 1) { + m = 1; + } + + // nΪҪĽĿ + n = n - m + 1; + // ʱҪʹβ巨βĸΪn-1 + for (int i = 1; i < n && q.next != null; i++) { + // ΪҪβĽ + r = q.next; + + // qĺβ + q.next = r.next; + r.next = p.next; + p.next = r; + } + + head = root.next; + } + + return head; + } +} diff --git a/[0093][Restore IP Addresses]/[0093][Restore IP Addresses].iml b/[0093][Restore IP Addresses]/[0093][Restore IP Addresses].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0093][Restore IP Addresses]/[0093][Restore IP Addresses].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0093][Restore IP Addresses]/src/Solution.java b/[0093][Restore IP Addresses]/src/Solution.java new file mode 100644 index 0000000..ad998bc --- /dev/null +++ b/[0093][Restore IP Addresses]/src/Solution.java @@ -0,0 +1,32 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-23 06:48 + **/ +public class Solution { + public List restoreIpAddresses(String s) { + List result = new ArrayList<>(); + doRestore(result, "", s, 0); + return result; + } + + private void doRestore(List result, String path, String s, int k) { + if (s.isEmpty() || k == 4) { + if (s.isEmpty() && k == 4) { + result.add(path.substring(1)); + } + return; + } + + int length = (s.charAt(0) == '0' ? 1 : 3); // 避免前导0 + length = length < s.length() ? length : s.length(); + for (int i = 1; i <= length; i++) { + String part = s.substring(0, i); + if (Integer.valueOf(part) <= 255) { + doRestore(result, path + "." + part, s.substring(i), k + 1); + } + } + } +} diff --git a/[0094][Binary Tree Inorder Traversal]/[0094][Binary Tree Inorder Traversal].iml b/[0094][Binary Tree Inorder Traversal]/[0094][Binary Tree Inorder Traversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0094][Binary Tree Inorder Traversal]/[0094][Binary Tree Inorder Traversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0094][Binary Tree Inorder Traversal]/[0094][BinaryTree InorderTraversal].iml b/[0094][Binary Tree Inorder Traversal]/[0094][BinaryTree InorderTraversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0094][Binary Tree Inorder Traversal]/[0094][BinaryTree InorderTraversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/src/Main.java" b/[0094][Binary Tree Inorder Traversal]/src/Main.java similarity index 100% rename from "\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/src/Main.java" rename to [0094][Binary Tree Inorder Traversal]/src/Main.java diff --git a/[0094][Binary Tree Inorder Traversal]/src/Solution.java b/[0094][Binary Tree Inorder Traversal]/src/Solution.java new file mode 100644 index 0000000..5af0019 --- /dev/null +++ b/[0094][Binary Tree Inorder Traversal]/src/Solution.java @@ -0,0 +1,38 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-07-25 + * Time: 18:19 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + public List inorderTraversal(TreeNode root) { + + List result = new LinkedList<>(); + LinkedList stack = new LinkedList<>(); + + // ڼ¼ǰҪԪ + TreeNode node = root; + + // node1root㣬2Һ + while (node != null || !stack.isEmpty()) { + // ջ + while (node != null) { + stack.addLast(node); + node = node.left; + } + + // ʱջеջԪһûӵ + if (!stack.isEmpty()) { + // ɾջԪ + node = stack.removeLast(); + result.add(node.val); + // ָҺ + node = node.right; + } + } + return result; + } +} diff --git "a/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/src/TreeNode.java" b/[0094][Binary Tree Inorder Traversal]/src/TreeNode.java similarity index 100% rename from "\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/src/TreeNode.java" rename to [0094][Binary Tree Inorder Traversal]/src/TreeNode.java diff --git a/[0095][Unique Binary Search Trees II]/[0095][Unique Binary Search Trees II].iml b/[0095][Unique Binary Search Trees II]/[0095][Unique Binary Search Trees II].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0095][Unique Binary Search Trees II]/[0095][Unique Binary Search Trees II].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0095][Unique Binary Search Trees II]/src/Main.java b/[0095][Unique Binary Search Trees II]/src/Main.java new file mode 100644 index 0000000..de39bd8 --- /dev/null +++ b/[0095][Unique Binary Search Trees II]/src/Main.java @@ -0,0 +1,44 @@ +import org.junit.Test; + +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 16:29 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + print(solution.generateTrees(3)); + } + + private void print(List generateTrees) { + for (TreeNode node : generateTrees) { + print(node); + System.out.println(); + } + } + + private void print(TreeNode node) { + if (node != null) { + System.out.print(node + ", "); + + if (node.left == null && node.right == null) { + return; + } + + if (node.left == null) { + System.out.print("null, "); + } else { + print(node.left); + } + if (node.right == null) { + System.out.print("null, "); + } else { + print(node.right); + } + } + } +} diff --git a/[0095][Unique Binary Search Trees II]/src/Solution.java b/[0095][Unique Binary Search Trees II]/src/Solution.java new file mode 100644 index 0000000..d3ca6f6 --- /dev/null +++ b/[0095][Unique Binary Search Trees II]/src/Solution.java @@ -0,0 +1,48 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 16:14 + **/ +public class Solution { + public List generateTrees(int n) { + + if (n == 0) { + return new LinkedList<>(); + } + + return trees(1, n); + } + + private List trees(int start, int end) { + List result = new LinkedList<>(); + if (start == end) { + result.add(new TreeNode(start)); + return result; + } + + if (start > end) { + result.add(null); + return result; + } + + for (int i = start; i <= end; i++) { + List left = trees(start, i - 1); + List right = trees(i + 1, end); + + for (TreeNode l : left) { + for (TreeNode r : right) { + TreeNode root = new TreeNode(i); + root.left = l; + root.right = r; + result.add(root); + } + } + } + + return result; + } + + +} diff --git a/[0095][Unique Binary Search Trees II]/src/TreeNode.java b/[0095][Unique Binary Search Trees II]/src/TreeNode.java new file mode 100644 index 0000000..2878b91 --- /dev/null +++ b/[0095][Unique Binary Search Trees II]/src/TreeNode.java @@ -0,0 +1,18 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 16:14 + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } + + @Override + public String toString() { + return val + ""; + } +} diff --git a/[0096][Unique Binary Search Trees]/[0096][Unique Binary Search Trees].iml b/[0096][Unique Binary Search Trees]/[0096][Unique Binary Search Trees].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0096][Unique Binary Search Trees]/[0096][Unique Binary Search Trees].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/src/Main.java" b/[0096][Unique Binary Search Trees]/src/Main.java similarity index 100% rename from "\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/src/Main.java" rename to [0096][Unique Binary Search Trees]/src/Main.java diff --git a/[0096][Unique Binary Search Trees]/src/Solution.java b/[0096][Unique Binary Search Trees]/src/Solution.java new file mode 100644 index 0000000..ab0f547 --- /dev/null +++ b/[0096][Unique Binary Search Trees]/src/Solution.java @@ -0,0 +1,49 @@ +/** + * Author: + * Date: 2015-06-18 + * Time: 17:36 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? + *

+ * For example, + * Given n = 3, there are a total of 5 unique BST's. + * 1 3 3 2 1 + * \ / / / \ \ + * 3 2 1 1 3 2 + * / / \ \ + * 2 1 2 3 + *

+ * ƹʽ + * f(0) = 1 + * f(1) = 1 + * f(i) = f(0)f(i-1) + f(1)f(i-1) + ... + f(i-1)f(0) + * + * @param n + * @return + */ + public int numTrees(int n) { + + if (n <= 0) { + return 1; + } else if (n == 1) { + return 1; + } + + int[] result = new int[n + 1]; + result[0] = 1; + result[1] = 1; + + + // f(2)...f(n) + for (int i = 2; i <= n; i++) { + for (int j = 1; j <= i; j++) { + result[i] += result[j - 1] * result[i - j]; + } + + } + return result[n]; + } +} diff --git a/[0096][Unique Binary Search Trees]/src/Solution2.java b/[0096][Unique Binary Search Trees]/src/Solution2.java new file mode 100644 index 0000000..31624d1 --- /dev/null +++ b/[0096][Unique Binary Search Trees]/src/Solution2.java @@ -0,0 +1,51 @@ +/** + * Author: + * Date: 2015-06-18 + * Time: 17:36 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? + *

+ * For example, + * Given n = 3, there are a total of 5 unique BST's. + * 1 3 3 2 1 + * \ / / / \ \ + * 3 2 1 1 3 2 + * / / \ \ + * 2 1 2 3 + *

+ * ƹʽ + * f(k)*f(n-1-k)f(k)ʾk㣬е״f(k)f(n-1-k)ʾn-1-k + *

+ * f(n) = 2*f(n-1) + f(1)*f(n-2) + f(2)f(n-3) + f(3)f(n-4) + ... +f(n-2)*f(1) + * + * @param n + * @return + */ + public int numTrees(int n) { + + if (n <= 0) { + return 1; + } else if (n == 1) { + return 1; + } + + int[] result = new int[n + 1]; + result[0] = 0; + result[1] = 1; + + + // f(2)...f(n) + for (int i = 2; i <= n; i++) { + // f(i) + result[i] = 2 * result[i - 1]; + for (int j = 1; j <= i - 1; j++) { + result[i] += result[j] * result[i - 1 - j]; + } + + } + return result[n]; + } +} diff --git a/[0098][Validate Binary Search Tree]/[0098][Validate Binary Search Tree].iml b/[0098][Validate Binary Search Tree]/[0098][Validate Binary Search Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0098][Validate Binary Search Tree]/[0098][Validate Binary Search Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0098][Validate Binary Search Tree]/[0098][ValidateBinarySearchTree].iml b/[0098][Validate Binary Search Tree]/[0098][ValidateBinarySearchTree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0098][Validate Binary Search Tree]/[0098][ValidateBinarySearchTree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221/src/Solution.java" b/[0098][Validate Binary Search Tree]/src/Solution.java similarity index 100% rename from "\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221/src/Solution.java" rename to [0098][Validate Binary Search Tree]/src/Solution.java diff --git "a/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221/src/TreeNode.java" b/[0098][Validate Binary Search Tree]/src/TreeNode.java similarity index 100% rename from "\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221/src/TreeNode.java" rename to [0098][Validate Binary Search Tree]/src/TreeNode.java diff --git a/[0100][Same Tree]/[0100][Same Tree].iml b/[0100][Same Tree]/[0100][Same Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0100][Same Tree]/[0100][Same Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0100][Same Tree]/[0100][SameTree].iml b/[0100][Same Tree]/[0100][SameTree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0100][Same Tree]/[0100][SameTree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/src/Solution.java" b/[0100][Same Tree]/src/Solution.java similarity index 100% rename from "\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/src/Solution.java" rename to [0100][Same Tree]/src/Solution.java diff --git a/[0100][Same Tree]/src/TreeNode.java b/[0100][Same Tree]/src/TreeNode.java new file mode 100644 index 0000000..a4b81b6 --- /dev/null +++ b/[0100][Same Tree]/src/TreeNode.java @@ -0,0 +1,15 @@ +/** + * Author: ������ + * Date: 2015-08-21 + * Time: 18:40 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0101][Symmetric Tree]/[0101][Symmetric Tree].iml b/[0101][Symmetric Tree]/[0101][Symmetric Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0101][Symmetric Tree]/[0101][Symmetric Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0101][Symmetric Tree]/[0101][SymmetricTree].iml b/[0101][Symmetric Tree]/[0101][SymmetricTree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0101][Symmetric Tree]/[0101][SymmetricTree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221/src/Solution.java" b/[0101][Symmetric Tree]/src/Solution.java similarity index 100% rename from "\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221/src/Solution.java" rename to [0101][Symmetric Tree]/src/Solution.java diff --git "a/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221/src/TreeNode.java" b/[0101][Symmetric Tree]/src/TreeNode.java similarity index 100% rename from "\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221/src/TreeNode.java" rename to [0101][Symmetric Tree]/src/TreeNode.java diff --git a/[0102][Binary Tree Level Order Traversal]/[0102][Binary Tree Level Order Traversal].iml b/[0102][Binary Tree Level Order Traversal]/[0102][Binary Tree Level Order Traversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0102][Binary Tree Level Order Traversal]/[0102][Binary Tree Level Order Traversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0102][Binary Tree Level Order Traversal]/[0102][BinaryTreeLevelOrderTraversal].iml b/[0102][Binary Tree Level Order Traversal]/[0102][BinaryTreeLevelOrderTraversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0102][Binary Tree Level Order Traversal]/[0102][BinaryTreeLevelOrderTraversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221/src/Solution.java" b/[0102][Binary Tree Level Order Traversal]/src/Solution.java similarity index 100% rename from "\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221/src/Solution.java" rename to [0102][Binary Tree Level Order Traversal]/src/Solution.java diff --git "a/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221/src/TreeNode.java" b/[0102][Binary Tree Level Order Traversal]/src/TreeNode.java similarity index 100% rename from "\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221/src/TreeNode.java" rename to [0102][Binary Tree Level Order Traversal]/src/TreeNode.java diff --git a/[0103][Binary Tree Zigzag LevelOrder Traversal]/[0103][Binary Tree Zigzag LevelOrder Traversal].iml b/[0103][Binary Tree Zigzag LevelOrder Traversal]/[0103][Binary Tree Zigzag LevelOrder Traversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0103][Binary Tree Zigzag LevelOrder Traversal]/[0103][Binary Tree Zigzag LevelOrder Traversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0103][Binary Tree Zigzag LevelOrder Traversal]/[0103][BinaryTreeZigzagLevelOrderTraversal].iml b/[0103][Binary Tree Zigzag LevelOrder Traversal]/[0103][BinaryTreeZigzagLevelOrderTraversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0103][Binary Tree Zigzag LevelOrder Traversal]/[0103][BinaryTreeZigzagLevelOrderTraversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/src/Main.java" b/[0103][Binary Tree Zigzag LevelOrder Traversal]/src/Main.java similarity index 100% rename from "\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/src/Main.java" rename to [0103][Binary Tree Zigzag LevelOrder Traversal]/src/Main.java diff --git "a/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/src/Solution.java" b/[0103][Binary Tree Zigzag LevelOrder Traversal]/src/Solution.java similarity index 100% rename from "\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/src/Solution.java" rename to [0103][Binary Tree Zigzag LevelOrder Traversal]/src/Solution.java diff --git "a/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/src/TreeNode.java" b/[0103][Binary Tree Zigzag LevelOrder Traversal]/src/TreeNode.java similarity index 100% rename from "\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/src/TreeNode.java" rename to [0103][Binary Tree Zigzag LevelOrder Traversal]/src/TreeNode.java diff --git a/[0104][Maximum Depth Of Binary Tree]/[0104][Maximum Depth Of Binary Tree].iml b/[0104][Maximum Depth Of Binary Tree]/[0104][Maximum Depth Of Binary Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0104][Maximum Depth Of Binary Tree]/[0104][Maximum Depth Of Binary Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221/src/Solution.java" b/[0104][Maximum Depth Of Binary Tree]/src/Solution.java similarity index 100% rename from "\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221/src/Solution.java" rename to [0104][Maximum Depth Of Binary Tree]/src/Solution.java diff --git "a/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221/src/TreeNode.java" b/[0104][Maximum Depth Of Binary Tree]/src/TreeNode.java similarity index 100% rename from "\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221/src/TreeNode.java" rename to [0104][Maximum Depth Of Binary Tree]/src/TreeNode.java diff --git a/[0105][Construct Binary Tree From Preorder And Inorder Traversal]/[0105][Construct Binary Tree From Preorder And Inorder Traversal].iml b/[0105][Construct Binary Tree From Preorder And Inorder Traversal]/[0105][Construct Binary Tree From Preorder And Inorder Traversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0105][Construct Binary Tree From Preorder And Inorder Traversal]/[0105][Construct Binary Tree From Preorder And Inorder Traversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0105][Construct Binary Tree From Preorder And Inorder Traversal]/src/Solution.java b/[0105][Construct Binary Tree From Preorder And Inorder Traversal]/src/Solution.java new file mode 100644 index 0000000..5922420 --- /dev/null +++ b/[0105][Construct Binary Tree From Preorder And Inorder Traversal]/src/Solution.java @@ -0,0 +1,89 @@ +/** + * Author: + * Date: 2015-06-23 + * Time: 14:04 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *

+     * Given preorder and inorder traversal of a tree, construct the binary tree.
+     *
+     * Note:
+     * You may assume that duplicates do not exist in the tree.
+     *
+     * Ŀ⣺
+     * һǰУһ
+     * ע⣺
+     *   - ԪظԪ
+     *
+     * ˼·
+     * ǰһԪǸ㣨kֵΪk±idx
+     * idxзֳǰҲһɽеݹ
+     * 
+ * + * @param preorder + * @param inorder + * @return + */ + public TreeNode buildTree(int[] preorder, int[] inorder) { + + // У + if (preorder == null || inorder == null || preorder.length == 0 || preorder.length != inorder.length) { + return null; + } + return solve(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); + } + + /** + * ȷԼ֤ + * + * @param preorder Ľ + * @param x Ŀʼλ + * @param y Ľλ + * @param inorder Ľ + * @param i Ŀʼλ + * @param j Ľλ + * @return ĸ + */ + public TreeNode solve(int[] preorder, int x, int y, int[] inorder, int i, int j) { + + if (x >= 0 && x <= y && i >= 0 && i <= j) { + // ֻһԪ + if (x == y) { + return new TreeNode(preorder[x]); + } + // xܴy + else if (x < y) { + // ¼ + int idx = i; + while (idx <= j && inorder[idx] != preorder[x]) { + idx++; + } + + // + TreeNode root = new TreeNode(inorder[idx]); + + // Ľ + //[i, i+1, ..., idx - 1] -> ܼidx - i + int leftLength = idx - i; + // + if (leftLength > 0) { + // x + 1, x + leftLengthʼͽλ + root.left = solve(preorder, x + 1, x + leftLength, inorder, i, idx - 1); + } + + // Ľ + // [idx+1, idx+2, ..., j] -> ܼƣj - idx + int rightLength = j - idx; + if (rightLength > 0) { + // x + leftLength + 1, yʼͽλ + root.right = solve(preorder, x + leftLength + 1, y, inorder, idx + 1, j); + } + return root; + } + } + + return null; + } +} diff --git "a/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/src/TreeNode.java" b/[0105][Construct Binary Tree From Preorder And Inorder Traversal]/src/TreeNode.java similarity index 100% rename from "\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/src/TreeNode.java" rename to [0105][Construct Binary Tree From Preorder And Inorder Traversal]/src/TreeNode.java diff --git a/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/[0106][Construct Binary Tree From Inorder And Postorder Traversal].iml b/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/[0106][Construct Binary Tree From Inorder And Postorder Traversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/[0106][Construct Binary Tree From Inorder And Postorder Traversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/Main.java b/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/Main.java new file mode 100644 index 0000000..c3569f8 --- /dev/null +++ b/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/Main.java @@ -0,0 +1,24 @@ +/** + * Author: ������ + * Date: 2015-06-23 + * Time: 10:32 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + int[] inorder = {1, 2, 3, 4}; + int[] postorder = {3, 2, 4, 1}; + + TreeNode root = solution.buildTree(inorder, postorder); + print(root); + } + + public static void print(TreeNode root) { + if (root != null) { + print(root.left); + System.out.print(root.val + " "); + print(root.right); + } + } +} diff --git a/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/Solution.java b/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/Solution.java new file mode 100644 index 0000000..d6415c7 --- /dev/null +++ b/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/Solution.java @@ -0,0 +1,92 @@ +/** + * Author: + * Date: 2015-06-23 + * Time: 10:05 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given inorder and postorder traversal of a tree, construct the binary tree.
+     *
+     * Note:
+     * You may assume that duplicates do not exist in the tree.
+     *
+     * Ŀ⣺
+     * һͺУһö
+     * ע⣺
+     * ûظԪ
+     *
+     * ˼·
+     * һԪؾĸ(ֵΪr)
+     * ֵΪrλidxidxзΪ
+     * ӦԽзݹ
+     * 
+ * + * @param inorder + * @param postorder + * @return + */ + public TreeNode buildTree(int[] inorder, int[] postorder) { + + // + if (inorder == null || postorder == null || inorder.length == 0 || inorder.length != postorder.length) { + return null; + } + + // + return solve(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); + } + + /** + * + * + * @param inorder Ľ + * @param x Ŀʼλ + * @param y Ľλ + * @param postorder Ľ + * @param i Ŀʼλ + * @param j Ľλ + * @return + */ + public TreeNode solve(int[] inorder, int x, int y, int[] postorder, int i, int j) { + + if (x >= 0 && x <= y && i >= 0 && i <= j) { + // ֻһԪأʱҲi=jɣ + if (x == y) { + return new TreeNode(postorder[j]); + } + // һԪأʱҲi ܼ idx-x + int leftLength = idx - x; + if (leftLength > 0) { + // i, i + leftLength - 1ǰʼλ + root.left = solve(inorder, x, idx - 1, postorder, i, i + leftLength - 1); + } + + // ǿգ + // [idx+1, idx+2, ..., y] -> ܼ y-idx + int rightLength = y - idx; + if (rightLength > 0) { + // i + leftLength, j - 1ǰʼλ + root.right = solve(inorder, idx + 1, y, postorder, i + leftLength, j - 1); + } + + return root; + } + } + + return null; + } +} diff --git "a/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/TreeNode.java" b/[0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/TreeNode.java similarity index 100% rename from "\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/TreeNode.java" rename to [0106][Construct Binary Tree From Inorder And Postorder Traversal]/src/TreeNode.java diff --git a/[0107][Binary Tree Level Order Traversa lII]/[0107][Binary Tree Level Order Traversa lII].iml b/[0107][Binary Tree Level Order Traversa lII]/[0107][Binary Tree Level Order Traversa lII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0107][Binary Tree Level Order Traversa lII]/[0107][Binary Tree Level Order Traversa lII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0107][Binary Tree Level Order Traversa lII]/[0107][BinaryTreeLevelOrderTraversalII].iml b/[0107][Binary Tree Level Order Traversa lII]/[0107][BinaryTreeLevelOrderTraversalII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0107][Binary Tree Level Order Traversa lII]/[0107][BinaryTreeLevelOrderTraversalII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221/src/Solution.java" b/[0107][Binary Tree Level Order Traversa lII]/src/Solution.java similarity index 100% rename from "\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221/src/Solution.java" rename to [0107][Binary Tree Level Order Traversa lII]/src/Solution.java diff --git "a/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221/src/TreeNode.java" b/[0107][Binary Tree Level Order Traversa lII]/src/TreeNode.java similarity index 100% rename from "\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221/src/TreeNode.java" rename to [0107][Binary Tree Level Order Traversa lII]/src/TreeNode.java diff --git a/[0108][Convert Sorted Array To Binary Search Tree]/[0108][Convert Sorted Array To Binary Search Tree].iml b/[0108][Convert Sorted Array To Binary Search Tree]/[0108][Convert Sorted Array To Binary Search Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0108][Convert Sorted Array To Binary Search Tree]/[0108][Convert Sorted Array To Binary Search Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0108][Convert Sorted Array To Binary Search Tree]/[0108][ConvertSortedArrayToBinarySearchTree].iml b/[0108][Convert Sorted Array To Binary Search Tree]/[0108][ConvertSortedArrayToBinarySearchTree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0108][Convert Sorted Array To Binary Search Tree]/[0108][ConvertSortedArrayToBinarySearchTree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221/src/Solution.java" b/[0108][Convert Sorted Array To Binary Search Tree]/src/Solution.java similarity index 100% rename from "\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221/src/Solution.java" rename to [0108][Convert Sorted Array To Binary Search Tree]/src/Solution.java diff --git "a/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221/src/TreeNode.java" b/[0108][Convert Sorted Array To Binary Search Tree]/src/TreeNode.java similarity index 100% rename from "\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221/src/TreeNode.java" rename to [0108][Convert Sorted Array To Binary Search Tree]/src/TreeNode.java diff --git a/[0109][Convert Sorted List To Binary Search Tree]/[0109][Convert Sorted List To Binary Search Tree].iml b/[0109][Convert Sorted List To Binary Search Tree]/[0109][Convert Sorted List To Binary Search Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0109][Convert Sorted List To Binary Search Tree]/[0109][Convert Sorted List To Binary Search Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0109][Convert Sorted List To Binary Search Tree]/[0109][ConvertSortedListToBinarySearchTree].iml b/[0109][Convert Sorted List To Binary Search Tree]/[0109][ConvertSortedListToBinarySearchTree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0109][Convert Sorted List To Binary Search Tree]/[0109][ConvertSortedListToBinarySearchTree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/ListNode.java" b/[0109][Convert Sorted List To Binary Search Tree]/src/ListNode.java similarity index 100% rename from "\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/ListNode.java" rename to [0109][Convert Sorted List To Binary Search Tree]/src/ListNode.java diff --git "a/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/Main.java" b/[0109][Convert Sorted List To Binary Search Tree]/src/Main.java similarity index 100% rename from "\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/Main.java" rename to [0109][Convert Sorted List To Binary Search Tree]/src/Main.java diff --git "a/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/Solution.java" b/[0109][Convert Sorted List To Binary Search Tree]/src/Solution.java similarity index 100% rename from "\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/Solution.java" rename to [0109][Convert Sorted List To Binary Search Tree]/src/Solution.java diff --git "a/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/TreeNode.java" b/[0109][Convert Sorted List To Binary Search Tree]/src/TreeNode.java similarity index 100% rename from "\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/src/TreeNode.java" rename to [0109][Convert Sorted List To Binary Search Tree]/src/TreeNode.java diff --git a/[0110][Balanced Binary Tree]/[0110][Balanced Binary Tree].iml b/[0110][Balanced Binary Tree]/[0110][Balanced Binary Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0110][Balanced Binary Tree]/[0110][Balanced Binary Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0110][Balanced Binary Tree]/[0110][BalancedBinaryTree].iml b/[0110][Balanced Binary Tree]/[0110][BalancedBinaryTree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0110][Balanced Binary Tree]/[0110][BalancedBinaryTree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221/src/Solution.java" b/[0110][Balanced Binary Tree]/src/Solution.java similarity index 100% rename from "\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221/src/Solution.java" rename to [0110][Balanced Binary Tree]/src/Solution.java diff --git "a/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221/src/TreeNode.java" b/[0110][Balanced Binary Tree]/src/TreeNode.java similarity index 100% rename from "\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221/src/TreeNode.java" rename to [0110][Balanced Binary Tree]/src/TreeNode.java diff --git a/[0111][Minimum Depth Of Binary Tree]/[0111][Minimum Depth Of Binary Tree].iml b/[0111][Minimum Depth Of Binary Tree]/[0111][Minimum Depth Of Binary Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0111][Minimum Depth Of Binary Tree]/[0111][Minimum Depth Of Binary Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0111][Minimum Depth Of Binary Tree]/src/Solution.java b/[0111][Minimum Depth Of Binary Tree]/src/Solution.java new file mode 100644 index 0000000..836fb49 --- /dev/null +++ b/[0111][Minimum Depth Of Binary Tree]/src/Solution.java @@ -0,0 +1,40 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 18:51 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * һСȡ
+     *
+     * ˼·
+     * бҳСȡ
+     * 
+ * + * @param root + * @return + */ + public int minDepth(TreeNode root) { + return minDepth(root, false); + } + + public int minDepth(TreeNode root, boolean hasBrother) { + if (root == null) { + // ԼΪnullֵܲΪnullϲӽ㣬˵ǰûҵС + // ûֵܣ˵ǰʱֲСѾҵ + return hasBrother ? Integer.MAX_VALUE : 0; + } + + return 1 + Math.min(minDepth(root.left, root.right != null), + minDepth(root.right, root.left != null)); + } + +} diff --git a/[0111][Minimum Depth Of Binary Tree]/src/Solution2.java b/[0111][Minimum Depth Of Binary Tree]/src/Solution2.java new file mode 100644 index 0000000..6dfcd46 --- /dev/null +++ b/[0111][Minimum Depth Of Binary Tree]/src/Solution2.java @@ -0,0 +1,64 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 18:51 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + private int min = Integer.MAX_VALUE; // ¼С + private int cur = 0; // iǰij + + /** + *
+     * ԭ
+     * 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.
+     *
+     * Ŀ
+     * һСȡ
+     *
+     * ˼·
+     * бҳСȡ
+     * 
+ * + * @param root + * @return + */ + public int minDepth(TreeNode root) { + + depth(root); + return min; + } + + /** + * + * + * @param node ǰ + */ + private void depth(TreeNode node) { + + if (node == null) { + min = cur; + return; + } + + cur++; // ǰIJμ1 + // Ҷڵ㣬·ȼ¼СС + if (node.left == null && node.right == null && cur < min) { + min = cur; // Сֵ + } + // + if (node.left != null) { + depth(node.left); + } + + // + if (node.right != null) { + depth(node.right); + } + + cur--; // ԭ + + } +} diff --git "a/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/src/TreeNode.java" b/[0111][Minimum Depth Of Binary Tree]/src/TreeNode.java similarity index 100% rename from "\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/src/TreeNode.java" rename to [0111][Minimum Depth Of Binary Tree]/src/TreeNode.java diff --git a/[0112][Path Sum]/[0112][Path Sum].iml b/[0112][Path Sum]/[0112][Path Sum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0112][Path Sum]/[0112][Path Sum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0112][Path Sum]/[0112][PathSum].iml b/[0112][Path Sum]/[0112][PathSum].iml new file mode 100644 index 0000000..86622ab --- /dev/null +++ b/[0112][Path Sum]/[0112][PathSum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221/src/Solution.java" b/[0112][Path Sum]/src/Solution.java similarity index 100% rename from "\343\200\220112\343\200\221\343\200\220PathSum\343\200\221/src/Solution.java" rename to [0112][Path Sum]/src/Solution.java diff --git "a/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221/src/TreeNode.java" b/[0112][Path Sum]/src/TreeNode.java similarity index 100% rename from "\343\200\220112\343\200\221\343\200\220PathSum\343\200\221/src/TreeNode.java" rename to [0112][Path Sum]/src/TreeNode.java diff --git a/[0113][Path Sum II]/[0113][Path Sum II].iml b/[0113][Path Sum II]/[0113][Path Sum II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0113][Path Sum II]/[0113][Path Sum II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0113][Path Sum II]/[0113][PathSumII].iml b/[0113][Path Sum II]/[0113][PathSumII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0113][Path Sum II]/[0113][PathSumII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221/src/Solution.java" b/[0113][Path Sum II]/src/Solution.java similarity index 100% rename from "\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221/src/Solution.java" rename to [0113][Path Sum II]/src/Solution.java diff --git "a/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221/src/TreeNode.java" b/[0113][Path Sum II]/src/TreeNode.java similarity index 100% rename from "\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221/src/TreeNode.java" rename to [0113][Path Sum II]/src/TreeNode.java diff --git a/[0114][Flatten Binary Tree To Linked List]/[0114][Flatten Binary Tree To Linked List].iml b/[0114][Flatten Binary Tree To Linked List]/[0114][Flatten Binary Tree To Linked List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0114][Flatten Binary Tree To Linked List]/[0114][Flatten Binary Tree To Linked List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0114][Flatten Binary Tree To Linked List]/[0114][FlattenBinaryTreeToLinkedList].iml b/[0114][Flatten Binary Tree To Linked List]/[0114][FlattenBinaryTreeToLinkedList].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0114][Flatten Binary Tree To Linked List]/[0114][FlattenBinaryTreeToLinkedList].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/src/Solution.java" b/[0114][Flatten Binary Tree To Linked List]/src/Solution.java similarity index 100% rename from "\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/src/Solution.java" rename to [0114][Flatten Binary Tree To Linked List]/src/Solution.java diff --git a/[0114][Flatten Binary Tree To Linked List]/src/TreeNode.java b/[0114][Flatten Binary Tree To Linked List]/src/TreeNode.java new file mode 100644 index 0000000..463b6fe --- /dev/null +++ b/[0114][Flatten Binary Tree To Linked List]/src/TreeNode.java @@ -0,0 +1,15 @@ +/** + * Author: ������ + * Date: 2015-08-21 + * Time: 19:02 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0116][Populating Next Right Pointersin Each Node]/[0116][Populating Next Right Pointersin Each Node].iml b/[0116][Populating Next Right Pointersin Each Node]/[0116][Populating Next Right Pointersin Each Node].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0116][Populating Next Right Pointersin Each Node]/[0116][Populating Next Right Pointersin Each Node].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0116][Populating Next Right Pointersin Each Node]/[0116][PopulatingNextRightPointersinEachNode ].iml b/[0116][Populating Next Right Pointersin Each Node]/[0116][PopulatingNextRightPointersinEachNode ].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0116][Populating Next Right Pointersin Each Node]/[0116][PopulatingNextRightPointersinEachNode ].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221/src/Solution.java" b/[0116][Populating Next Right Pointersin Each Node]/src/Solution.java similarity index 100% rename from "\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221/src/Solution.java" rename to [0116][Populating Next Right Pointersin Each Node]/src/Solution.java diff --git "a/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221/src/TreeLinkNode.java" b/[0116][Populating Next Right Pointersin Each Node]/src/TreeLinkNode.java similarity index 100% rename from "\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221/src/TreeLinkNode.java" rename to [0116][Populating Next Right Pointersin Each Node]/src/TreeLinkNode.java diff --git a/[0117][Populating Next Right Pointers In Each Node II]/[0117][Populating Next Right Pointers In Each Node II].iml b/[0117][Populating Next Right Pointers In Each Node II]/[0117][Populating Next Right Pointers In Each Node II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0117][Populating Next Right Pointers In Each Node II]/[0117][Populating Next Right Pointers In Each Node II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0117][Populating Next Right Pointers In Each Node II]/[0117][PopulatingNextRightPointersInEachNodeII].iml b/[0117][Populating Next Right Pointers In Each Node II]/[0117][PopulatingNextRightPointersInEachNodeII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0117][Populating Next Right Pointers In Each Node II]/[0117][PopulatingNextRightPointersInEachNodeII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/src/Main.java" b/[0117][Populating Next Right Pointers In Each Node II]/src/Main.java similarity index 100% rename from "\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/src/Main.java" rename to [0117][Populating Next Right Pointers In Each Node II]/src/Main.java diff --git "a/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/src/Solution.java" b/[0117][Populating Next Right Pointers In Each Node II]/src/Solution.java similarity index 100% rename from "\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/src/Solution.java" rename to [0117][Populating Next Right Pointers In Each Node II]/src/Solution.java diff --git "a/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/src/TreeLinkNode.java" b/[0117][Populating Next Right Pointers In Each Node II]/src/TreeLinkNode.java similarity index 100% rename from "\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/src/TreeLinkNode.java" rename to [0117][Populating Next Right Pointers In Each Node II]/src/TreeLinkNode.java diff --git a/[0118][Pascal's Triangle]/[0118][Pascal's Triangle].iml b/[0118][Pascal's Triangle]/[0118][Pascal's Triangle].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0118][Pascal's Triangle]/[0118][Pascal's Triangle].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0118][Pascal's Triangle]/[0118][Pascal'sTriangle].iml b/[0118][Pascal's Triangle]/[0118][Pascal'sTriangle].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0118][Pascal's Triangle]/[0118][Pascal'sTriangle].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221/src/Solution.java" b/[0118][Pascal's Triangle]/src/Solution.java similarity index 100% rename from "\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221/src/Solution.java" rename to [0118][Pascal's Triangle]/src/Solution.java diff --git a/[0119][Pascal's Triangle II]/[0119][Pascal's Triangle II].iml b/[0119][Pascal's Triangle II]/[0119][Pascal's Triangle II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0119][Pascal's Triangle II]/[0119][Pascal's Triangle II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0119][Pascal's Triangle II]/[0119][Pascal'sTriangleII].iml b/[0119][Pascal's Triangle II]/[0119][Pascal'sTriangleII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0119][Pascal's Triangle II]/[0119][Pascal'sTriangleII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221/src/Solution.java" b/[0119][Pascal's Triangle II]/src/Solution.java similarity index 100% rename from "\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221/src/Solution.java" rename to [0119][Pascal's Triangle II]/src/Solution.java diff --git a/[0120][Triangle]/[0120][Triangle].iml b/[0120][Triangle]/[0120][Triangle].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0120][Triangle]/[0120][Triangle].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/src/Main.java" b/[0120][Triangle]/src/Main.java similarity index 100% rename from "\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/src/Main.java" rename to [0120][Triangle]/src/Main.java diff --git "a/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/src/Solution.java" b/[0120][Triangle]/src/Solution.java similarity index 100% rename from "\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/src/Solution.java" rename to [0120][Triangle]/src/Solution.java diff --git a/[0121][Best Time To Buy And Sell Stock]/[0121][Best Time To Buy And Sell Stock].iml b/[0121][Best Time To Buy And Sell Stock]/[0121][Best Time To Buy And Sell Stock].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0121][Best Time To Buy And Sell Stock]/[0121][Best Time To Buy And Sell Stock].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0121][Best Time To Buy And Sell Stock]/src/Solution.java b/[0121][Best Time To Buy And Sell Stock]/src/Solution.java new file mode 100644 index 0000000..6809bcf --- /dev/null +++ b/[0121][Best Time To Buy And Sell Stock]/src/Solution.java @@ -0,0 +1,58 @@ +/** + * Author: + * Date: 2015-06-22 + * Time: 15:42 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Say you have an array for which the ith 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.
+     *
+     * Ŀ⣺
+     * һprices[]prices[i]Ʊڵiۼֻۣһν(һ)ܵõ档
+     *
+     * ˼·
+     * 
+     * ̰ķֱҵ۸ͺߵһ죬ͽ߳ע͵һҪߵһ֮ǰ
+     * ԭʼ۸бɲУҲmӶκͣm = 1
+     *
+     * ֻҪҳIJֵɣ max(prices[j], prices[i]) i < jһαɣڱʱñ
+     * low¼ prices[0, ..., i] еСֵǵǰΪֹۼۣʱ临ӶΪ O(n)
+     * 
+ * + * @param prices + * @return + */ + public int maxProfit(int[] prices) { + + if (prices == null || prices.length < 1) { + return 0; + } + + int min = prices[0]; + int profit = 0; + + // iļ۸ԿҲԿ + for (int i = 1; i < prices.length; i++) { + // ҵ͵ + if (min > prices[i]) { + // + min = prices[i]; + } + // ļ۸񲻵 + else { + // ļ۸֮ǰļ۸ + if (profit < prices[i] - min) { + // + profit = prices[i] - min; + } + } + } + + return profit; + } +} diff --git a/[0122][Best Time to Buy and Sell Stock II]/[0122][Best Time to Buy and Sell Stock II].iml b/[0122][Best Time to Buy and Sell Stock II]/[0122][Best Time to Buy and Sell Stock II].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0122][Best Time to Buy and Sell Stock II]/[0122][Best Time to Buy and Sell Stock II].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0122][Best Time to Buy and Sell Stock II]/src/Main.java b/[0122][Best Time to Buy and Sell Stock II]/src/Main.java new file mode 100644 index 0000000..b0a9f62 --- /dev/null +++ b/[0122][Best Time to Buy and Sell Stock II]/src/Main.java @@ -0,0 +1,37 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 09:13 + **/ +public class Main { + + @Test + public void test1() { + int[] prices = {7, 1, 5, 3, 6, 4}; + Solution solution = new Solution(); + Assert.assertEquals(7, solution.maxProfit(prices)); + } + + @Test + public void test2() { + int[] prices = {1, 2, 3, 4, 5}; + Solution solution = new Solution(); + Assert.assertEquals(4, solution.maxProfit(prices)); + } + + @Test + public void test3() { + int[] prices = {7, 6, 4, 3, 1}; + Solution solution = new Solution(); + Assert.assertEquals(0, solution.maxProfit(prices)); + } + + @Test + public void test4() { + int[] prices = {3, 2, 9, 1, 7, 4}; + Solution2 solution = new Solution2(); + Assert.assertEquals(13, solution.maxProfit(prices)); + } +} diff --git a/[0122][Best Time to Buy and Sell Stock II]/src/Solution.java b/[0122][Best Time to Buy and Sell Stock II]/src/Solution.java new file mode 100644 index 0000000..baed796 --- /dev/null +++ b/[0122][Best Time to Buy and Sell Stock II]/src/Solution.java @@ -0,0 +1,58 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 08:46 + **/ +public class Solution { + /** + *
+     * Say you have an array for which the ith 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.
+     *
+     * 
+ * + * @param prices + * @return + */ + public int maxProfit(int[] prices) { + + if (prices == null || prices.length < 2) { + return 0; + } + + int sum = 0; + int diff; + for (int i = 1; i < prices.length; i++) { + // 如果后一天的价格比前一天高就卖出 + diff = prices[i] - prices[i - 1]; + if (diff > 0) { + sum += diff; + } + } + + return sum; + } +} diff --git a/[0122][Best Time to Buy and Sell Stock II]/src/Solution2.java b/[0122][Best Time to Buy and Sell Stock II]/src/Solution2.java new file mode 100644 index 0000000..cef7e3c --- /dev/null +++ b/[0122][Best Time to Buy and Sell Stock II]/src/Solution2.java @@ -0,0 +1,71 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 08:46 + **/ +public class Solution2 { + /** + *
+     * Say you have an array for which the ith 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.
+     *
+     * 
+ * + * @param prices + * @return + */ + public int maxProfit(int[] prices) { + + if (prices == null || prices.length < 2) { + return 0; + } + + int buy = 0; + int sell = 1; + + int sum = 0; + while (sell < prices.length) { + // 从buy的位置开始找降序子序列中最小的值 + while (buy + 1 < prices.length && prices[buy] >= prices[buy + 1]) { + buy++; + } + // 从buy的位置开始找升序子序列中最大的值 + sell = buy + 1; + while (sell + 1 < prices.length && prices[sell] <= prices[sell + 1]) { + sell++; + } + + if (sell < prices.length) { + sum += prices[sell] - prices[buy]; + } + + buy = sell + 1; + + } + + return sum; + } +} diff --git a/[0124][Binary Tree Maximum Path Sum]/[0124][Binary Tree Maximum Path Sum].iml b/[0124][Binary Tree Maximum Path Sum]/[0124][Binary Tree Maximum Path Sum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0124][Binary Tree Maximum Path Sum]/[0124][Binary Tree Maximum Path Sum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0124][Binary Tree Maximum Path Sum]/[0124][BinaryTreeMaximumPathSum].iml b/[0124][Binary Tree Maximum Path Sum]/[0124][BinaryTreeMaximumPathSum].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0124][Binary Tree Maximum Path Sum]/[0124][BinaryTreeMaximumPathSum].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220124\346\234\252\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221/src/Solution.java" b/[0124][Binary Tree Maximum Path Sum]/src/Solution.java similarity index 100% rename from "\343\200\220124\346\234\252\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221/src/Solution.java" rename to [0124][Binary Tree Maximum Path Sum]/src/Solution.java diff --git "a/\343\200\220124\346\234\252\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221/src/TreeNode.java" b/[0124][Binary Tree Maximum Path Sum]/src/TreeNode.java similarity index 100% rename from "\343\200\220124\346\234\252\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221/src/TreeNode.java" rename to [0124][Binary Tree Maximum Path Sum]/src/TreeNode.java diff --git a/[0125][Valid Palindrome]/[0125][Valid Palindrome].iml b/[0125][Valid Palindrome]/[0125][Valid Palindrome].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0125][Valid Palindrome]/[0125][Valid Palindrome].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0125][Valid Palindrome]/[0125][ValidPalindrome].iml b/[0125][Valid Palindrome]/[0125][ValidPalindrome].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0125][Valid Palindrome]/[0125][ValidPalindrome].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221/src/Solution.java" b/[0125][Valid Palindrome]/src/Solution.java similarity index 100% rename from "\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221/src/Solution.java" rename to [0125][Valid Palindrome]/src/Solution.java diff --git a/[0126][Word Ladder II]/[0126][Word Ladder II].iml b/[0126][Word Ladder II]/[0126][Word Ladder II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0126][Word Ladder II]/[0126][Word Ladder II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0126][Word Ladder II]/src/Main.java b/[0126][Word Ladder II]/src/Main.java new file mode 100644 index 0000000..87f620f --- /dev/null +++ b/[0126][Word Ladder II]/src/Main.java @@ -0,0 +1,49 @@ +import org.junit.Test; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-20 08:17 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + String beginWord = "hit"; + String endWord = "cog"; + List wordList = new LinkedList<>(Arrays.asList("hot", "dot", "dog", "lot", "log", "cog")); + System.out.println(solution.findLadders(beginWord, endWord, wordList)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + String beginWord = "hot"; + String endWord = "dog"; + List wordList = new LinkedList<>(Arrays.asList("hot", "dog", "dot")); + System.out.println(solution.findLadders(beginWord, endWord, wordList)); + } + + @Test + public void test3() { + Solution solution = new Solution(); + String beginWord = "cet"; + String endWord = "ism"; + String[] words = {"kid", "tag", "pup", "ail", "tun", "woo", "erg", "luz", "brr", "gay", "sip", "kay", "per", "val", "mes", "ohs", "now", "boa", "cet", "pal", "bar", "die", "war", "hay", "eco", "pub", "lob", "rue", "fry", "lit", "rex", "jan", "cot", "bid", "ali", "pay", "col", "gum", "ger", "row", "won", "dan", "rum", "fad", "tut", "sag", "yip", "sui", "ark", "has", "zip", "fez", "own", "ump", "dis", "ads", "max", "jaw", "out", "btu", "ana", "gap", "cry", "led", "abe", "box", "ore", "pig", "fie", "toy", "fat", "cal", "lie", "noh", "sew", "ono", "tam", "flu", "mgm", "ply", "awe", "pry", "tit", "tie", "yet", "too", "tax", "jim", "san", "pan", "map", "ski", "ova", "wed", "non", "wac", "nut", "why", "bye", "lye", "oct", "old", "fin", "feb", "chi", "sap", "owl", "log", "tod", "dot", "bow", "fob", "for", "joe", "ivy", "fan", "age", "fax", "hip", "jib", "mel", "hus", "sob", "ifs", "tab", "ara", "dab", "jag", "jar", "arm", "lot", "tom", "sax", "tex", "yum", "pei", "wen", "wry", "ire", "irk", "far", "mew", "wit", "doe", "gas", "rte", "ian", "pot", "ask", "wag", "hag", "amy", "nag", "ron", "soy", "gin", "don", "tug", "fay", "vic", "boo", "nam", "ave", "buy", "sop", "but", "orb", "fen", "paw", "his", "sub", "bob", "yea", "oft", "inn", "rod", "yam", "pew", "web", "hod", "hun", "gyp", "wei", "wis", "rob", "gad", "pie", "mon", "dog", "bib", "rub", "ere", "dig", "era", "cat", "fox", "bee", "mod", "day", "apr", "vie", "nev", "jam", "pam", "new", "aye", "ani", "and", "ibm", "yap", "can", "pyx", "tar", "kin", "fog", "hum", "pip", "cup", "dye", "lyx", "jog", "nun", "par", "wan", "fey", "bus", "oak", "bad", "ats", "set", "qom", "vat", "eat", "pus", "rev", "axe", "ion", "six", "ila", "lao", "mom", "mas", "pro", "few", "opt", "poe", "art", "ash", "oar", "cap", "lop", "may", "shy", "rid", "bat", "sum", "rim", "fee", "bmw", "sky", "maj", "hue", "thy", "ava", "rap", "den", "fla", "auk", "cox", "ibo", "hey", "saw", "vim", "sec", "ltd", "you", "its", "tat", "dew", "eva", "tog", "ram", "let", "see", "zit", "maw", "nix", "ate", "gig", "rep", "owe", "ind", "hog", "eve", "sam", "zoo", "any", "dow", "cod", "bed", "vet", "ham", "sis", "hex", "via", "fir", "nod", "mao", "aug", "mum", "hoe", "bah", "hal", "keg", "hew", "zed", "tow", "gog", "ass", "dem", "who", "bet", "gos", "son", "ear", "spy", "kit", "boy", "due", "sen", "oaf", "mix", "hep", "fur", "ada", "bin", "nil", "mia", "ewe", "hit", "fix", "sad", "rib", "eye", "hop", "haw", "wax", "mid", "tad", "ken", "wad", "rye", "pap", "bog", "gut", "ito", "woe", "our", "ado", "sin", "mad", "ray", "hon", "roy", "dip", "hen", "iva", "lug", "asp", "hui", "yak", "bay", "poi", "yep", "bun", "try", "lad", "elm", "nat", "wyo", "gym", "dug", "toe", "dee", "wig", "sly", "rip", "geo", "cog", "pas", "zen", "odd", "nan", "lay", "pod", "fit", "hem", "joy", "bum", "rio", "yon", "dec", "leg", "put", "sue", "dim", "pet", "yaw", "nub", "bit", "bur", "sid", "sun", "oil", "red", "doc", "moe", "caw", "eel", "dix", "cub", "end", "gem", "off", "yew", "hug", "pop", "tub", "sgt", "lid", "pun", "ton", "sol", "din", "yup", "jab", "pea", "bug", "gag", "mil", "jig", "hub", "low", "did", "tin", "get", "gte", "sox", "lei", "mig", "fig", "lon", "use", "ban", "flo", "nov", "jut", "bag", "mir", "sty", "lap", "two", "ins", "con", "ant", "net", "tux", "ode", "stu", "mug", "cad", "nap", "gun", "fop", "tot", "sow", "sal", "sic", "ted", "wot", "del", "imp", "cob", "way", "ann", "tan", "mci", "job", "wet", "ism", "err", "him", "all", "pad", "hah", "hie", "aim", "ike", "jed", "ego", "mac", "baa", "min", "com", "ill", "was", "cab", "ago", "ina", "big", "ilk", "gal", "tap", "duh", "ola", "ran", "lab", "top", "gob", "hot", "ora", "tia", "kip", "han", "met", "hut", "she", "sac", "fed", "goo", "tee", "ell", "not", "act", "gil", "rut", "ala", "ape", "rig", "cid", "god", "duo", "lin", "aid", "gel", "awl", "lag", "elf", "liz", "ref", "aha", "fib", "oho", "tho", "her", "nor", "ace", "adz", "fun", "ned", "coo", "win", "tao", "coy", "van", "man", "pit", "guy", "foe", "hid", "mai", "sup", "jay", "hob", "mow", "jot", "are", "pol", "arc", "lax", "aft", "alb", "len", "air", "pug", "pox", "vow", "got", "meg", "zoe", "amp", "ale", "bud", "gee", "pin", "dun", "pat", "ten", "mob"}; +// List wordList = new ArrayList<>(); +// wordList.addAll(Arrays.asList(words)); + System.out.println(solution.findLadders(beginWord, endWord, Arrays.asList(words))); + } + + @Test + public void test4() { + Solution solution = new Solution(); + String beginWord = "hit"; + String endWord = "cog"; + List wordList = new LinkedList<>(Arrays.asList("hot", "dot", "dog", "lot", "log")); + System.out.println(solution.findLadders(beginWord, endWord, wordList)); + } +} diff --git a/[0126][Word Ladder II]/src/Solution.java b/[0126][Word Ladder II]/src/Solution.java new file mode 100644 index 0000000..14edd09 --- /dev/null +++ b/[0126][Word Ladder II]/src/Solution.java @@ -0,0 +1,124 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-20 08:42 + **/ +public class Solution { + /** + *
+     * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
+     *
+     * Only one letter can be changed at a time
+     * Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
+     * Note:
+     *
+     * Return an empty list if there is no such transformation sequence.
+     * All words have the same length.
+     * All words contain only lowercase alphabetic characters.
+     * You may assume no duplicates in the word list.
+     * You may assume beginWord and endWord are non-empty and are not the same.
+     * Example 1:
+     *
+     * Input:
+     * beginWord = "hit",
+     * endWord = "cog",
+     * wordList = ["hot","dot","dog","lot","log","cog"]
+     *
+     * Output:
+     * [
+     *   ["hit","hot","dot","dog","cog"],
+     *   ["hit","hot","lot","log","cog"]
+     * ]
+     * Example 2:
+     *
+     * Input:
+     * beginWord = "hit"
+     * endWord = "cog"
+     * wordList = ["hot","dot","dog","lot","log"]
+     *
+     * Output: []
+     *
+     * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
+     *
+     * 使用了图的遍历
+     * https://www.cnblogs.com/splash/p/4102786.html
+     * 
+ * + * @param beginWord + * @param endWord + * @param wordList + * @return + */ + HashMap> nodeSet = new HashMap<>(); + + public List> findLadders(String start, String end, List wordList) { + Set wordDict = new HashSet<>(wordList); + + List> result = new ArrayList>(); + + if (!wordDict.contains(end)) { + return result; + } + + Queue q = new LinkedList(); + HashSet hs = new HashSet(); + HashMap dist = new HashMap(); + q.add(start); + nodeSet.put(start, new ArrayList()); + nodeSet.put(end, new ArrayList()); + dist.put(start, 1); + + while (!q.isEmpty()) { + String temp = q.poll(); + int l = dist.get(temp); + hs.add(temp); + for (int i = 0; i < temp.length(); i++) { + for (char c = 'a'; c <= 'z'; c++) { + if (temp.charAt(i) == c) { + continue; + } + StringBuilder sb = new StringBuilder(temp); + sb.setCharAt(i, c); + String next = sb.toString(); + if (next.equals(end)) { + if (!dist.containsKey(end)) { + dist.put(end, l + 1); + nodeSet.get(end).add(temp); + } else if (dist.get(end) == l + 1) { + nodeSet.get(end).add(temp); + } + } else if (wordDict.contains(next) && !hs.contains(next)) { + if (!dist.containsKey(next)) { + q.add(next); + dist.put(next, l + 1); + ArrayList arr = new ArrayList(); + arr.add(temp); + nodeSet.put(next, arr); + } else if (dist.get(next) == l + 1) { + nodeSet.get(next).add(temp); + } + } + } + } + } + List path = new ArrayList(); + path.add(end); + + collect(start, result, path, nodeSet.get(end)); + return result; + } + + public void collect(String start, List> re, List path, ArrayList prevNodes) { + for (int i = 0; i < prevNodes.size(); i++) { + path.add(0, prevNodes.get(i)); + if (prevNodes.get(i).equals(start)) { + List pathCopy = new ArrayList(path); + re.add(pathCopy); + } else { + collect(start, re, path, nodeSet.get(prevNodes.get(i))); + } + path.remove(0); + } + } +} diff --git a/[0126][Word Ladder II]/src/Solution2.java b/[0126][Word Ladder II]/src/Solution2.java new file mode 100644 index 0000000..206bddb --- /dev/null +++ b/[0126][Word Ladder II]/src/Solution2.java @@ -0,0 +1,109 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-20 08:42 + **/ +public class Solution2 { + /** + *
+     * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
+     *
+     * Only one letter can be changed at a time
+     * Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
+     * Note:
+     *
+     * Return an empty list if there is no such transformation sequence.
+     * All words have the same length.
+     * All words contain only lowercase alphabetic characters.
+     * You may assume no duplicates in the word list.
+     * You may assume beginWord and endWord are non-empty and are not the same.
+     * Example 1:
+     *
+     * Input:
+     * beginWord = "hit",
+     * endWord = "cog",
+     * wordList = ["hot","dot","dog","lot","log","cog"]
+     *
+     * Output:
+     * [
+     *   ["hit","hot","dot","dog","cog"],
+     *   ["hit","hot","lot","log","cog"]
+     * ]
+     * Example 2:
+     *
+     * Input:
+     * beginWord = "hit"
+     * endWord = "cog"
+     * wordList = ["hot","dot","dog","lot","log"]
+     *
+     * Output: []
+     *
+     * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
+     *
+     * 使用了深度优化遍历方案,会超时
+     * 
+ * + * @param beginWord + * @param endWord + * @param wordList + * @return + */ + public List> findLadders(String beginWord, String endWord, List wordList) { + Set wordDict = new HashSet<>(wordList); + List> result = new LinkedList<>(); + Deque current = new LinkedList<>(); + findLadders(beginWord, endWord, wordDict, current, result); + for (List r : result) { + r.add(0, beginWord); + } + return result; + } + + private void findLadders(String beginWord, String endWord, Set wordDict, Deque current, List> result) { + + if (beginWord.equals(endWord)) { + + // 还没有结果,或者有的最优解,就添加结果 + if (result.isEmpty() || result.get(0).size() == current.size()) { + result.add(new LinkedList<>(current)); + } + // 当前解不是最优解,记录最优化解 + else if (result.get(0).size() > current.size()) { + result.clear(); + result.add(new LinkedList<>(current)); + } + + return; + } + + // 已经找到至少一个可能的最优解,当前还没有找到最优化解,但是转换次数已经等于目前找到的最优化解的次数, + // 目前的方案一定不存在最优化解 + if (!result.isEmpty() && current.size() >= result.get(0).size()) { + return; + } + + char[] chars = beginWord.toCharArray(); + + for (int i = 0; i < chars.length; i++) { + for (char ch = 'a'; ch <= 'z'; ch++) { + char temp = chars[i]; + chars[i] = ch; + String s = new String(chars); + + if (wordDict.contains(s)) { + wordDict.remove(s); + current.add(s); + + findLadders(s, endWord, wordDict, current, result); + // 还原 + wordDict.add(s); + current.remove(s); + } + + // 还原 + chars[i] = temp; + } + } + } +} diff --git a/[0126][Word Ladder II]/src/Solution3.java b/[0126][Word Ladder II]/src/Solution3.java new file mode 100644 index 0000000..ddb5639 --- /dev/null +++ b/[0126][Word Ladder II]/src/Solution3.java @@ -0,0 +1,124 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-20 08:42 + **/ +public class Solution3 { + /** + *
+     * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
+     *
+     * Only one letter can be changed at a time
+     * Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
+     * Note:
+     *
+     * Return an empty list if there is no such transformation sequence.
+     * All words have the same length.
+     * All words contain only lowercase alphabetic characters.
+     * You may assume no duplicates in the word list.
+     * You may assume beginWord and endWord are non-empty and are not the same.
+     * Example 1:
+     *
+     * Input:
+     * beginWord = "hit",
+     * endWord = "cog",
+     * wordList = ["hot","dot","dog","lot","log","cog"]
+     *
+     * Output:
+     * [
+     *   ["hit","hot","dot","dog","cog"],
+     *   ["hit","hot","lot","log","cog"]
+     * ]
+     * Example 2:
+     *
+     * Input:
+     * beginWord = "hit"
+     * endWord = "cog"
+     * wordList = ["hot","dot","dog","lot","log"]
+     *
+     * Output: []
+     *
+     * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
+     *
+     * 使用了广度优化遍历方案,会超时
+     * 
+ * + * @param beginWord + * @param endWord + * @param wordList + * @return + */ + public List> findLadders(String beginWord, String endWord, List wordList) { + + + Set wordDict = new HashSet<>(wordList); + List> result = new LinkedList<>(); + // 用于保存所有中间结果 + Deque> paths = new LinkedList<>(); + + + Deque deque = new LinkedList<>(); + deque.addLast(beginWord); + paths.addLast(deque); + + boolean find = false; + + while (!paths.isEmpty() && !find) { + // 先遍历看是否找到结果,如果找到了,一定是最优化解 + for (Deque path : paths) { + if (path.getLast().equals(endWord)) { + result.add(new LinkedList<>(path)); + find = true; + } + } + + // find表示已经找到了 + // paths.getFirst().size() >=beginWord.length()说明不可能找到结果,path最 + System.out.println(paths.getFirst().size()); + if (find || paths.getFirst().size() >= wordDict.size()) { + break; + } + + // TODO 什么时候判断找不到,path中可能形成环 + + + // 没有找到最优化解,构建下一层 + for (int k = paths.size(); k > 0; k--) { + + // 取路径的最后一个元素 + Deque path = paths.removeFirst(); + String s = path.getLast(); + + // 当前路径下,还可以使用的字词 + Set set = new HashSet<>(wordDict); + set.removeAll(path); + + System.out.println(set); + + // 找出当前层的每个元素经过一次变化后,是否在剩余的wordDict中找到, + // 如果找到就放到下一层的处理中 + char[] chars = s.toCharArray(); + for (int i = 0; i < beginWord.length(); i++) { + for (char j = 'a'; j <= 'z'; j++) { + char temp = chars[i]; + chars[i] = j; + String t = new String(chars); + + // 一次变换后可以找到单词,放到下一层处理中 + if (set.contains(t) && !t.equals(s)) { + path.addLast(t); + paths.addLast(new LinkedList<>(path)); + path.removeLast(); + } + // 还原 + chars[i] = temp; + } + } + + } + } + + return result; + } +} diff --git a/[0127][Word Ladder]/[0127][Word Ladder].iml b/[0127][Word Ladder]/[0127][Word Ladder].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0127][Word Ladder]/[0127][Word Ladder].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0127][Word Ladder]/[0127][WordLadder].iml b/[0127][Word Ladder]/[0127][WordLadder].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0127][Word Ladder]/[0127][WordLadder].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0127][Word Ladder]/src/Main.java b/[0127][Word Ladder]/src/Main.java new file mode 100644 index 0000000..2a6d29a --- /dev/null +++ b/[0127][Word Ladder]/src/Main.java @@ -0,0 +1,21 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-20 08:17 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + String beginWord = "hit"; + String endWord = "cog"; + List wordList = new LinkedList<>(Arrays.asList("hot", "dot", "dog", "lot", "log", "cog")); + Assert.assertEquals(5, solution.ladderLength(beginWord, endWord, wordList)); + } +} diff --git a/[0127][Word Ladder]/src/Solution.java b/[0127][Word Ladder]/src/Solution.java new file mode 100644 index 0000000..4cb9ab8 --- /dev/null +++ b/[0127][Word Ladder]/src/Solution.java @@ -0,0 +1,96 @@ +import java.util.*; + +/** + * Author: + * Date: 2015-06-20 + * Time: 08:11 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given two words (beginWord and endWord), and a dictionary, find the length
+     * of shortest transformation sequence from beginWord to endWord, such that:
+     *
+     *   - Only one letter can be changed at a time
+     *   - Each intermediate word must exist in the dictionary
+     *
+     * For example,
+     *
+     * Given:
+     * start = "hit"
+     * end = "cog"
+     * dict = ["hot","dot","dog","lot","log"]
+     * As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
+     * return its length 5.
+     *
+     * Note:
+     *   - Return 0 if there is no such transformation sequence.
+     *   - All words have the same length.
+     *   - All words contain only lowercase alphabetic characters.
+     *
+     * Ŀ⣺
+     * ʣbeginWordendWordһֵ䣬ҴbeginWordת͵endWord̳ȣ
+     *   - һֻһĸԱı
+     *   - ÿмֱڴʵ
+     *
+     * ע⣺
+     *   - ı任У0
+     *   - еʾͬijȡ
+     *   - еֻСдĸַ
+     *
+     * ˼·
+     * Ż
+     * 
+ * + * @param beginWord + * @param endWord + * @param wordList + * @return + */ + public int ladderLength(String beginWord, String endWord, List wordList) { + + Set wordDict = new HashSet<>(wordList); + + char[] chars; + Deque deque = new LinkedList<>(); + deque.addLast(beginWord); + int result = 0; + String s; + String t; + while (!deque.isEmpty()) { + + // ǰ + for (int k = deque.size(); k > 0; k--) { + s = deque.removeFirst(); + + if (s.equalsIgnoreCase(endWord)) { + return result + 1; + } + + // ҳǰÿԪؾһα仯ǷʣwordDictҵ + // ҵͷŵһĴ + chars = s.toCharArray(); + for (int i = 0; i < beginWord.length(); i++) { + for (char j = 'a'; j <= 'z'; j++) { + char temp = chars[i]; + chars[i] = j; + t = new String(chars); + // һα任ҵʣŵһ㴦УwordDictɾ¼ + if (wordDict.contains(t) && !t.equals(s)) { + deque.addLast(t); + wordDict.remove(t); + } + // ԭ + chars[i] = temp; + } + } + } + + + result++; + } + + return 0; + } +} diff --git a/[0128][Longest Consecutive Sequence]/[0128][Longest Consecutive Sequence].iml b/[0128][Longest Consecutive Sequence]/[0128][Longest Consecutive Sequence].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0128][Longest Consecutive Sequence]/[0128][Longest Consecutive Sequence].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0128][Longest Consecutive Sequence]/src/Main.java b/[0128][Longest Consecutive Sequence]/src/Main.java new file mode 100644 index 0000000..d6d2e5c --- /dev/null +++ b/[0128][Longest Consecutive Sequence]/src/Main.java @@ -0,0 +1,17 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-14 15:02 + **/ +public class Main { + @Test + public void test() { + int[] nums = {100, 4, 200, 1, 3, 2}; + + Solution solution = new Solution(); + + Assert.assertEquals(4, solution.longestConsecutive(nums)); + } +} diff --git a/[0128][Longest Consecutive Sequence]/src/Solution.java b/[0128][Longest Consecutive Sequence]/src/Solution.java new file mode 100644 index 0000000..b41b5ec --- /dev/null +++ b/[0128][Longest Consecutive Sequence]/src/Solution.java @@ -0,0 +1,59 @@ +import java.util.HashSet; +import java.util.Set; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-14 14:48 + **/ +class Solution { + /** + *
+     * Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
+     *
+     * Your algorithm should run in O(n) complexity.
+     *
+     * Example:
+     *
+     * Input: [100, 4, 200, 1, 3, 2]
+     * Output: 4
+     * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
+     *
+     * 这道题要求求最长连续序列,并给定了O(n)复杂度限制,我们的思路是,使用一个集合HashSet存入所有的数字,
+     * 然后遍历数组中的每个数字,如果其在集合中存在,那么将其移除,然后分别用两个变量pre和next算出其前一个
+     * 数跟后一个数,然后在集合中循环查找,如果pre在集合中,那么将pre移除集合,然后pre再自减1,直至pre不在
+     * 集合之中,对next采用同样的方法,那么next-pre-1就是当前数字的最长连续序列,更新res即可。这里再说下,
+     * 为啥当检测某数字在集合中存在当时候,都要移除数字。这是为了避免大量的重复计算,就拿题目中的例子来说吧,
+     * 我们在遍历到4的时候,会向下遍历3,2,1,如果都不移除数字的话,遍历到1的时候,还会遍历2,3,4。同样,
+     * 遍历到3的时候,向上遍历4,向下遍历2,1,等等等。如果数组中有大量的连续数字的话,那么就有大量的重复计算,
+     * 十分的不高效,所以我们要从HashSet中移除数字
+     * 
+ * + * @param nums + * @return + */ + public int longestConsecutive(int[] nums) { + int res = 0; + Set set = new HashSet<>(); + + for (int i : nums) { + set.add(i); + } + + for (int i : nums) { + if (set.remove(i)) { + int prev = i - 1; + int next = i + 1; + while (set.remove(prev)) { + --prev; + } + while (set.remove(next)) { + ++next; + } + + res = Math.max(res, next - prev - 1); + } + } + + return res; + } +} diff --git a/[0129][Sum Root To Leaf Numbers]/[0129][Sum Root To Leaf Numbers].iml b/[0129][Sum Root To Leaf Numbers]/[0129][Sum Root To Leaf Numbers].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0129][Sum Root To Leaf Numbers]/[0129][Sum Root To Leaf Numbers].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0129][Sum Root To Leaf Numbers]/[0129][SumRootToLeafNumbers].iml b/[0129][Sum Root To Leaf Numbers]/[0129][SumRootToLeafNumbers].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0129][Sum Root To Leaf Numbers]/[0129][SumRootToLeafNumbers].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221/src/Solution.java" b/[0129][Sum Root To Leaf Numbers]/src/Solution.java similarity index 100% rename from "\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221/src/Solution.java" rename to [0129][Sum Root To Leaf Numbers]/src/Solution.java diff --git "a/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221/src/TreeNode.java" b/[0129][Sum Root To Leaf Numbers]/src/TreeNode.java similarity index 100% rename from "\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221/src/TreeNode.java" rename to [0129][Sum Root To Leaf Numbers]/src/TreeNode.java diff --git a/[0130][Surrounded Regions]/[0130][Surrounded Regions].iml b/[0130][Surrounded Regions]/[0130][Surrounded Regions].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0130][Surrounded Regions]/[0130][Surrounded Regions].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0130][Surrounded Regions]/[0130][SurroundedRegions].iml b/[0130][Surrounded Regions]/[0130][SurroundedRegions].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0130][Surrounded Regions]/[0130][SurroundedRegions].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0130][Surrounded Regions]/src/Main.java b/[0130][Surrounded Regions]/src/Main.java new file mode 100644 index 0000000..6c22ca8 --- /dev/null +++ b/[0130][Surrounded Regions]/src/Main.java @@ -0,0 +1,81 @@ +import org.junit.Test; + +/** + * Author: + * Date: 2015-06-22 + * Time: 10:02 + * Declaration: All Rights Reserved !!! + */ +public class Main { + + @Test + public void test01() { + Solution solution = new Solution(); + char[][] board = { + "XXXX".toCharArray(), + "XOOX".toCharArray(), + "XXOX".toCharArray(), + "XOXX".toCharArray() + }; + + solution.solve(board); + + for (char[] line : board) { + System.out.println(new String(line)); + } + System.out.println(); + } + + @Test + public void test02() { + Solution solution = new Solution(); + char[][] board = { + "XOXX".toCharArray(), + "OXOX".toCharArray(), + "XOXO".toCharArray(), + "OXOX".toCharArray(), + "XOXO".toCharArray(), + "OXOX".toCharArray() + }; + + solution.solve(board); + + for (char[] line : board) { + System.out.println(new String(line)); + } + System.out.println(); + } + + @Test + public void test03() { + Solution solution = new Solution(); + char[][] board = { + "OO".toCharArray(), + "OO".toCharArray() + }; + + solution.solve(board); + + for (char[] line : board) { + System.out.println(new String(line)); + } + System.out.println(); + } + + @Test + public void test04() { + Solution solution = new Solution(); + char[][] board = { + "OOO".toCharArray(), + "OOO".toCharArray(), + "OOO".toCharArray() + }; + + solution.solve(board); + + for (char[] line : board) { + System.out.println(new String(line)); + } + System.out.println(); + } +} diff --git a/[0130][Surrounded Regions]/src/Solution.java b/[0130][Surrounded Regions]/src/Solution.java new file mode 100644 index 0000000..4f7cf47 --- /dev/null +++ b/[0130][Surrounded Regions]/src/Solution.java @@ -0,0 +1,82 @@ +/** + * Author: + * Date: 2015-06-22 + * Time: 08:51 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
+     * A region is captured by flipping all 'O's into 'X's in that surrounded region.
+     *
+     * For example,
+     * X X X X
+     * X O O X
+     * X X O X
+     * X O X X
+     *
+     * After running your function, the board should be:
+     * X X X X
+     * X X X X
+     * X X X X
+     * X O X X
+     *
+     * Ŀ⣺
+     * һά񣬰'X''O'ԱXΧOX
+     * ˼·
+     * ȶȱķʽҳXΧOΪ$
+     * 
+ * + * @param board + */ + void solve(char[][] board) { + + // У + if (board == null || board.length < 1 || board[0].length < 1) { + return; + } + + // һк + for (int i = 0; i < board[0].length; i++) { + dfs(board, 0, i); + dfs(board, board.length - 1, i); + } + + // һкһ + for (int i = 1; i < board.length - 1; i++) { + dfs(board, i, 0); + dfs(board, i, board[0].length - 1); + } + + + for (int i = 0; i < board.length; ++i) { + for (int j = 0; j < board[i].length; ++j) { + if (board[i][j] == 'O') { + board[i][j] = 'X'; + } + if (board[i][j] == '$') { + board[i][j] = 'O'; + } + } + } + } + + void dfs(char[][] board, int i, int j) { + if (board[i][j] == 'O') { + board[i][j] = '$'; + if (i > 0 && board[i - 1][j] == 'O') { + dfs(board, i - 1, j); + } + if (j < board[i].length - 1 && board[i][j + 1] == 'O') { + dfs(board, i, j + 1); + } + if (i < board.length - 1 && board[i + 1][j] == 'O') { + dfs(board, i + 1, j); + } + if (j > 1 && board[i][j - 1] == 'O') { + dfs(board, i, j - 1); + } + } + } +} diff --git a/[0130][Surrounded Regions]/src/Solution2.java b/[0130][Surrounded Regions]/src/Solution2.java new file mode 100644 index 0000000..3308a10 --- /dev/null +++ b/[0130][Surrounded Regions]/src/Solution2.java @@ -0,0 +1,258 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-22 + * Time: 08:51 + * Declaration: All Rights Reserved !!! + */ +public class Solution2 { + /** + *
+     * Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
+     * A region is captured by flipping all 'O's into 'X's in that surrounded region.
+     *
+     * For example,
+     * X X X X
+     * X O O X
+     * X X O X
+     * X O X X
+     *
+     * After running your function, the board should be:
+     * X X X X
+     * X X X X
+     * X X X X
+     * X O X X
+     *
+     * Ŀ⣺
+     * һά񣬰'X''O'ԱXΧOX
+     * ˼·
+     * ùȱķʽҲԲóȵķʽջ,dzеıΧĵ㣬ʣµľDzΧĵ
+     * 
+ * + * @param board + */ + //////////////////////////////////////////////////////////////////////////////////////////////// + // ùȶȱķʽҳеġΧĵ + //////////////////////////////////////////////////////////////////////////////////////////////// + public void solve(char[][] board) { + // У + if (board == null || board.length < 1 || board[0].length < 1) { + return; + } + + boolean[][] visited = new boolean[board.length][board[0].length]; + // ʱΧһȦԪ + List round = new LinkedList<>(); + // + for (int col = 0; col < board[0].length; col++) { + // УҵOҵδʹ + if (!visited[0][col] && board[0][col] == 'O') { + round.clear(); + round.add(new Coordinate(0, col)); + bfs(board, visited, round); + } + } + + // ײ + for (int col = 0; col < board[0].length; col++) { + // УҵOҵδʹ + if (!visited[board.length - 1][col] && board[board.length - 1][col] == 'O') { + round.clear(); + round.add(new Coordinate(board.length - 1, col)); + bfs(board, visited, round); + } + } + + // + for (int row = 1; row < board.length - 1; row++) { + // УҵOҵδʹ + if (!visited[row][0] && board[row][0] == 'O') { + round.clear(); + round.add(new Coordinate(row, 0)); + bfs(board, visited, round); + } + } + + // ұ + for (int row = 1; row < board.length - 1; row++) { + // УҵOҵδʹ + if (!visited[row][board[0].length - 1] && board[row][board[0].length - 1] == 'O') { + round.clear(); + round.add(new Coordinate(row, board[0].length - 1)); + bfs(board, visited, round); + } + } + + // + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + // δʹֿܣһX㣬ڶO㣬OһDZXΧ + // ʱδʹĵΪXȷ + if (!visited[i][j]) { + board[i][j] = 'X'; + } + } + } + } + + /** + * ȣҲΧĵ + * + * @param board ά + * @param visited ʱ + * @param round ʱΧһȦԪ + */ + public void bfs(char[][] board, boolean[][] visited, List round) { + Coordinate c; + while (round.size() > 0) { + c = round.remove(0); + if (c.x >= 0 && c.x < board.length && c.y >= 0 && c.y < board[0].length && board[c.x][c.y] == 'O' && !visited[c.x][c.y]) { + visited[c.x][c.y] = true; + round.add(new Coordinate(c.x - 1, c.y)); + round.add(new Coordinate(c.x, c.y + 1)); + round.add(new Coordinate(c.x + 1, c.y)); + round.add(new Coordinate(c.x, c.y - 1)); + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + // ùȶȱķʽҳеıΧĵ㣬ұǻᳬʱ + //////////////////////////////////////////////////////////////////////////////////////////////// + public void solve2(char[][] board) { + // У + if (board == null || board.length < 1 || board[0].length < 1) { + return; + } + + boolean[][] visited = new boolean[board.length][board[0].length]; + + // ʱΧһȦԪ + List round = new LinkedList<>(); + // Ԫ + List all = new LinkedList<>(); + + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + if (!visited[i][j] && board[i][j] == 'O') { + // һȦԪ + round.add(new Coordinate(i, j)); + boolean result = bfs(board, visited, round, all); + // һOڣҲڱ߽ + if (result) { + // ñ + for (Coordinate c : all) { + board[c.x][c.y] = 'X'; + } + } + + // Ԫ + round.clear(); + all.clear(); + } + } + } + + } + + /** + * ȱ + * + * @param board ά + * @param visited ʱ + * @param round ʱΧһȦԪ + * @param all Ԫ + * @return trueOڣҲڱ߽ϣXܷtrue + */ + public boolean bfs(char[][] board, boolean[][] visited, List round, List all) { + boolean result = true; + int size = round.size(); + Coordinate c; + while (size > 0) { + size--; + + // ȡԪ + c = round.remove(0); + // ӵ¼Ԫؼ + all.add(c); + // Ѿʹ + visited[c.x][c.y] = true; + // жcǷOڵ + result &= isInner(board, c.x, c.y); + + // cһǷOûзʹӵround + if (isO(board, c.x - 1, c.y) && !visited[c.x - 1][c.y]) { + round.add(new Coordinate(c.x - 1, c.y)); + } + + // cһǷOûзʹӵround + if (isO(board, c.x, c.y + 1) && !visited[c.x][c.y + 1]) { + round.add(new Coordinate(c.x, c.y + 1)); + } + + // cһǷOûзʹӵround + if (isO(board, c.x + 1, c.y) && !visited[c.x + 1][c.y]) { + round.add(new Coordinate(c.x + 1, c.y)); + } + + // cһǷOûзʹӵround + if (isO(board, c.x, c.y - 1) && !visited[c.x][c.y - 1]) { + round.add(new Coordinate(c.x, c.y - 1)); + } + } + + if (round.size() > 0) { + return bfs(board, visited, round, all) && result; + } else { + return result; + } + + } + + /** + * жϵڶάڲҲڱ߽ + * + * @param board ά + * @param x + * @param y + * @return true + */ + public boolean isInner(char[][] board, int x, int y) { + return x > 0 && x < board.length - 1 && y > 0 && y < board[0].length - 1; + } + + /** + * жϵǷO + * + * @param board ά + * @param x + * @param y + * @return true + */ + public boolean isO(char[][] board, int x, int y) { + return x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] == 'O'; + } + + /** + * + */ + public static class Coordinate { + private int x; + private int y; + + public Coordinate() { + } + + public Coordinate(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public String toString() { + return "(" + x + ", " + y + ")"; + } + } +} diff --git a/[0131][Palindrome Partitioning]/[0131][Palindrome Partitioning].iml b/[0131][Palindrome Partitioning]/[0131][Palindrome Partitioning].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0131][Palindrome Partitioning]/[0131][Palindrome Partitioning].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0131][Palindrome Partitioning]/src/Main.java b/[0131][Palindrome Partitioning]/src/Main.java new file mode 100644 index 0000000..d295707 --- /dev/null +++ b/[0131][Palindrome Partitioning]/src/Main.java @@ -0,0 +1,13 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-21 18:36 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + System.out.println(solution.partition("aab")); + } +} diff --git a/[0131][Palindrome Partitioning]/src/Solution.java b/[0131][Palindrome Partitioning]/src/Solution.java new file mode 100644 index 0000000..e3efdab --- /dev/null +++ b/[0131][Palindrome Partitioning]/src/Solution.java @@ -0,0 +1,70 @@ +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-21 18:29 + **/ +public class Solution { + /** + *
+     * Given a string s, partition s such that every substring of the partition is a palindrome.
+     *
+     * Return all possible palindrome partitioning of s.
+     *
+     * Example:
+     *
+     * Input: "aab"
+     * Output:
+     * [
+     *   ["aa","b"],
+     *   ["a","a","b"]
+     * ]
+     *
+     * 解决方案:可以使用回溯法
+     * TODO : 可以构建一个回文表,再进行判定
+     * 
+ * + * @param s + * @return + */ + public List> partition(String s) { + List> result = new LinkedList<>(); + Deque current = new LinkedList<>(); + + partition(s, 0, current, result); + + return result; + } + + private void partition(String s, int index, Deque current, List> result) { + if (index == s.length()) { + result.add(new LinkedList<>(current)); + return; + } + + for (int i = index; i < s.length(); i++) { + String t = s.substring(index, i + 1); + if (isPalindrome(s, index, i)) { + current.addLast(t); + partition(s, i + 1, current, result); + // 还原 + current.removeLast(); + } + } + } + + private boolean isPalindrome(String s, int start, int end) { + while (start < end) { + + if (s.charAt(start) != s.charAt(end)) { + return false; + } else { + start++; + end--; + } + } + return true; + } +} diff --git a/[0132][Palindrome Partitioning II]/[0132][Palindrome Partitioning II].iml b/[0132][Palindrome Partitioning II]/[0132][Palindrome Partitioning II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0132][Palindrome Partitioning II]/[0132][Palindrome Partitioning II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0132][Palindrome Partitioning II]/src/Solution.java b/[0132][Palindrome Partitioning II]/src/Solution.java new file mode 100644 index 0000000..6eddbef --- /dev/null +++ b/[0132][Palindrome Partitioning II]/src/Solution.java @@ -0,0 +1,56 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-24 19:22 + **/ +public class Solution { + /** + *
+     * Given a string s, partition s such that every substring of the partition is a palindrome.
+     *
+     * Return the minimum cuts needed for a palindrome partitioning of s.
+     *
+     * Example:
+     *
+     * Input: "aab"
+     * Output: 1
+     * Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
+     *
+     * 分析
+     * 定义状态f(i,j) 表示区间[i,j] 之间最小的cut 数,则状态转移方程为
+     * f(i; j) = min {f(i; k) + f(k + 1; j)} ; i  k  j; 0  i  j < n
+     * 这是一个二维函数,实际写代码比较麻烦。
+     * 所以要转换成一维DP。如果每次,从i 往右扫描,每找到一个回文就算一次DP 的话,就可以
+     * 转换为f(i)= 区间[i, n-1] 之间最小的cut 数,n 为字符串长度,则状态转移方程为
+     * f(i) = min {f(j + 1) + 1} ; i <= j < n TODO 怎么理解?
+     * 一个问题出现了,就是如何判断[i,j] 是否是回文?每次都从i 到j 比较一遍?太浪费了,这
+     * 里也是一个DP 问题。
+     * 定义状态P[i][j] = true if [i,j] 为回文,那么
+     * P[i][j] = str[i] == str[j] && P[i+1][j-1]
+     *
+     * https://www.cnblogs.com/grandyang/p/4271456.html
+     * 
+ * + * @param s + * @return + */ + public int minCut(String s) { + final int n = s.length(); + + int[] dp = new int[n]; + boolean[][] p = new boolean[n][]; + + for (int i = 0; i < n; ++i) { + dp[i] = i; + p[i] = new boolean[n]; + + for (int j = 0; j <= i; ++j) { + if (s.charAt(i) == s.charAt(j) && (i - j < 2 || p[j + 1][i - 1])) { + p[j][i] = true; + dp[i] = (j == 0) ? 0 : Math.min(dp[i], dp[j - 1] + 1); + } + } + } + + return dp[n - 1]; + } +} diff --git a/[0132][Palindrome Partitioning II]/src/Solution2.java b/[0132][Palindrome Partitioning II]/src/Solution2.java new file mode 100644 index 0000000..c0611da --- /dev/null +++ b/[0132][Palindrome Partitioning II]/src/Solution2.java @@ -0,0 +1,62 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-24 19:22 + **/ +public class Solution2 { + /** + *
+     * Given a string s, partition s such that every substring of the partition is a palindrome.
+     *
+     * Return the minimum cuts needed for a palindrome partitioning of s.
+     *
+     * Example:
+     *
+     * Input: "aab"
+     * Output: 1
+     * Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
+     *
+     * 分析
+     * 定义状态f(i,j) 表示区间[i,j] 之间最小的cut 数,则状态转移方程为
+     * f(i; j) = min {f(i; k) + f(k + 1; j)} ; i  k  j; 0  i  j < n
+     * 这是一个二维函数,实际写代码比较麻烦。
+     * 所以要转换成一维DP。如果每次,从i 往右扫描,每找到一个回文就算一次DP 的话,就可以
+     * 转换为f(i)= 区间[i, n-1] 之间最小的cut 数,n 为字符串长度,则状态转移方程为
+     * f(i) = min {f(j + 1) + 1} ; i <= j < n TODO 怎么理解?
+     * 一个问题出现了,就是如何判断[i,j] 是否是回文?每次都从i 到j 比较一遍?太浪费了,这
+     * 里也是一个DP 问题。
+     * 定义状态P[i][j] = true if [i,j] 为回文,那么
+     * P[i][j] = str[i] == str[j] && P[i+1][j-1]
+     *
+     * https://www.cnblogs.com/grandyang/p/4271456.html
+     * 
+ * + * @param s + * @return + */ + public int minCut(String s) { + final int n = s.length(); + + int[] f = new int[n + 1]; + boolean[][] p = new boolean[n][]; + //the worst case is cutting by each char + // 最后一个f[n]=-1 + for (int i = 0; i <= n; i++) { + // [n-1, n-2, ..., 1, 0, -1],为了后面做切分 + f[i] = n - 1 - i; + } + for (int i = n - 1; i >= 0; i--) { + p[i] = new boolean[n]; + + for (int j = i; j < n; j++) { + // j - i < 2 : 表示j在i位置或者j在i之后一个位置 + // p[i + 1][j - 1] : [i+1, j-1]是回文 + if (s.charAt(i) == s.charAt(j) && (j - i < 2 || p[i + 1][j - 1])) { + p[i][j] = true; + f[i] = Math.min(f[i], f[j + 1] + 1); + } + } + } + + return f[0]; + } +} diff --git a/[0134][Gas Station]/[0134][Gas Station].iml b/[0134][Gas Station]/[0134][Gas Station].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0134][Gas Station]/[0134][Gas Station].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0134][Gas Station]/[0134][GasStation].iml b/[0134][Gas Station]/[0134][GasStation].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0134][Gas Station]/[0134][GasStation].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0134][Gas Station]/src/Main.java b/[0134][Gas Station]/src/Main.java new file mode 100644 index 0000000..250a219 --- /dev/null +++ b/[0134][Gas Station]/src/Main.java @@ -0,0 +1,17 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-16 11:06 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] gas = {1, 2, 3, 4, 5}; + int[] cost = {3, 4, 5, 1, 2}; + int pos = solution.canCompleteCircuit(gas, cost); + Assert.assertEquals(3, pos); + } +} diff --git a/[0134][Gas Station]/src/Solution.java b/[0134][Gas Station]/src/Solution.java new file mode 100644 index 0000000..213926c --- /dev/null +++ b/[0134][Gas Station]/src/Solution.java @@ -0,0 +1,146 @@ +/** + * Author: + * Date: 2015-06-21 + * Time: 10:11 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * There are N gas stations along a circular route, where the amount
+     * of gas at station i is gas[i].
+     *
+     * You have a car with an unlimited gas tank and it costs cost[i] of gas
+     * to travel from station i to its next station (i+1). You begin the journey
+     * with an empty tank at one of the gas stations.
+     *
+     * Return the starting gas station's index if you can travel around the
+     * circuit once, otherwise return -1.
+     *
+     * Note:
+     *   - The solution is guaranteed to be unique.
+     *
+     * Ŀ⣺
+     * ػ·Nվڳվigas[i]
+     * гޣӼվiһվվi+1Ҫcost[i]塣
+     * 㿪ʼóʱǿյġصʼվָѡһ㿪ʼΣ
+     * ΧһΣͷؿʼļվ򷵻-1
+     *
+     * ע⣺
+     *   - 𰸱֤Ψһ
+     *
+     * ˼·
+     * վ i վ k ֮ǰȻܱ֤û׶k 󣬼׶ˡ
+     * ô˵ diff[i] + diff[i+1] + ... + diff[k] < 0diff[k]⣬diff[i]
+     * ʼۼӶ >= 0ġҲ˵diff[i] Ҳ >= 0ģʱǻбҪվ i + 1
+     * ϸһ֪ҪǴվ i+1վkûվkͼ
+     * ˣΪټվ i ͡
+     *
+     * ˣǷֵk վ׶i  k Щվ㶼Ϊˣ϶
+     * ֻҪk+1վ㳢Լɣ˽ⷨʱ临ӶȴO(n2) O(2n)֮
+     * O(2n)Ϊk+1վΪʼվȦk֤k+1Ƿ㡣
+     *
+     * ȵȣҪ
+     * ģһ¹̣
+     * a. ʼվ0ʼվ賵վpˣ
+     *      sum1 = diff[0] +diff[1] + ... + diff[p]֪sum1 < 0
+     *
+     * b. ǽp+1Ϊʼվqվֿˣ
+     *      sum2 = diff[p+1] +diff[p+2] + ... + diff[q]֪sum2 < 0
+     *
+     * c. q+1Ϊʼվһֱδѭĩվû׶
+     *      sum3 = diff[q+1] +diff[q+2] + ... + diff[size-1]֪sum3 >= 0
+     *
+     * Ҫ֪ܷ񿪻 q վʵsum3 Ļϣμ diff[0]  diff[q]
+     * sum3ǷС0֮ǰѾ֪ diff[0]  diff[p-1] ·
+     * һֱַǸֻҪsum3 + sum1Ƿ <0֪ܲܿ p+1վˡ
+     * ܴp+1վֻҪsum3 + sum1 + sum2 Ƿ < 0֪ܲܿqվˡ
+     *
+     * Ϊ sum1, sum2  < 0 sum3 + sum1 + sum2 >=0 ô
+     * sum3 + sum1 Ȼ >= 0Ҳ˵ֻҪsum3 + sum1 + sum2 >=0Ȼܿqվ
+     * sum3 + sum1 + sum2 ʵ diffܺ TotalԪѾˡ
+     *  Total ܷ >= 0Ƿվ ֱҪ
+     *
+     * ʱ临ӶȽһO(2n) O(n)
+     * 
+ * + * @param gas + * @param cost + * @return + */ + public int canCompleteCircuit(int[] gas, int[] cost) { + // + if (gas == null || cost == null || gas.length == 0 || gas.length != cost.length) { + return -1; + } + + // ¼ʵʼ + int start = 0; + // ӵĵֵܲ + int total = 0; + // startλÿʼӵĵֵܲ + int sum = 0; + + for (int i = 0; i < gas.length; i++) { + total += (gas[i] - cost[i]); + + // û + if (sum < 0) { + // е + sum = gas[i] - cost[i]; + // ¼µλ + start = i; + } else { + // лͣе + sum += (gas[i] - cost[i]); + } + } + + return total >= 0 ? start : -1; + } + + + /** + * ķᳬʱO(N^2)ʱ临Ӷ + */ + public int canCompleteCircuit2(int[] gas, int[] cost) { + // + if (gas == null || cost == null || gas.length == 0 || gas.length != cost.length) { + return -1; + } + + // ʣµ壬ʼʱΪ0 + int leftGas = 0; + // ʼվ + int start = 0; + // վ + int end = 1; + + // δһ + while (start < gas.length) { + + // һվ + leftGas = gas[start] - cost[start]; + + // ߵһվ + if (leftGas > 0) { + // ¼һվ + end = (start + 1) % gas.length; + + // һֱԵһվͳв + while (start != end && (leftGas += (gas[end] - cost[end])) >= 0) { + end = (end + 1) % gas.length; + } + + // ˵Ѿһ + if (start == end) { + return start; + } + } + + start++; + } + + return -1; + } +} diff --git a/[0135][Candy]/[0135][Candy].iml b/[0135][Candy]/[0135][Candy].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0135][Candy]/[0135][Candy].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0135][Candy]/src/Main.java b/[0135][Candy]/src/Main.java new file mode 100644 index 0000000..54ea1af --- /dev/null +++ b/[0135][Candy]/src/Main.java @@ -0,0 +1,14 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-16 11:37 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(5, solution.candy(new int[]{1, 0, 2})); + } +} diff --git a/[0135][Candy]/src/Solution.java b/[0135][Candy]/src/Solution.java new file mode 100644 index 0000000..ea602e0 --- /dev/null +++ b/[0135][Candy]/src/Solution.java @@ -0,0 +1,77 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-16 11:27 + **/ +public class Solution { + /** + *
+     * There are N children standing in a line. Each child is assigned a rating value.
+     *
+     * You are giving candies to these children subjected to the following requirements:
+     *
+     * 1. Each child must have at least one candy.
+     * 2. Children with a higher rating get more candies than their neighbors.
+     * What is the minimum candies you must give?
+     *
+     * Example 1:
+     *
+     * Input: [1,0,2]
+     * Output: 5
+     * Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
+     * Example 2:
+     *
+     * Input: [1,2,2]
+     * Output: 4
+     * Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
+     *              The third child gets 1 candy because it satisfies the above two conditions.
+     * 
+ * + * @param ratings + * @return + */ + public int candy(int[] ratings) { + if (ratings == null || ratings.length < 1) { + return 0; + } + + + int[] increment = new int[ratings.length]; + // 左右各扫描一遍 + for (int i = 1, inc = 1; i < ratings.length; i++) { + // 右边的孩子分数比左边的孩子分数高 + if (ratings[i] > ratings[i - 1]) { + // 右边的孩子比左边的孩子多发至少一个糖果 + increment[i] = increment[i - 1] + 1; + } +// // 右边的孩子分数与左边的孩子分数相等,相等可以少发 +// else if (ratings[i] == ratings[i - 1]) { +// // 右边和左边的孩子增同样多颗糖 +// increment[i] = increment[i - 1]; +// } + // 可以不处理 +// else{ +// increment[i] = 0; +// } + } + + // 从右到左进行处理 + for (int i = ratings.length - 2, inc = 1; i >= 0; i--) { + // 左边的孩子分数比右边高 + if (ratings[i] > ratings[i + 1]) { + increment[i] = Math.max(increment[i], increment[i + 1] + 1); + } + // +// else if (ratings[i] == ratings[i + 1]) { +// // 总是成立了 +// increment[i] = increment[i - 1]; +// } + // ratings[i] < ratings[i + 1] 不需要操作 + } + + int sum = ratings.length; + for (int n : increment) { + sum += n; + } + return sum; + } +} diff --git a/[0136][Single Number]/[0136][Single Number].iml b/[0136][Single Number]/[0136][Single Number].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0136][Single Number]/[0136][Single Number].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0136][Single Number]/src/Solution.java b/[0136][Single Number]/src/Solution.java new file mode 100644 index 0000000..b32b8a7 --- /dev/null +++ b/[0136][Single Number]/src/Solution.java @@ -0,0 +1,35 @@ +/** + * Author: + * Date: 2015-06-18 + * Time: 10:29 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + * Given an array of integers, every element appears twice except for one. + * Find that single one. + *

+ * Note: Your algorithm should have a linear runtime complexity. + * Could you implement it without using extra memory? + *

+ * һ飬ÿԪض2γеһҳֻһε + * ע⣺㷨ʱ临ӶȣԲʹöռʵ + *

+ * ˼·ʹ + * + * @param nums + * @return + */ + public int singleNumber(int[] nums) { + + if (nums == null || nums.length < 1) { + throw new IllegalArgumentException("nums should contain at least one element"); + } + + + for (int i = 1; i < nums.length; i++) { + nums[0] ^= nums[i]; + } + return nums[0]; + } +} diff --git a/[0137][Single Number II]/[0137][Single Number II].iml b/[0137][Single Number II]/[0137][Single Number II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0137][Single Number II]/[0137][Single Number II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221/src/Solution.java" b/[0137][Single Number II]/src/Solution.java similarity index 100% rename from "\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221/src/Solution.java" rename to [0137][Single Number II]/src/Solution.java diff --git a/[0138][Copy List With Random Pointer]/[0138][Copy List With Random Pointer].iml b/[0138][Copy List With Random Pointer]/[0138][Copy List With Random Pointer].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0138][Copy List With Random Pointer]/[0138][Copy List With Random Pointer].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0138][Copy List With Random Pointer]/src/Main.java b/[0138][Copy List With Random Pointer]/src/Main.java new file mode 100644 index 0000000..92f5099 --- /dev/null +++ b/[0138][Copy List With Random Pointer]/src/Main.java @@ -0,0 +1,32 @@ +/** + * Author: ������ + * Date: 2015-06-24 + * Time: 09:18 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + RandomListNode n1 = new RandomListNode(1); + RandomListNode n2 = new RandomListNode(2); + RandomListNode n3 = new RandomListNode(3); + RandomListNode n4 = new RandomListNode(4); + n1.next = n2; + n2.next = n3; + n3.next = n4; + + Solution solution = new Solution(); + RandomListNode copy = solution.copyRandomList(n1); + + print(copy); + + } + + public static void print(RandomListNode head) { + while (head != null) { + System.out.print(head.label + "->"); + head = head.next; + } + + System.out.println("null"); + } +} diff --git "a/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/RandomListNode.java" b/[0138][Copy List With Random Pointer]/src/RandomListNode.java similarity index 100% rename from "\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/RandomListNode.java" rename to [0138][Copy List With Random Pointer]/src/RandomListNode.java diff --git a/[0138][Copy List With Random Pointer]/src/Solution.java b/[0138][Copy List With Random Pointer]/src/Solution.java new file mode 100644 index 0000000..f392526 --- /dev/null +++ b/[0138][Copy List With Random Pointer]/src/Solution.java @@ -0,0 +1,108 @@ +/** + * Author: + * Date: 2015-06-24 + * Time: 08:48 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *

+     * A linked list is given such that each node contains an additional random
+     * pointer which could point to any node in the list or null.
+     *
+     * Return a deep copy of the list.
+     *
+     * Ŀ⣺
+     * һһָnullĽָ룬
+     *
+     * ˼·
+     * һƽ㣬ƵĽڴƵĽȻһ
+     * ڶָ
+     * ָƺ
+     * 
+ * + * @param head + * @return + */ + public RandomListNode copyRandomList(RandomListNode head) { + if (head == null) { + return null; + } + + copyNode(head); + linkRandomPointer(head); + + return splitList(head); + } + + /** + * ƽ㣬ƵĽڴƵĽȻһ + * + * @param head ͷ + */ + public void copyNode(RandomListNode head) { + // ¼ǰҪƵ + RandomListNode node = head; + while (node != null) { + // һµĽ + RandomListNode copyNode = new RandomListNode(node.label); + // 㴮ӵƵĽ󣬲Ȼɵ + copyNode.next = node.next; + node.next = copyNode; + node = copyNode.next; + } + } + + /** + * ָ + * + * @param head ͷ + */ + public void linkRandomPointer(RandomListNode head) { + // ¼ǰҪƵ + RandomListNode node = head; + while (node != null) { + // ָָijĽ + if (node.random != null) { + // nodeƽָ + node.next.random = node.random.next; + } + + // ָһƵĽ + node = node.next.next; + } + } + + /** + * ֣ԭԭװ + * + * @param head ͷ + * @return ͷ + */ + public RandomListNode splitList(RandomListNode head) { + // ͷ + RandomListNode copyHead = head.next; + // ǰıƵĽ + RandomListNode node = head; + // ǰƵĽ + RandomListNode copy; + + while (node != null) { + // ָƽ + copy = node.next; + + // node.nextָһƵĽ + node.next = copy.next; + + // һƵĽ㲻Ϊnull + if (node.next != null) { + // copy.nextָһƵĽ + copy.next = node.next.next; + } + + // nodeָһҪıƽ + node = node.next; + } + return copyHead; + } +} diff --git a/[0139][Word Break]/[0139][Word Break].iml b/[0139][Word Break]/[0139][Word Break].iml new file mode 100644 index 0000000..73f33e3 --- /dev/null +++ b/[0139][Word Break]/[0139][Word Break].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0139][Word Break]/src/Main.java b/[0139][Word Break]/src/Main.java new file mode 100644 index 0000000..adb7df9 --- /dev/null +++ b/[0139][Word Break]/src/Main.java @@ -0,0 +1,59 @@ +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Author: + * Date: 2015-06-21 + * Time: 08:48 + * Declaration: All Rights Reserved !!! + */ +public class Main { + + + @Test + public void test01() { + Solution solution = new Solution(); + Set set = new HashSet<>(); + set.add("leet"); + set.add("code"); + System.out.println(solution.wordBreak("leetcode", set)); + } + + @Test + public void test02() { + Solution solution = new Solution(); + Set set = new HashSet<>(); + System.out.println(solution.wordBreak("a", set)); + } + + @Test + public void test03() { + Solution solution = new Solution(); + Set set = new HashSet<>(); + set.add("b"); + set.add("a"); + set.add("aa"); + set.add("aaa"); + set.add("aaaa"); + set.add("aaaaa"); + set.add("aaaaaa"); + set.add("aaaaaaa"); + set.add("aaaaaaaa"); + set.add("aaaaaaaaa"); + set.add("aaaaaaaaaa"); + System.out.println(solution.wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaab", set)); + } + + @Test + public void test04() { + Solution solution = new Solution(); + Set set = new HashSet<>(Arrays.asList("cats", "dog", "sand", "and", "cat")); + + System.out.println(solution.wordBreak("catsandog", set)); + } +} diff --git "a/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/src/Solution.java" b/[0139][Word Break]/src/Solution.java similarity index 100% rename from "\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/src/Solution.java" rename to [0139][Word Break]/src/Solution.java diff --git a/[0141][Linked List Cycle]/[0141][Linked List Cycle].iml b/[0141][Linked List Cycle]/[0141][Linked List Cycle].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0141][Linked List Cycle]/[0141][Linked List Cycle].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0141][Linked List Cycle]/src/ListNode.java b/[0141][Linked List Cycle]/src/ListNode.java new file mode 100644 index 0000000..8892796 --- /dev/null +++ b/[0141][Linked List Cycle]/src/ListNode.java @@ -0,0 +1,15 @@ +/** + * Author: ������ + * Date: 2015-08-21 + * Time: 19:17 + * Declaration: All Rights Reserved !!! + */ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } +} diff --git a/[0141][Linked List Cycle]/src/Solution.java b/[0141][Linked List Cycle]/src/Solution.java new file mode 100644 index 0000000..1bac274 --- /dev/null +++ b/[0141][Linked List Cycle]/src/Solution.java @@ -0,0 +1,57 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:16 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * ԭ
+     * Given a linked list, determine if it has a cycle in it.
+     * Follow up:
+     * Can you solve it without using extra space?
+     *
+     * Ŀ
+     * һжǷл
+     *
+     * ˼·
+     * ָ(fast, slow)ʼֵָͷslowÿǰһfastÿǰڻ
+     * fastضȽ뻷slow뻷ָض
+     * 
+ * + * @param head + * @return + */ + public boolean hasCycle(ListNode head) { + + ListNode fast = head; + ListNode slow = head; + + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (slow == fast) { + return true; + } + } + + return false; + } + + public boolean hasCycle2(ListNode head) { + + ListNode fast = head; + ListNode slow = head; + + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (slow == fast) { + break; + } + } + + return !(fast == null || fast.next == null); + } +} diff --git a/[0142][Linked List Cycle II]/[0142][Linked List Cycle II].iml b/[0142][Linked List Cycle II]/[0142][Linked List Cycle II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0142][Linked List Cycle II]/[0142][Linked List Cycle II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0142][Linked List Cycle II]/[0142][LinkedListCycleII].iml b/[0142][Linked List Cycle II]/[0142][LinkedListCycleII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0142][Linked List Cycle II]/[0142][LinkedListCycleII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0142][Linked List Cycle II]/src/ListNode.java b/[0142][Linked List Cycle II]/src/ListNode.java new file mode 100644 index 0000000..c9da456 --- /dev/null +++ b/[0142][Linked List Cycle II]/src/ListNode.java @@ -0,0 +1,15 @@ +/** + * Author: ������ + * Date: 2015-08-21 + * Time: 19:19 + * Declaration: All Rights Reserved !!! + */ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } +} diff --git "a/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/src/Solution.java" b/[0142][Linked List Cycle II]/src/Solution.java similarity index 100% rename from "\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/src/Solution.java" rename to [0142][Linked List Cycle II]/src/Solution.java diff --git a/[0143][Reorder List]/[0143][CopyListWithRandomPointer].iml b/[0143][Reorder List]/[0143][CopyListWithRandomPointer].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0143][Reorder List]/[0143][CopyListWithRandomPointer].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0143][Reorder List]/[0143][Reorder List].iml b/[0143][Reorder List]/[0143][Reorder List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0143][Reorder List]/[0143][Reorder List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0143][Reorder List]/src/ListNode.java b/[0143][Reorder List]/src/ListNode.java new file mode 100644 index 0000000..dc97875 --- /dev/null +++ b/[0143][Reorder List]/src/ListNode.java @@ -0,0 +1,14 @@ +/** + * Author: 王俊超 + * Date: 2015-08-21 + * Time: 19:22 + * Declaration: All Rights Reserved !!! + */ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } +} diff --git a/[0143][Reorder List]/src/Solution.java b/[0143][Reorder List]/src/Solution.java new file mode 100644 index 0000000..c4f61a9 --- /dev/null +++ b/[0143][Reorder List]/src/Solution.java @@ -0,0 +1,79 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:21 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a singly linked list L: L0L1Ln-1Ln,
+     * reorder it to: L0LnL1Ln-1L2Ln-2
+     *
+     * You may not modify the values in the list's nodes, only nodes itself may be changed.
+     *
+     * Example 1:
+     *
+     * Given 1->2->3->4, reorder it to 1->4->2->3.
+     * Example 2:
+     *
+     * Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
+     *
+     * ˼·
+     * 1ҵм
+     * 2㣬ͽм֮в֣
+     *
+     * 
+ * + * @param head + */ + public void reorderList(ListNode head) { + if (head == null || head.next == null) { + return; + } + + ListNode root = new ListNode(-1); + root.next = head; + ListNode fast = head; + // мǰ + ListNode slow = root; + + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + + // ˵żڵ + if (fast == null) { + root.next = slow.next; + slow.next = null; + + } else { // + slow = slow.next; + root.next = slow.next; + slow.next = null; + } + + // һҪͷ巨 + fast = root.next; + ListNode tmp; + // 벿 + while (fast.next != null) { + tmp = fast.next; + fast.next = tmp.next; + tmp.next = root.next; + root.next = tmp; + } + + slow = head; + fast = root.next; + + while (fast != null) { + tmp = fast.next; + fast.next = slow.next; + slow.next = fast; + slow = slow.next.next; + fast = tmp; + } + } +} diff --git a/[0144][Binary Tree Preorder Traversal]/[0144][Binary Tree Preorder Traversal].iml b/[0144][Binary Tree Preorder Traversal]/[0144][Binary Tree Preorder Traversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0144][Binary Tree Preorder Traversal]/[0144][Binary Tree Preorder Traversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221/src/Solution.java" b/[0144][Binary Tree Preorder Traversal]/src/Solution.java similarity index 100% rename from "\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221/src/Solution.java" rename to [0144][Binary Tree Preorder Traversal]/src/Solution.java diff --git "a/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221/src/TreeNode.java" b/[0144][Binary Tree Preorder Traversal]/src/TreeNode.java similarity index 100% rename from "\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221/src/TreeNode.java" rename to [0144][Binary Tree Preorder Traversal]/src/TreeNode.java diff --git a/[0145][Binary Tree Postorder Traversal]/[0145][Binary Tree Postorder Traversal].iml b/[0145][Binary Tree Postorder Traversal]/[0145][Binary Tree Postorder Traversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0145][Binary Tree Postorder Traversal]/[0145][Binary Tree Postorder Traversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0145][Binary Tree Postorder Traversal]/[0145][BinaryTreePostorderTraversal].iml b/[0145][Binary Tree Postorder Traversal]/[0145][BinaryTreePostorderTraversal].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0145][Binary Tree Postorder Traversal]/[0145][BinaryTreePostorderTraversal].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0145][Binary Tree Postorder Traversal]/src/Solution.java b/[0145][Binary Tree Postorder Traversal]/src/Solution.java new file mode 100644 index 0000000..2adec07 --- /dev/null +++ b/[0145][Binary Tree Postorder Traversal]/src/Solution.java @@ -0,0 +1,93 @@ +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: + * Date: 2015-06-22 + * Time: 14:54 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Given a binary tree, return the postorder traversal of its nodes' values.
+     *
+     * For example:
+     * Given binary tree {1,#,2,3},
+     *      1
+     *       \
+     *        2
+     *       /
+     *      3
+     * return [3,2,1].
+     *
+     * Note: Recursive solution is trivial, could you do it iteratively?
+     *
+     * Ŀ⣺
+     * һŶĺĽֵ
+     *
+     * ע⣺
+     *   - ݹⷨף볢ʽ
+     *
+     * ˼·
+     * ǵݹ
+     * ݺ˳ȷٷʸڵ㣬ÿ˵
+     * ְͬķ˳бķǵݹʵ˵ҪһЩҪ֤
+     * ʺܷʣ˼·£
+     *
+     * һڵP
+     * 1ȽڵPջ
+     * 2PӺҺӣPӻҺӣҺѾ
+     *      ֱڵPջջڵPΪһĽڵ㣬ٽʱ
+     *      ջΪǰڵ㣻
+     * 32еPҺӺջǰڵΪջ㣬
+     *      ֮ظ2
+     * 4ֱջգ
+     * 
+ * + * @param root + * @return + */ + public List postorderTraversal(TreeNode root) { + List list = new LinkedList<>(); + + if (root != null) { + // ˫˶Уջʹ + Deque deque = new LinkedList<>(); + // ָǰһĽ + TreeNode prev = null; + // ָǰĽ + TreeNode curr; + // ջ + deque.addLast(root); + // ջǿ + while (!deque.isEmpty()) { + // ȡջԪأɾ + curr = deque.getLast(); + if ((curr.left == null && curr.right == null) // ǰԪ + // prev != null && curr.left == prevǰֻѾ + // prev != null && curr.right == prevǰѾ + || (prev != null && (curr.left == prev || curr.right == prev))) { + // ɾջԪ + curr = deque.removeLast(); + // ֵջ + list.add(curr.val); + // һĽ + prev = curr; + } else { + + // δ꣬ǿջ + if (curr.right != null) { + deque.addLast(curr.right); + } + if (curr.left != null) { + deque.addLast(curr.left); + } + } + } + } + + return list; + } +} diff --git "a/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/src/TreeNode.java" b/[0145][Binary Tree Postorder Traversal]/src/TreeNode.java similarity index 100% rename from "\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/src/TreeNode.java" rename to [0145][Binary Tree Postorder Traversal]/src/TreeNode.java diff --git a/[0146][LRU Cache]/[0146][LRU Cache].iml b/[0146][LRU Cache]/[0146][LRU Cache].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0146][LRU Cache]/[0146][LRU Cache].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0146][LRU Cache]/src/LRUCache.java b/[0146][LRU Cache]/src/LRUCache.java new file mode 100644 index 0000000..3d26ca7 --- /dev/null +++ b/[0146][LRU Cache]/src/LRUCache.java @@ -0,0 +1,69 @@ +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 17:34 + **/ +public class LRUCache extends LinkedHashMap { + /** + *
+     * Design and implement a data structure for Least Recently Used (LRU) cache.
+     * It should support the following operations: get and put.
+     *
+     * get(key) - Get the value (will always be positive) of the key if the key exists
+     * in the cache, otherwise return -1.
+     * put(key, value) - Set or insert the value if the key is not already present. When
+     * the cache reached its capacity, it should invalidate the least recently used item
+     * before inserting a new item.
+     *
+     * The cache is initialized with a positive capacity.
+     *
+     * Follow up:
+     * Could you do both operations in O(1) time complexity?
+     *
+     * Example:
+     *
+     * LRUCache cache = new LRUCache( 2  );// capacity
+     *
+     * cache.put(1,1);
+     * cache.put(2,2);
+     * cache.get(1);       // returns 1
+     * cache.put(3,3);    // evicts key 2
+     * cache.get(2);       // returns -1 (not found)
+     * cache.put(4,4);    // evicts key 1
+     * cache.get(1);       // returns -1 (not found)
+     * cache.get(3);       // returns 3
+     * cache.get(4);       // returns 4
+     * 
+ * + * @param capacity + */ + + private int capacity; + + + public LRUCache(int capacity) { + super(capacity, 0.75F, true); + this.capacity = capacity; + } + + public int get(int key) { + Integer value = super.get(key); + if (value == null) { + return -1; + } else { + return value; + } + } + + public void put(int key, int value) { + super.put(key, value); + } + + + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > capacity; + } +} diff --git a/[0146][LRU Cache]/src/Main.java b/[0146][LRU Cache]/src/Main.java new file mode 100644 index 0000000..61644cc --- /dev/null +++ b/[0146][LRU Cache]/src/Main.java @@ -0,0 +1,26 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-17 17:41 + **/ +public class Main { + + @Test + public void test1() { + LRUCache cache = new LRUCache(2); + + cache.put(1, 1); + cache.put(2, 2); + cache.get(1); // returns 1 + cache.put(3, 3); // evicts key 2 + cache.get(2); // returns -1 (not found) + Assert.assertEquals(-1, cache.get(2)); + cache.put(4, 4); // evicts key 1 + cache.get(1); // returns -1 (not found) + Assert.assertEquals(-1, cache.get(1)); + cache.get(3); // returns 3 + cache.get(4); // returns 4 + } +} diff --git a/[0147][Insertion Sort List]/[0147][Insertion Sort List].iml b/[0147][Insertion Sort List]/[0147][Insertion Sort List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0147][Insertion Sort List]/[0147][Insertion Sort List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0147][Insertion Sort List]/[0147][InsertionSortList].iml b/[0147][Insertion Sort List]/[0147][InsertionSortList].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0147][Insertion Sort List]/[0147][InsertionSortList].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221/src/ListNode.java" b/[0147][Insertion Sort List]/src/ListNode.java similarity index 100% rename from "\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221/src/ListNode.java" rename to [0147][Insertion Sort List]/src/ListNode.java diff --git "a/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221/src/Solution.java" b/[0147][Insertion Sort List]/src/Solution.java similarity index 100% rename from "\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221/src/Solution.java" rename to [0147][Insertion Sort List]/src/Solution.java diff --git a/[0148][Sort List]/[0148][Sort List].iml b/[0148][Sort List]/[0148][Sort List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0148][Sort List]/[0148][Sort List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0148][Sort List]/src/ListNode.java b/[0148][Sort List]/src/ListNode.java new file mode 100644 index 0000000..0c7f1c1 --- /dev/null +++ b/[0148][Sort List]/src/ListNode.java @@ -0,0 +1,14 @@ +/** + * Author: + * Date: 2015-08-21 + * Time: 19:24 + * Declaration: All Rights Reserved !!! + */ +public class ListNode { + int val; + ListNode next; + + ListNode(int v) { + val = v; + } +} diff --git a/[0148][Sort List]/src/Solution.java b/[0148][Sort List]/src/Solution.java new file mode 100644 index 0000000..7cbd141 --- /dev/null +++ b/[0148][Sort List]/src/Solution.java @@ -0,0 +1,84 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-19 14:28 + **/ +public class Solution { + /** + *
+     * Sort a linked list in O(n log n) time using constant space complexity.
+     *
+     * Example 1:
+     *
+     * Input: 4->2->1->3
+     * Output: 1->2->3->4
+     * Example 2:
+     *
+     * Input: -1->5->3->4->0
+     * Output: -1->0->3->4->5
+     *
+     * 使用链表的归并排序可以解决
+     * 
+ * + * @param head + * @return + */ + public ListNode sortList(ListNode head) { + + if (head == null || head.next == null) { + return head; + } + return mergeSort(head); + } + + private ListNode mergeSort(ListNode head) { + + if (head == null || head.next == null) { + return head; + } + + ListNode p = head; + ListNode q = head; + // 记录前驱 + ListNode r = null; + + // 将链表分害割成两半 + while (p != null && p.next != null) { + p = p.next.next; + r = q; + q = q.next; + } + + r.next = null; + + // 两个链接分别进行排序 + ListNode h1 = mergeSort(head); + ListNode h2 = mergeSort(q); + + return merge(h1, h2); + } + + private ListNode merge(ListNode l1, ListNode l2) { + + ListNode head = new ListNode(0); + ListNode p = head; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + p.next = l1; + l1 = l1.next; + } else { + p.next = l2; + l2 = l2.next; + } + + p = p.next; + } + + if (l1 != null) { + p.next = l1; + } else { + p.next = l2; + } + + return head.next; + } +} diff --git a/[0150][Evaluate Reverse Polish Notation]/[0150][Evaluate Reverse Polish Notation].iml b/[0150][Evaluate Reverse Polish Notation]/[0150][Evaluate Reverse Polish Notation].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0150][Evaluate Reverse Polish Notation]/[0150][Evaluate Reverse Polish Notation].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0150][Evaluate Reverse Polish Notation]/src/Main.java b/[0150][Evaluate Reverse Polish Notation]/src/Main.java new file mode 100644 index 0000000..ce7f89f --- /dev/null +++ b/[0150][Evaluate Reverse Polish Notation]/src/Main.java @@ -0,0 +1,12 @@ +/** + * Author: ������ + * Date: 2015-06-20 + * Time: 07:14 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.evalRPN(new String[]{"0", "3", "/"})); + } +} diff --git a/[0150][Evaluate Reverse Polish Notation]/src/Solution.java b/[0150][Evaluate Reverse Polish Notation]/src/Solution.java new file mode 100644 index 0000000..17993a7 --- /dev/null +++ b/[0150][Evaluate Reverse Polish Notation]/src/Solution.java @@ -0,0 +1,74 @@ +import java.util.Stack; + +/** + * Author: + * Date: 2015-06-20 + * Time: 06:58 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Evaluate the value of an arithmetic expression in Reverse Polish Notation.
+     * Valid operators are +, -, *, /. Each operand may be an integer or another expression.
+     *
+     * Some examples:
+     * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
+     * ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
+     *
+     * Ŀ⣺
+     * 沨ʽֵЧǣ+-*/ÿҪôһҪôһʽ
+     *
+     * ˼·
+     * ʹջв
+     * 
+ * + * @param tokens + * @return + */ + public int evalRPN(String[] tokens) { + // У + if (tokens == null || tokens.length < 1) { + throw new IllegalArgumentException(); + } + + int op1; + int op2; + // ջ + Stack stack = new Stack<>(); + + for (String token : tokens) { + // ˵ҪȡջԪؽ + if ("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token)) { + // ȡջԪ + op2 = stack.pop(); + op1 = stack.pop(); + + // + switch (token.charAt(0)) { + case '+': + op1 += op2; + break; + case '-': + op1 -= op2; + break; + case '*': + op1 *= op2; + break; + case '/': + op1 /= op2; + break; + } + // ջ + stack.push(op1); + } + // ˵Dzջ + else { + stack.push(Integer.parseInt(token)); + } + } + + // ջֻʣһԪأǾĽ + return stack.pop(); + } +} diff --git a/[0151][Reverse Words In A String]/[0151][Reverse Words In A String].iml b/[0151][Reverse Words In A String]/[0151][Reverse Words In A String].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0151][Reverse Words In A String]/[0151][Reverse Words In A String].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0151][Reverse Words In A String]/[0151][ReverseWordsInAString].iml b/[0151][Reverse Words In A String]/[0151][ReverseWordsInAString].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0151][Reverse Words In A String]/[0151][ReverseWordsInAString].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/src/Main.java" b/[0151][Reverse Words In A String]/src/Main.java similarity index 100% rename from "\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/src/Main.java" rename to [0151][Reverse Words In A String]/src/Main.java diff --git "a/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/src/Solution.java" b/[0151][Reverse Words In A String]/src/Solution.java similarity index 100% rename from "\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/src/Solution.java" rename to [0151][Reverse Words In A String]/src/Solution.java diff --git a/[0152][Maximum Product Subarray]/[0152][Maximum Product Subarray].iml b/[0152][Maximum Product Subarray]/[0152][Maximum Product Subarray].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0152][Maximum Product Subarray]/[0152][Maximum Product Subarray].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0152][Maximum Product Subarray]/[0152][MaximumProductSubarray].iml b/[0152][Maximum Product Subarray]/[0152][MaximumProductSubarray].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0152][Maximum Product Subarray]/[0152][MaximumProductSubarray].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/src/Main.java" b/[0152][Maximum Product Subarray]/src/Main.java similarity index 100% rename from "\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/src/Main.java" rename to [0152][Maximum Product Subarray]/src/Main.java diff --git "a/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/src/Solution.java" b/[0152][Maximum Product Subarray]/src/Solution.java similarity index 100% rename from "\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/src/Solution.java" rename to [0152][Maximum Product Subarray]/src/Solution.java diff --git a/[0153][Find Minimum In Rotated Sorted Array]/[0153][Find Minimum In Rotated Sorted Array].iml b/[0153][Find Minimum In Rotated Sorted Array]/[0153][Find Minimum In Rotated Sorted Array].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0153][Find Minimum In Rotated Sorted Array]/[0153][Find Minimum In Rotated Sorted Array].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0153][Find Minimum In Rotated Sorted Array]/[0153][FindMinimumInRotatedSortedArray].iml b/[0153][Find Minimum In Rotated Sorted Array]/[0153][FindMinimumInRotatedSortedArray].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0153][Find Minimum In Rotated Sorted Array]/[0153][FindMinimumInRotatedSortedArray].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/src/Main.java" b/[0153][Find Minimum In Rotated Sorted Array]/src/Main.java similarity index 100% rename from "\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/src/Main.java" rename to [0153][Find Minimum In Rotated Sorted Array]/src/Main.java diff --git "a/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/src/Solution.java" b/[0153][Find Minimum In Rotated Sorted Array]/src/Solution.java similarity index 100% rename from "\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/src/Solution.java" rename to [0153][Find Minimum In Rotated Sorted Array]/src/Solution.java diff --git a/[0154][Find Minimum In Rotated Sorted Array II]/[0154][Find Minimum In Rotated Sorted Array II].iml b/[0154][Find Minimum In Rotated Sorted Array II]/[0154][Find Minimum In Rotated Sorted Array II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0154][Find Minimum In Rotated Sorted Array II]/[0154][Find Minimum In Rotated Sorted Array II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0154][Find Minimum In Rotated Sorted Array II]/[0154][FindMinimumInRotatedSortedArrayII].iml b/[0154][Find Minimum In Rotated Sorted Array II]/[0154][FindMinimumInRotatedSortedArrayII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0154][Find Minimum In Rotated Sorted Array II]/[0154][FindMinimumInRotatedSortedArrayII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/src/Main.java" b/[0154][Find Minimum In Rotated Sorted Array II]/src/Main.java similarity index 100% rename from "\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/src/Main.java" rename to [0154][Find Minimum In Rotated Sorted Array II]/src/Main.java diff --git "a/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/src/Solution.java" b/[0154][Find Minimum In Rotated Sorted Array II]/src/Solution.java similarity index 100% rename from "\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/src/Solution.java" rename to [0154][Find Minimum In Rotated Sorted Array II]/src/Solution.java diff --git a/[0155][Min Stack]/[0155][Min Stack].iml b/[0155][Min Stack]/[0155][Min Stack].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0155][Min Stack]/[0155][Min Stack].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0155][Min Stack]/[0155][MinStack].iml b/[0155][Min Stack]/[0155][MinStack].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0155][Min Stack]/[0155][MinStack].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220155\343\200\221\343\200\220MinStack\343\200\221/src/MinStack.java" b/[0155][Min Stack]/src/MinStack.java similarity index 100% rename from "\343\200\220155\343\200\221\343\200\220MinStack\343\200\221/src/MinStack.java" rename to [0155][Min Stack]/src/MinStack.java diff --git "a/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221.iml" b/[0160][Intersection of Two Linked Lists]/[0160][Intersection of Two Linked Lists].iml similarity index 100% rename from "\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221.iml" rename to [0160][Intersection of Two Linked Lists]/[0160][Intersection of Two Linked Lists].iml diff --git a/[0160][Intersection of Two Linked Lists]/src/ListNode.java b/[0160][Intersection of Two Linked Lists]/src/ListNode.java new file mode 100644 index 0000000..e49628e --- /dev/null +++ b/[0160][Intersection of Two Linked Lists]/src/ListNode.java @@ -0,0 +1,9 @@ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } +} diff --git a/[0160][Intersection of Two Linked Lists]/src/Solution.java b/[0160][Intersection of Two Linked Lists]/src/Solution.java new file mode 100644 index 0000000..72f8e1a --- /dev/null +++ b/[0160][Intersection of Two Linked Lists]/src/Solution.java @@ -0,0 +1,130 @@ +//Write a program to find the node at which the intersection of two singly linke +//d lists begins. +// +// For example, the following two linked lists: +// +// +// begin to intersect at node c1. +// +// +// +// Example 1: +// +// +// +//Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2 +//, skipB = 3 +//Output: Reference of the node with value = 8 +//Input Explanation: The intersected node's value is 8 (note that this must not +//be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. F +//rom the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the inter +//sected node in A; There are 3 nodes before the intersected node in B. +// +// +// +// Example 2: +// +// +// +//Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skip +//B = 1 +//Output: Reference of the node with value = 2 +//Input Explanation: The intersected node's value is 2 (note that this must not +//be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. F +//rom the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected +// node in A; There are 1 node before the intersected node in B. +// +// +// +// +// Example 3: +// +// +// +//Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 +//Output: null +//Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B +//, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be +//0, while skipA and skipB can be arbitrary values. +//Explanation: The two lists do not intersect, so return null. +// +// +// +// +// Notes: +// +// +// If the two linked lists have no intersection at all, return null. +// The linked lists must retain their original structure after the function returns. +// You may assume there are no cycles anywhere in the entire linked structure. +// Your code should preferably run in O(n) time and use only O(1) memory. +// +// Related Topics Linked List + + +//leetcode submit region begin(Prohibit modification and deletion) + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + /** + * 解题思路:将headA链表的尾结点链接到headB的头部,问题等价于求链表中环的入口节点,最后再还原两个表 + */ + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + + if (headA == null || headB == null) { + return null; + } + + if (headA == headB) { + return headA; + } + + ListNode tailA = headA; + while (tailA.next != null) { + tailA = tailA.next; + } + + tailA.next = headB; + + // 定义快慢指针 + ListNode fast = headA; + ListNode slow = headA; + + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + + //如果有环,想遇于环中某点 + if (fast == slow) { + break; + } + } + + //如果没有环,return null + if (fast.next == null || fast.next.next == null) { + tailA.next = null; // 还原链表 + return null; + } + + slow = headA; + while (slow != fast) { + slow = slow.next; + fast = fast.next; + } + + + tailA.next = null; // 还原链表 + return fast; + } +} +//leetcode submit region end(Prohibit modification and deletion) diff --git a/[0162][Find Peak Element]/[0162][Find Peak Element].iml b/[0162][Find Peak Element]/[0162][Find Peak Element].iml new file mode 100644 index 0000000..73f33e3 --- /dev/null +++ b/[0162][Find Peak Element]/[0162][Find Peak Element].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0162][Find Peak Element]/src/Main.java b/[0162][Find Peak Element]/src/Main.java new file mode 100644 index 0000000..9112882 --- /dev/null +++ b/[0162][Find Peak Element]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 16:44 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(2, solution.findPeakElement(new int[]{1, 2, 3, 1})); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(1, solution.findPeakElement(new int[]{1, 2, 1, 3, 5, 6, 4})); + } +} diff --git a/[0162][Find Peak Element]/src/Solution.java b/[0162][Find Peak Element]/src/Solution.java new file mode 100644 index 0000000..fc64ef2 --- /dev/null +++ b/[0162][Find Peak Element]/src/Solution.java @@ -0,0 +1,68 @@ +/** + * Author: + * Date: 2015-06-19 + * Time: 17:30 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * A peak element is an element that is greater than its neighbors.
+     *
+     * Given an input array where num[i]  num[i+1], find a peak element and return its index.
+     *
+     * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
+     *
+     * You may imagine that num[-1] = num[n] = -.
+     *
+     * For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return
+     * the index number 2.
+     *
+     * Note:
+     * Your solution should be in logarithmic complexity.
+     *
+     * Ŀ⣺
+     * ֵԪءֵָھӵԪ
+     *
+     * һnum[i]  num[i+1]ҵһֵԪز±ꡣ
+     *
+     * ֵܰ·һɡ
+     *
+     * Լnum[-1] = num[n] = -ޣʼԪصĩβԪصҲΪ
+     *
+     * 磬[1, 2, 3, 1]У3ǷֵԪأĺӦ÷±2
+     *
+     * ע⣺
+     * ΪӶȡ
+     * 
+ * + * @param nums + * @return + */ + public int findPeakElement(int[] nums) { + + if (nums == null || nums.length < 1) { + return -1; + } + + if (nums.length == 1) { + return 0; + } + + if (nums[0] > nums[1]) { + return 0; + } else if (nums[nums.length - 1] > nums[nums.length - 2]) { + return nums.length - 1; + } + + + for (int i = 1; i < nums.length - 1; i++) { + if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) { + return i; + } + } + + return -1; + } + +} diff --git a/[0167][Two Sum II - Input array is sorted]/[0167][Two Sum II - Input array is sorted].iml b/[0167][Two Sum II - Input array is sorted]/[0167][Two Sum II - Input array is sorted].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0167][Two Sum II - Input array is sorted]/[0167][Two Sum II - Input array is sorted].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0167][Two Sum II - Input array is sorted]/src/Solution.java b/[0167][Two Sum II - Input array is sorted]/src/Solution.java new file mode 100644 index 0000000..fd34284 --- /dev/null +++ b/[0167][Two Sum II - Input array is sorted]/src/Solution.java @@ -0,0 +1,59 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-09-28 16:17 + **/ +public class Solution { + /** + * 如果数组很大,target很小,可以考虑先用二分查找法找到不大于target元素的下标,再作处理 + * + * @param numbers + * @param target + * @return + */ + public int[] twoSum(int[] numbers, int target) { +// int idx = search(numbers, target); + int idx = numbers.length - 1; + return twoSum(numbers, target, idx); + } + + public int[] twoSum(int[] numbers, int target, int end) { + int[] result = {0, 0}; + + int lo = 0; + int hi = end; + + while (lo < hi) { + if (numbers[lo] + numbers[hi] == target) { + result[0] = lo; + result[1] = hi; + break; + } else if (numbers[lo] + numbers[hi] > target) { + hi--; + } else { + lo++; + } + } + + return result; + } + + public int search(int[] numbers, int target) { + + int lo = 0; + int hi = numbers.length - 1; + int mid; + + while (lo <= hi) { + mid = lo + (hi - lo) / 2; + if (numbers[mid] == target) { + return mid; + } else if (numbers[mid] > target) { + hi = mid - 1; + } else { + lo = mid + 1; + } + + } + return hi; + } +} diff --git a/[0173][Binary Search Tree Iterator]/[0173][Binary Search Tree Iterator].iml b/[0173][Binary Search Tree Iterator]/[0173][Binary Search Tree Iterator].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0173][Binary Search Tree Iterator]/[0173][Binary Search Tree Iterator].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0173][Binary Search Tree Iterator]/src/BSTIterator.java b/[0173][Binary Search Tree Iterator]/src/BSTIterator.java new file mode 100644 index 0000000..8465ef7 --- /dev/null +++ b/[0173][Binary Search Tree Iterator]/src/BSTIterator.java @@ -0,0 +1,53 @@ +import java.util.Deque; +import java.util.LinkedList; +import java.util.NoSuchElementException; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 16:54 + **/ +public class BSTIterator { + private TreeNode root; + private TreeNode prev = null; + // 最后一个元素表示next元素的值 + private Deque deque = new LinkedList<>(); + + public BSTIterator(TreeNode root) { + this.root = root; + TreeNode temp = root; + // 找最左的子结点,并且将经过的路径都记录下来 + while (temp != null) { + deque.addLast(temp); + temp = temp.left; + } + } + + /** + * @return the next smallest number + */ + public int next() { + + if (deque.isEmpty()) { + throw new NoSuchElementException(); + } + + TreeNode temp = deque.removeLast(); + + if (temp.right != null) { + TreeNode n = temp.right; + while (n != null) { + deque.addLast(n); + n = n.left; + } + } + + return temp.val; + } + + /** + * @return whether we have a next smallest number + */ + public boolean hasNext() { + return !deque.isEmpty(); + } +} diff --git a/[0173][Binary Search Tree Iterator]/src/Solution.java b/[0173][Binary Search Tree Iterator]/src/Solution.java new file mode 100644 index 0000000..6fb2141 --- /dev/null +++ b/[0173][Binary Search Tree Iterator]/src/Solution.java @@ -0,0 +1,49 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 17:06 + **/ +public class Solution { + @Test + public void test1() { + TreeNode root = new TreeNode(7); + root.left = new TreeNode(3); + root.right = new TreeNode(15); + root.right.left = new TreeNode(9); + root.right.right = new TreeNode(20); + + BSTIterator iterator = new BSTIterator(root); + Assert.assertEquals(3, iterator.next()); // return 3 + Assert.assertEquals(7, iterator.next()); // return 7 + Assert.assertEquals(true, iterator.hasNext()); // return true + Assert.assertEquals(9, iterator.next()); // return 9 + Assert.assertEquals(true, iterator.hasNext()); // return true + Assert.assertEquals(15, iterator.next()); // return 15 + Assert.assertEquals(true, iterator.hasNext()); // return true + Assert.assertEquals(20, iterator.next()); // return 20 + Assert.assertEquals(false, iterator.hasNext()); // return false + } + + @Test + public void test2() { + TreeNode root = new TreeNode(7); + BSTIterator iterator = new BSTIterator(root); + Assert.assertEquals(7, iterator.next()); // return 3 + Assert.assertEquals(false, iterator.hasNext()); // return false + Assert.assertEquals(false, iterator.hasNext()); // return false + } + + @Test + public void test3() { + TreeNode root = new TreeNode(1); + root.right = new TreeNode(2); + BSTIterator iterator = new BSTIterator(root); + Assert.assertEquals(true, iterator.hasNext()); // return 3 + Assert.assertEquals(1, iterator.next()); // return 3 + Assert.assertEquals(true, iterator.hasNext()); // return false + Assert.assertEquals(2, iterator.next()); // return false + Assert.assertEquals(false, iterator.hasNext()); // return false + } +} diff --git a/[0173][Binary Search Tree Iterator]/src/TreeNode.java b/[0173][Binary Search Tree Iterator]/src/TreeNode.java new file mode 100644 index 0000000..9aec4dd --- /dev/null +++ b/[0173][Binary Search Tree Iterator]/src/TreeNode.java @@ -0,0 +1,15 @@ +/** + * Author: + * Date: 2015-08-19 + * Time: 06:45 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0191][Number Of 1 Bits]/[0191][Number Of 1 Bits].iml b/[0191][Number Of 1 Bits]/[0191][Number Of 1 Bits].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0191][Number Of 1 Bits]/[0191][Number Of 1 Bits].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0191][Number Of 1 Bits]/[0191][NumberOf1Bits].iml b/[0191][Number Of 1 Bits]/[0191][NumberOf1Bits].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0191][Number Of 1 Bits]/[0191][NumberOf1Bits].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/src/Main.java" b/[0191][Number Of 1 Bits]/src/Main.java similarity index 100% rename from "\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/src/Main.java" rename to [0191][Number Of 1 Bits]/src/Main.java diff --git a/[0191][Number Of 1 Bits]/src/Solution.java b/[0191][Number Of 1 Bits]/src/Solution.java new file mode 100644 index 0000000..3e63a99 --- /dev/null +++ b/[0191][Number Of 1 Bits]/src/Solution.java @@ -0,0 +1,30 @@ +/** + * Author: ������ + * Date: 2015-06-17 + * Time: 21:51 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + * Write a function that takes an unsigned integer and returns the number of ��1' bits it has + * (also known as the Hamming weight). + *

+ * For example, the 32-bit integer ��11' has binary representation 00000000000000000000000000001011, + * so the function should return 3. + *

+ * ���������е�λ�� + * + * @param n + * @return + */ + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + + int count = 0; + while (n != 0) { + count++; + n = (n - 1) & n; + } + return count; + } +} diff --git a/[0198][House Robber]/[0198][House Robber].iml b/[0198][House Robber]/[0198][House Robber].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0198][House Robber]/[0198][House Robber].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0198][House Robber]/[0198][HouseRobber].iml b/[0198][House Robber]/[0198][HouseRobber].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0198][House Robber]/[0198][HouseRobber].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/src/Main.java" b/[0198][House Robber]/src/Main.java similarity index 100% rename from "\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/src/Main.java" rename to [0198][House Robber]/src/Main.java diff --git "a/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/src/Solution.java" b/[0198][House Robber]/src/Solution.java similarity index 100% rename from "\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/src/Solution.java" rename to [0198][House Robber]/src/Solution.java diff --git a/[0199][Binary Tree Right Side View]/[0199][Binary Tree Right Side View].iml b/[0199][Binary Tree Right Side View]/[0199][Binary Tree Right Side View].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0199][Binary Tree Right Side View]/[0199][Binary Tree Right Side View].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0199][Binary Tree Right Side View]/[0199][BinaryTreeRightSideView].iml b/[0199][Binary Tree Right Side View]/[0199][BinaryTreeRightSideView].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0199][Binary Tree Right Side View]/[0199][BinaryTreeRightSideView].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221/src/Solution.java" b/[0199][Binary Tree Right Side View]/src/Solution.java similarity index 100% rename from "\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221/src/Solution.java" rename to [0199][Binary Tree Right Side View]/src/Solution.java diff --git "a/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221/src/TreeNode.java" b/[0199][Binary Tree Right Side View]/src/TreeNode.java similarity index 100% rename from "\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221/src/TreeNode.java" rename to [0199][Binary Tree Right Side View]/src/TreeNode.java diff --git a/[0200][Number Of Islands]/[0200][Number Of Islands].iml b/[0200][Number Of Islands]/[0200][Number Of Islands].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0200][Number Of Islands]/[0200][Number Of Islands].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0200][Number Of Islands]/[0200][NumberOfIslands].iml b/[0200][Number Of Islands]/[0200][NumberOfIslands].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0200][Number Of Islands]/[0200][NumberOfIslands].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0200][Number Of Islands]/src/Solution.java b/[0200][Number Of Islands]/src/Solution.java new file mode 100644 index 0000000..ff8698a --- /dev/null +++ b/[0200][Number Of Islands]/src/Solution.java @@ -0,0 +1,90 @@ +/** + * Author: ������ + * Date: 2015-06-20 + * Time: 11:00 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *

+     * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
+     * An island is surrounded by water and is formed by connecting adjacent lands horizontally
+     * or vertically. You may assume all four edges of the grid are all surrounded by water.
+     *
+     * Example 1:
+     *      11110
+     *      11010
+     *      11000
+     *      00000
+     * Answer: 1
+     *
+     * Example 2:
+     *      11000
+     *      11000
+     *      00100
+     *      00011
+     * Answer: 3
+     *
+     * ��Ŀ���⣺
+     * ������һ����ά����ĵ�ͼ��'1'��½�أ���0��ˮ�����������������������������滷ˮ��
+     * �������ڵ�½��ˮƽ��ֱ���Ӷ��γɵġ�����Լ��������������ĸ��߶���ˮ��Χ��
+     *
+     * ����˼·��
+     * һ��������һ����Ӧ�ķ��ʱ�Ǿ��󣬶�����ÿ��Ԫ��ʱ�й�����ȱ���������������ȱ�������ͳ�Ƶ�����Ŀ
+     *
+     * 
+ * + * @param grid + * @return + */ + public int numIslands(char[][] grid) { + // ����У�� + if (grid == null || grid.length == 0 || grid[0].length == 0) { + return 0; + } + + // Ԫ��Ĭ��ֵ��false + boolean[][] visited = new boolean[grid.length][grid[0].length]; + + int result = 0; + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + // �����λ��û�б����ʹ������Ҵ�λ���ǵ�������¹�����ȱ��� + if (!visited[i][j] && grid[i][j] == '1') { + result++; + bfs(grid, visited, i, j); + } + } + } + return result; + } + + /** + * ����������� + * + * @param grid ���� + * @param visited ���ʱ�Ǿ��� + * @param row ������ + * @param col ������ + */ + private void bfs(char[][] grid, boolean[][] visited, int row, int col) { + + if (row >= 0 && row < grid.length // �кϷ� + && col >= 0 && col < grid[0].length // �кϷ� + && !visited[row][col] // û�з��ʹ� + && grid[row][col] == '1') { // �ǵ���½�� + + // ��Ǵ�λ���Ѿ����ʹ��� + visited[row][col] = true; + + // �� + bfs(grid, visited, row - 1, col); + // �� + bfs(grid, visited, row, col + 1); + // �� + bfs(grid, visited, row + 1, col); + // �� + bfs(grid, visited, row, col - 1); + } + } +} diff --git a/[0201][Bitwise AND Of Numbers Range]/[0201][Bitwise AND Of Numbers Range].iml b/[0201][Bitwise AND Of Numbers Range]/[0201][Bitwise AND Of Numbers Range].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0201][Bitwise AND Of Numbers Range]/[0201][Bitwise AND Of Numbers Range].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0201][Bitwise AND Of Numbers Range]/[0201][BitwiseANDOfNumbersRange].iml b/[0201][Bitwise AND Of Numbers Range]/[0201][BitwiseANDOfNumbersRange].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0201][Bitwise AND Of Numbers Range]/[0201][BitwiseANDOfNumbersRange].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221/src/Solution.java" b/[0201][Bitwise AND Of Numbers Range]/src/Solution.java similarity index 100% rename from "\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221/src/Solution.java" rename to [0201][Bitwise AND Of Numbers Range]/src/Solution.java diff --git a/[0202][Happy Number ]/[0202][Happy Number ].iml b/[0202][Happy Number ]/[0202][Happy Number ].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0202][Happy Number ]/[0202][Happy Number ].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0202][Happy Number ]/[0202][HappyNumber ].iml b/[0202][Happy Number ]/[0202][HappyNumber ].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0202][Happy Number ]/[0202][HappyNumber ].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/src/Main.java" b/[0202][Happy Number ]/src/Main.java similarity index 100% rename from "\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/src/Main.java" rename to [0202][Happy Number ]/src/Main.java diff --git a/[0202][Happy Number ]/src/Solution.java b/[0202][Happy Number ]/src/Solution.java new file mode 100644 index 0000000..46f562d --- /dev/null +++ b/[0202][Happy Number ]/src/Solution.java @@ -0,0 +1,51 @@ +import java.util.HashSet; + +/** + * Author: ������ + * Date: 2015-06-17 + * Time: 21:36 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + * Write an algorithm to determine if a number is "happy". + * A happy number is a number defined by the following process: Starting with any positive integer, + * replace the number by the sum of the squares of its digits, and repeat the process until the number + * equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those + * numbers for which this process ends in 1 are happy numbers. + *

+ * ��ĿҪ�������һ�������������ϸ�����λ�����ֵ�ƽ���ͣ�����������Ϊ1���������Ϊhappy number�� + * ���������ܴ�ij������ʼ����ѭ���� + * + * @param n + * @return + */ + public boolean isHappy(int n) { + + if (n < 1) { + return false; + } + + // ���ڱ����м���ֵĽ�� + HashSet set = new HashSet<>(32); + + int tmp; + int newN; + + // n��Ϊ1������n��ֵ�����ظ����֣��������ѭ�� + while (n != 1 && !set.contains(n)) { + set.add(n); + newN = 0; + while (n > 0) { + tmp = n % 10; + n /= 10; + newN += tmp * tmp; + } + + n = newN; + } + + return n == 1; + } + +} diff --git a/[0203][Remove Linked List Elements]/[0203][Remove Linked List Elements].iml b/[0203][Remove Linked List Elements]/[0203][Remove Linked List Elements].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0203][Remove Linked List Elements]/[0203][Remove Linked List Elements].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0203][Remove Linked List Elements]/[0203][RemoveLinkedList Elements].iml b/[0203][Remove Linked List Elements]/[0203][RemoveLinkedList Elements].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0203][Remove Linked List Elements]/[0203][RemoveLinkedList Elements].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221/src/ListNode.java" b/[0203][Remove Linked List Elements]/src/ListNode.java similarity index 100% rename from "\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221/src/ListNode.java" rename to [0203][Remove Linked List Elements]/src/ListNode.java diff --git "a/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221/src/Solution.java" b/[0203][Remove Linked List Elements]/src/Solution.java similarity index 100% rename from "\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221/src/Solution.java" rename to [0203][Remove Linked List Elements]/src/Solution.java diff --git a/[0204][Count Primes]/[0204][Count Primes].iml b/[0204][Count Primes]/[0204][Count Primes].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0204][Count Primes]/[0204][Count Primes].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0204][Count Primes]/[0204][CountPrimes].iml b/[0204][Count Primes]/[0204][CountPrimes].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0204][Count Primes]/[0204][CountPrimes].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221/src/Solution.java" b/[0204][Count Primes]/src/Solution.java similarity index 100% rename from "\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221/src/Solution.java" rename to [0204][Count Primes]/src/Solution.java diff --git a/[0205][Isomorphic Strings]/[0205][Isomorphic Strings].iml b/[0205][Isomorphic Strings]/[0205][Isomorphic Strings].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0205][Isomorphic Strings]/[0205][Isomorphic Strings].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0205][Isomorphic Strings]/[0205][IsomorphicStrings].iml b/[0205][Isomorphic Strings]/[0205][IsomorphicStrings].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0205][Isomorphic Strings]/[0205][IsomorphicStrings].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221/src/Solution.java" b/[0205][Isomorphic Strings]/src/Solution.java similarity index 100% rename from "\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221/src/Solution.java" rename to [0205][Isomorphic Strings]/src/Solution.java diff --git a/[0206][Reverse Linked List]/[0206][Reverse Linked List].iml b/[0206][Reverse Linked List]/[0206][Reverse Linked List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0206][Reverse Linked List]/[0206][Reverse Linked List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/src/ListNode.java" b/[0206][Reverse Linked List]/src/ListNode.java similarity index 100% rename from "\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/src/ListNode.java" rename to [0206][Reverse Linked List]/src/ListNode.java diff --git "a/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/src/Main.java" b/[0206][Reverse Linked List]/src/Main.java similarity index 100% rename from "\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/src/Main.java" rename to [0206][Reverse Linked List]/src/Main.java diff --git a/[0206][Reverse Linked List]/src/Solution.java b/[0206][Reverse Linked List]/src/Solution.java new file mode 100644 index 0000000..360bebd --- /dev/null +++ b/[0206][Reverse Linked List]/src/Solution.java @@ -0,0 +1,48 @@ +/** + * Author: + * Date: 2015-06-19 + * Time: 11:17 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + * Reverse a singly linked list. + * ת + * ʹͷ巨 + * + * @param head + * @return + */ + public ListNode reverseList(ListNode head) { + // ͷ + ListNode root = new ListNode(0); + ListNode nextNode; + while (head != null) { + nextNode = head.next; + head.next = root.next; + root.next = head; + head = nextNode; + } + + head = root.next; + root.next = null; + + return head; + } + + /** + * TODO ʹõݹⷨ + * + * @param head + * @return + */ + public ListNode reverseList2(ListNode head) { + if (head == null) { + return null; + } + + reverseList2(head.next).next = head; + + return null; + } +} diff --git a/[0207][Course Schedule]/[0207][Course Schedule].iml b/[0207][Course Schedule]/[0207][Course Schedule].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0207][Course Schedule]/[0207][Course Schedule].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0207][Course Schedule]/src/Main.java b/[0207][Course Schedule]/src/Main.java new file mode 100644 index 0000000..a94abab --- /dev/null +++ b/[0207][Course Schedule]/src/Main.java @@ -0,0 +1,45 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-07 11:35 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[][] arr = {{1, 0}}; + Assert.assertEquals(true, solution.canFinish(2, arr)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + int[][] arr = {{1, 0}, {0, 1}}; + Assert.assertEquals(false, solution.canFinish(2, arr)); + } + + + @Test + public void test3() { + Solution solution = new Solution(); + int[][] arr = {{0, 1}, {0, 2}, {1, 2}}; + Assert.assertEquals(true, solution.canFinish(3, arr)); + } + + @Test + public void test4() { + Solution solution = new Solution(); + int[][] arr = {{2, 0}, {1, 0}, {3, 1}, {3, 2}, {1, 3}}; + Assert.assertEquals(false, solution.canFinish(4, arr)); + } + + + @Test + public void test5() { + Solution solution = new Solution(); + int[][] arr = {{1, 0}, {2, 6}, {1, 7}, {6, 4}, {7, 0}, {0, 5}}; + Assert.assertEquals(true, solution.canFinish(8, arr)); + } +} diff --git a/[0207][Course Schedule]/src/Solution.java b/[0207][Course Schedule]/src/Solution.java new file mode 100644 index 0000000..208c49e --- /dev/null +++ b/[0207][Course Schedule]/src/Solution.java @@ -0,0 +1,104 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-07 11:23 + **/ +public class Solution { + /** + *

+     * There are a total of n courses you have to take, labeled from 0 to n-1.
+     *
+     * Some courses may have prerequisites, for example to take course 0 you have to first take
+     * course 1, which is expressed as a pair: [0,1]
+     *
+     * Given the total number of courses and a list of prerequisite pairs, is it possible for
+     * you to finish all courses?
+     *
+     * Example 1:
+     *
+     * Input: 2, [[1,0]]
+     * Output: true
+     * Explanation: There are a total of 2 courses to take.
+     *              To take course 1 you should have finished course 0. So it is possible.
+     * Example 2:
+     *
+     * Input: 2, [[1,0],[0,1]]
+     * Output: false
+     * Explanation: There are a total of 2 courses to take.
+     *              To take course 1 you should have finished course 0, and to take course 0 you should
+     *              also have finished course 1. So it is impossible.
+     * Note:
+     *
+     * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read
+     * more about how a graph is represented.
+     * You may assume that there are no duplicate edges in the input prerequisites.
+     *
+     * 解题思路:
+     * 使用深度度优先遍历,记录每个访问过的点,如果遍历过程中再次遍历到了已经访问过的点,
+     * 说明有环状依赖,课程安排不合理
+     * 
+ */ + + public boolean canFinish(int numCourses, int[][] prerequisites) { + // 说明没有课程依赖 + if (prerequisites == null || prerequisites.length == 0) { + return true; + } + + + Map> dependencies = new HashMap<>(); + + for (int[] arr : prerequisites) { + List val = dependencies.computeIfAbsent(arr[0], k -> new LinkedList<>()); + val.add(arr[1]); + } + + boolean[] visit = new boolean[numCourses]; + Deque path = new LinkedList<>(); + for (int i = 0; i < visit.length; i++) { + if (!visit[i]) { + if (!dfs(i, dependencies, visit, path)) { + return false; + } + } + } + + return true; + } + + /** + * 判断从i课程序开始,是否存在环 + * + * @param course + * @param dependencies + * @param visit + * @return + */ + private boolean dfs(int course, Map> dependencies, boolean[] visit, Deque path) { + List dependency = dependencies.get(course); + + if (dependency == null) { + return true; + } + + if (path.contains(course)) { + return false; + } + + path.addLast(course); + + + for (int i : dependency) { + boolean result = dfs(i, dependencies, visit, path); + if (!result) { + return false; + } + } + + visit[course] = true; + path.removeLast(); + + return true; + } +} diff --git a/[0215][Kth Largest Element In An Array]/[0215][Kth Largest Element In An Array].iml b/[0215][Kth Largest Element In An Array]/[0215][Kth Largest Element In An Array].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0215][Kth Largest Element In An Array]/[0215][Kth Largest Element In An Array].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0215][Kth Largest Element In An Array]/[0215][KthLargestElementInAnArray].iml b/[0215][Kth Largest Element In An Array]/[0215][KthLargestElementInAnArray].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0215][Kth Largest Element In An Array]/[0215][KthLargestElementInAnArray].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0215][Kth Largest Element In An Array]/src/Main.java b/[0215][Kth Largest Element In An Array]/src/Main.java new file mode 100644 index 0000000..ec1a203 --- /dev/null +++ b/[0215][Kth Largest Element In An Array]/src/Main.java @@ -0,0 +1,12 @@ +/** + * Author: ������ + * Date: 2015-06-19 + * Time: 20:01 + * Declaration: All Rights Reserved !!! + */ +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.findKthLargest(new int[]{2, 1}, 2)); + } +} diff --git a/[0215][Kth Largest Element In An Array]/src/Solution.java b/[0215][Kth Largest Element In An Array]/src/Solution.java new file mode 100644 index 0000000..7648127 --- /dev/null +++ b/[0215][Kth Largest Element In An Array]/src/Solution.java @@ -0,0 +1,79 @@ +/** + * Author: ������ + * Date: 2015-06-19 + * Time: 19:36 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Find the kth largest element in an unsorted array. Note that it is the kth
+     * largest element in the sorted order, not the kth distinct element.
+     *
+     * For example,
+     * Given [3,2,1,5,6,4] and k = 2, return 5.
+     *
+     * Note:
+     * You may assume k is always valid, 1 �� k �� array's length.
+     *
+     * ��Ŀ���⣺
+     * ��һ��δ��������������ҳ���k���Ԫ�ء�ע��������֮��ĵ�k�󣬶��ǵ�k�����ظ���Ԫ��
+     * ���Լ���kһ������Ч�ģ� 1 �� k �� ���鳤��
+     *
+     * ����˼·��
+     * O(n)�ⷨ������ѡ��QuickSelect���㷨
+     * 
+ * + * @param nums + * @param k + * @return + */ + public int findKthLargest(int[] nums, int k) { + + if (k < 1 || nums == null || nums.length < k) { + throw new IllegalArgumentException(); + } + + return findKthLargest(nums, 0, nums.length - 1, k); + } + + public int findKthLargest(int[] nums, int start, int end, int k) { + + // ����ֵ + int pivot = nums[start]; + int lo = start; + int hi = end; + + while (lo < hi) { + // ��С������ֵ�����ƶ���������� + while (lo < hi && nums[hi] >= pivot) { + hi--; + } + nums[lo] = nums[hi]; + + // ����������ֵ�����ƶ��������ұ� + while (lo < hi && nums[lo] <= pivot) { + lo++; + } + nums[hi] = nums[lo]; + } + + nums[lo] = pivot; + + // ����Ѿ��ҵ��� + if (end - lo + 1 == k) { + return pivot; + } + // ��k�������loλ�õ��ұ� + else if (end - lo + 1 > k) { + return findKthLargest(nums, lo + 1, end, k); + } + // ��k�������loλ�õ���� + else { + // k-(end-lo+1) + // (end-lo+1)����ʾ��loλ�ÿ�ʼ��endλ�õ�Ԫ�ظ�������������Ұ벿�� + // ԭ���ĵ�k����k-(end-lo+1)�� + return findKthLargest(nums, start, lo - 1, k - (end - lo + 1)); + } + } +} diff --git a/[0216][Combination Sum III]/[0216][Combination Sum III].iml b/[0216][Combination Sum III]/[0216][Combination Sum III].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0216][Combination Sum III]/[0216][Combination Sum III].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0216][Combination Sum III]/[0216][CombinationSumIII].iml b/[0216][Combination Sum III]/[0216][CombinationSumIII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0216][Combination Sum III]/[0216][CombinationSumIII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/src/Main.java" b/[0216][Combination Sum III]/src/Main.java similarity index 100% rename from "\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/src/Main.java" rename to [0216][Combination Sum III]/src/Main.java diff --git a/[0216][Combination Sum III]/src/Solution.java b/[0216][Combination Sum III]/src/Solution.java new file mode 100644 index 0000000..563a5f7 --- /dev/null +++ b/[0216][Combination Sum III]/src/Solution.java @@ -0,0 +1,100 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: ������ + * Date: 2015-06-21 + * Time: 21:31 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + /** + *
+     * Find all possible combinations of k numbers that add up to a number n,
+     * given that only numbers from 1 to 9 can be used and each combination
+     * should be a unique set of numbers.
+     *
+     * Ensure that numbers within the set are sorted in ascending order.
+     *
+     * Example 1:
+     * Input: k = 3, n = 7
+     * Output:
+     * [[1,2,4]]
+     *
+     * Example 2:
+     * Input: k = 3, n = 9
+     * Output:
+     * [[1,2,6], [1,3,5], [2,3,4]]
+     *
+     * ��Ŀ���⣺
+     * Ѱ����������k����֮�͵���n����ϣ�ֻ����ʹ������1-9������ÿһ������е�����Ӧ����Ψһ�ġ�
+     * ȷ������е������Ե���˳�����С�
+     *
+     * ����˼·��
+     * ���ݷ�
+     * 
+ * + * @param k + * @param n + * @return + */ + public List> combinationSum3(int k, int n) { + // ���ڱ������н�� + List> result = new LinkedList<>(); + // ���ڱ����м��� + List list = new LinkedList<>(); + // ��������ͽ��н������ + if (k > 0 && k <= 9) { + solve(k, 1, n, 0, list, result); + } + + // ���ؽ�� + return result; + } + + /** + * ��ⷽ�� + * + * @param k ÿ�����Ԫ�ظ��� + * @param cur ��ǰ�����k��Ԫ�� + * @param remainder k - cur + 1��Ԫ�صĺ� + * @param prevVal ��cur-1��Ԫ�ص�ȡֵ + * @param list �����Ԫ�صļ����� + * @param result �������н�������� + */ + public void solve(int k, int cur, int remainder, int prevVal, List list, List> result) { + // �������һ��Ԫ�� + if (cur == k) { + // remainderΪ���һ����Ԫ�ص�ֵ�����������ǰһ����Ԫ�ص�ֵ�����Ҳ��ܳ���9 + if (remainder > prevVal && remainder <= 9) { + // ���Ԫ��ֵ + list.add(remainder); + + // ����������µĶ����� + List one = new LinkedList<>(); + for (Integer i : list) { + one.add(i); + } + + // ������ + result.add(one); + // ɾ�����һ��Ԫ�أ������ֳ���ԭ + list.remove(list.size() - 1); + } + } + // �������һ��Ԫ�� + else if (cur < k) { + for (int i = prevVal + 1; i <= 9 - (k - cur); i++) { + // ���Ԫ�� + list.add(i); + // �ݹ���� + solve(k, cur + 1, remainder - i, i, list, result); + // �ֳ���ԭ + list.remove(list.size() - 1); + + } + } + + + } +} diff --git a/[0217][Contains Duplicate ]/[0217][Contains Duplicate ].iml b/[0217][Contains Duplicate ]/[0217][Contains Duplicate ].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0217][Contains Duplicate ]/[0217][Contains Duplicate ].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0217][Contains Duplicate ]/[0217][ContainsDuplicate ].iml b/[0217][Contains Duplicate ]/[0217][ContainsDuplicate ].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0217][Contains Duplicate ]/[0217][ContainsDuplicate ].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/src/Main.java" b/[0217][Contains Duplicate ]/src/Main.java similarity index 100% rename from "\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/src/Main.java" rename to [0217][Contains Duplicate ]/src/Main.java diff --git a/[0217][Contains Duplicate ]/src/Solution.java b/[0217][Contains Duplicate ]/src/Solution.java new file mode 100644 index 0000000..d144b96 --- /dev/null +++ b/[0217][Contains Duplicate ]/src/Solution.java @@ -0,0 +1,46 @@ +import java.util.HashSet; +import java.util.Set; + +/** + * Author: ������ + * Date: 2015-06-18 + * Time: 09:40 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + + + /** + * Given an array of integers, find if the array contains any duplicates. + * Your function should return true if any value appears at least twice in the + * array, and it should return false if every element is distinct. + *

+ * ��Ŀ���⣺����һ���������飬�ж��������Ƿ�����ظ�Ԫ�ء��������������һ�����ֳ������������Σ� + * ��ĺ���Ӧ�÷���true�����ÿһ��Ԫ�ض���Ψһ�ģ�����false�� + *

+ * ����˼·����set���ݽṹ + * + * @param nums + * @return + */ + public boolean containsDuplicate(int[] nums) { + + // Ԫ�ظ�������1�Ž�������IJ��� + if (nums != null && nums.length > 1) { + //����һ��hashSet + Set set = new HashSet<>(nums.length); + for (int i : nums) { + // ���Ԫ���Ѿ����ھͷ���true + if (set.contains(i)) { + return true; + } + // û�о���ӵ�Ԫ�ؼ����� + else { + set.add(i); + } + } + } + + return false; + } +} diff --git a/[0219][Contains Duplicate II]/[0219][Contains Duplicate II].iml b/[0219][Contains Duplicate II]/[0219][Contains Duplicate II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0219][Contains Duplicate II]/[0219][Contains Duplicate II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0219][Contains Duplicate II]/[0219][ContainsDuplicateII].iml b/[0219][Contains Duplicate II]/[0219][ContainsDuplicateII].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0219][Contains Duplicate II]/[0219][ContainsDuplicateII].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0219][Contains Duplicate II]/src/Solution.java b/[0219][Contains Duplicate II]/src/Solution.java new file mode 100644 index 0000000..3c0f97e --- /dev/null +++ b/[0219][Contains Duplicate II]/src/Solution.java @@ -0,0 +1,55 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * Author: ������ + * Date: 2015-06-19 + * Time: 14:10 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + + /** + * Given an array of integers and an integer k, find out whether there there are + * two distinct indices i and j in the array such that nums[i] = nums[j] and the + * difference between i and j is at most k. + *

+ * ��Ŀ���⣺ + * ����һ����������nums��һ������k�����ҽ�������������ͬ���±�i��j����nums[i] = nums[j] + * ����|i-j|<=kʱ����true�����򷵻�false�� + *

+ * ����˼·�� + * ��nums[0...n-1]������һ��map�У�(muns[i], i)�������nums[k]�Ѿ����ڣ� + * ��Ƚ�֮ǰ���±�����ڵ��±�IJ�ֵ�������ֵ������k��˵��������������������ֵ�� + * ����ʹ���µ��±���Ϊֵ + * + * @param nums + * @param k + * @return + */ + public boolean containsNearbyDuplicate(int[] nums, int k) { + // ���������ж� + if (nums == null || nums.length < 2 || k < 1) { + return false; + } + + Map map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + + // ���û�ж�Ӧ��key��ӽ�ȥ + if (!map.containsKey(nums[i])) { + map.put(nums[i], i); + } + // �Ѿ��ж�Ӧ��key-value�� + else { + // ԭ�������ֵ��Ӧ���±꣬��һ��С�����ڵ��±� + int value = map.get(nums[i]); + if (i - value <= k) { + return true; + } + map.put(nums[i], i); + } + } + return false; + } +} diff --git a/[0222][Count Complete Tree Nodes]/[0222][Count Complete Tree Nodes].iml b/[0222][Count Complete Tree Nodes]/[0222][Count Complete Tree Nodes].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0222][Count Complete Tree Nodes]/[0222][Count Complete Tree Nodes].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0222][Count Complete Tree Nodes]/src/Main.java b/[0222][Count Complete Tree Nodes]/src/Main.java new file mode 100644 index 0000000..19fccc0 --- /dev/null +++ b/[0222][Count Complete Tree Nodes]/src/Main.java @@ -0,0 +1,21 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-08 21:07 + **/ +public class Main { + @Test + public void test1() { + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.left = new TreeNode(4); + root.left.right = new TreeNode(5); + root.right.left = new TreeNode(6); + Solution solution = new Solution(); + + Assert.assertEquals(6, solution.countNodes(root)); + } +} diff --git a/[0222][Count Complete Tree Nodes]/src/Solution.java b/[0222][Count Complete Tree Nodes]/src/Solution.java new file mode 100644 index 0000000..ce53173 --- /dev/null +++ b/[0222][Count Complete Tree Nodes]/src/Solution.java @@ -0,0 +1,46 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-08 20:52 + **/ +public class Solution { + public int countNodes(TreeNode root) { + if (root == null) { + return 0; + } + + int h1 = leftestHeight(root); + int h2 = rightestHeight(root); + + if (h1 == h2) { + return ((1 << h1) - 1); + } + + return 1 + countNodes(root.left) + countNodes(root.right); + } + + /** + * 最右路径的长度 + * + * @param node + * @return + */ + private int rightestHeight(TreeNode node) { + if (node == null) { + return 0; + } + return 1 + rightestHeight(node.right); + } + + /** + * 最左路径的长度 + * + * @param node + * @return + */ + private int leftestHeight(TreeNode node) { + if (node == null) { + return 0; + } + return 1 + leftestHeight(node.left); + } +} diff --git "a/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221/src/TreeNode.java" b/[0222][Count Complete Tree Nodes]/src/TreeNode.java similarity index 100% rename from "\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221/src/TreeNode.java" rename to [0222][Count Complete Tree Nodes]/src/TreeNode.java diff --git a/[0223][Rectangle Area]/[0223][Rectangle Area].iml b/[0223][Rectangle Area]/[0223][Rectangle Area].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0223][Rectangle Area]/[0223][Rectangle Area].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0223][Rectangle Area]/[0223][RectangleArea].iml b/[0223][Rectangle Area]/[0223][RectangleArea].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0223][Rectangle Area]/[0223][RectangleArea].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/src/Main.java" b/[0223][Rectangle Area]/src/Main.java similarity index 100% rename from "\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/src/Main.java" rename to [0223][Rectangle Area]/src/Main.java diff --git a/[0223][Rectangle Area]/src/Solution.java b/[0223][Rectangle Area]/src/Solution.java new file mode 100644 index 0000000..b8d05d5 --- /dev/null +++ b/[0223][Rectangle Area]/src/Solution.java @@ -0,0 +1,76 @@ +/** + * Author: ������ + * Date: 2015-06-19 + * Time: 15:32 + * Declaration: All Rights Reserved !!! + */ +public class Solution { + + /** + *

+     * Find the total area covered by two rectilinear rectangles in a 2D plane.
+     * Each rectangle is defined by its bottom left corner and top right
+     * corner as shown in the figure.
+     *
+     * Assume that the total area is never beyond the maximum possible value of int.
+     *
+     * *****************************(C,D):(3,4)
+     * *                           *
+     * *                           *
+     * *           *************************************(G,H):(9,2)
+     * *           *               *                   *
+     * *           *               *                   *
+     * *           *               *                   *
+     * *           *               *                   *
+     * *           *(0,0)          *                   *
+     * *****************************                   *
+     * (A,B):(-3,0)*                                   *
+     *             *                                   *
+     *             * (E,F):(0��-1)                     *
+     *             *************************************
+     *
+     *   ***************************        ***************************
+     *   *            D            *        *            H            *
+     *   *                         *        *                         *
+     *   *A                       C*        *E                       G*
+     *   *                         *        *                         *
+     *   *                         *        *                         *
+     *   *            B            *        *            F            *
+     *   ***************************        ***************************
+     *
+     *
+     *
+     * 
+ * ��Ŀ���⣺ + * �������������ܹ����ǵ���� + *

+ * ����˼·�� + * ���㷽��Ϊ����1�����+����2�����-�������ι�ͬ�ĸ�������� + * + * @param A + * @param B + * @param C + * @param D + * @param E + * @param F + * @param G + * @param H + * @return + */ + public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { + long area = (long) (C - A) * (D - B) + (long) (G - E) * (H - F); + // Math.min(C, G) ��ʾ�ұ߱ߵ���С�ı� + // Math.max(A, E) ��ʾ��߱ߵ����ı� + // ����ļ������������Խ�飬Ҫ�������ݷ�Χ + long width = Math.max((long) Math.min(C, G) - (long) Math.max(A, E), 0); + // Math.min(D, H) ��ʾ���߱ߵ���С�ı� + // Math.max(B, F) ��ʾ�ױ߱ߵ����ı� + long height = Math.max((long) Math.min(D, H) - (long) Math.max(B, F), 0); + + System.out.println(width + ":" + height + "=" + width * height); + + return (int) (area - width * height); + } + + +} diff --git a/[0225][Implement Stack Using Queues]/[0225][Implement Stack Using Queues].iml b/[0225][Implement Stack Using Queues]/[0225][Implement Stack Using Queues].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0225][Implement Stack Using Queues]/[0225][Implement Stack Using Queues].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0225][Implement Stack Using Queues]/[0225][ImplementStackUsingQueues].iml b/[0225][Implement Stack Using Queues]/[0225][ImplementStackUsingQueues].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0225][Implement Stack Using Queues]/[0225][ImplementStackUsingQueues].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221/src/MyStack.java" b/[0225][Implement Stack Using Queues]/src/MyStack.java similarity index 100% rename from "\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221/src/MyStack.java" rename to [0225][Implement Stack Using Queues]/src/MyStack.java diff --git a/[0226][Invert Binary Tree]/[0226][Invert Binary Tree].iml b/[0226][Invert Binary Tree]/[0226][Invert Binary Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0226][Invert Binary Tree]/[0226][Invert Binary Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git "a/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221/src/Solution.java" b/[0226][Invert Binary Tree]/src/Solution.java similarity index 100% rename from "\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221/src/Solution.java" rename to [0226][Invert Binary Tree]/src/Solution.java diff --git a/[0226][Invert Binary Tree]/src/TreeNode.java b/[0226][Invert Binary Tree]/src/TreeNode.java new file mode 100644 index 0000000..73c7ed9 --- /dev/null +++ b/[0226][Invert Binary Tree]/src/TreeNode.java @@ -0,0 +1,15 @@ +/** + * Author: + * Date: 2015-06-18 + * Time: 10:02 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0227][Basic Calculator II]/[0227][Basic Calculator II].iml b/[0227][Basic Calculator II]/[0227][Basic Calculator II].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0227][Basic Calculator II]/[0227][Basic Calculator II].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0227][Basic Calculator II]/src/Main.java b/[0227][Basic Calculator II]/src/Main.java new file mode 100644 index 0000000..9d0983f --- /dev/null +++ b/[0227][Basic Calculator II]/src/Main.java @@ -0,0 +1,32 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 13:23 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(7, solution.calculate("3+2*2")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(5, solution.calculate(" 3 + 5 / 2 ")); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals(1, solution.calculate("1-1+1")); + } + + @Test + public void test4() { + Solution solution = new Solution(); + Assert.assertEquals(1, solution.calculate("1+1-1")); + } +} diff --git a/[0227][Basic Calculator II]/src/Solution.java b/[0227][Basic Calculator II]/src/Solution.java new file mode 100644 index 0000000..5f8a945 --- /dev/null +++ b/[0227][Basic Calculator II]/src/Solution.java @@ -0,0 +1,133 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * https://leetcode.com/problems/basic-calculator-ii/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 10:54 + **/ +public class Solution { + /** + *

+     * Implement a basic calculator to evaluate a simple expression string.
+     *
+     * The expression string contains only non-negative integers, +, -, *, / operators
+     * and empty spaces . The integer division should truncate toward zero.
+     *
+     * Example 1:
+     *
+     * Input: "3+2*2"
+     * Output: 7
+     * Example 2:
+     *
+     * Input: " 3/2 "
+     * Output: 1
+     * Example 3:
+     *
+     * Input: " 3+5 / 2 "
+     * Output: 5
+     * Note:
+     *
+     * You may assume that the given expression is always valid.
+     * Do not use the eval built-in library function.
+     * 思路:
+     * 遇到加减就入操作数栈和操作符栈,遇到乘除就计算,将计算结果作为新的字符串的第一个值,后面是处理的字符串
+     * 最后处理所有剩下的加减操作
+     * 如 1+2+3*4+5+6
+     * 处理完第一个*号后
+     * operator: +, +
+     * operand: 1, 2
+     * s: 12+5+6
+     * 整个字符串处理完后
+     * operator: +, +, +, +
+     * operand: 1, 2, 12, 5, 6
+     * 再进行计算
+     * 
+ * + * @param s + * @return + */ + public int calculate(String s) { + + if (s == null || s.length() < 1) { + throw new IllegalArgumentException("s: " + s); + } + + Deque operands = new LinkedList<>(); + Deque operators = new LinkedList<>(); + + int idx = 0; + while (idx < s.length()) { + while (idx < s.length() && s.charAt(idx) == ' ') { + idx++; + } + + // 找操作数 + int start = idx; + idx++; + while (idx < s.length() && Character.isDigit(s.charAt(idx))) { + idx++; + } + // 操作数入栈 + operands.addLast(Integer.parseInt(s.substring(start, idx))); + + // 找idx后的第一个非空白字符 + while (idx < s.length() && s.charAt(idx) == ' ') { + idx++; + } + + // 如果是乘法或者除法,就进行一次计算 + if (idx < s.length() && (s.charAt(idx) == '*' || s.charAt(idx) == '/')) { + char op = s.charAt(idx); + // 下一个数字的第一个位置 + while (idx < s.length() && !Character.isDigit(s.charAt(idx))) { + idx++; + } + + start = idx; + while (idx < s.length() && Character.isDigit(s.charAt(idx))) { + idx++; + } + + int operand = Integer.parseInt(s.substring(start, idx)); + int prev = operands.removeLast(); + int result = calculate(prev, operand, op); + // 计算结果放在新的字符串首位,idx变成第一位 + // 比如 1*2+3 => 2+3 + s = result + s.substring(idx); + idx = 0; + } else if (idx < s.length() && (s.charAt(idx) == '+' || s.charAt(idx) == '-')) { + // 如果是加减 + operators.addLast(s.charAt(idx)); + idx++; + } else { + idx++; + } + } + + while (!operators.isEmpty()) { + int a = operands.removeFirst(); + int b = operands.removeFirst(); + int r = calculate(a, b, operators.removeFirst()); + operands.addFirst(r); + } + + return operands.getLast(); + } + + private int calculate(int a, int b, char op) { + switch (op) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + return a / b; + default: + return 0; + } + } +} diff --git a/[0228][Summary Ranges]/[0228][Summary Ranges].iml b/[0228][Summary Ranges]/[0228][Summary Ranges].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0228][Summary Ranges]/[0228][Summary Ranges].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0228][Summary Ranges]/src/Main.java b/[0228][Summary Ranges]/src/Main.java new file mode 100644 index 0000000..528c00e --- /dev/null +++ b/[0228][Summary Ranges]/src/Main.java @@ -0,0 +1,24 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 13:47 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] arr = {0, 1, 2, 4, 5, 7}; + Assert.assertEquals(Arrays.asList("0->2", "4->5", "7"), solution.summaryRanges(arr)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + int[] arr = {0, 2, 3, 4, 6, 8, 9}; + Assert.assertEquals(Arrays.asList("0", "2->4", "6", "8->9"), solution.summaryRanges(arr)); + } +} diff --git a/[0228][Summary Ranges]/src/Solution.java b/[0228][Summary Ranges]/src/Solution.java new file mode 100644 index 0000000..3fceab0 --- /dev/null +++ b/[0228][Summary Ranges]/src/Solution.java @@ -0,0 +1,37 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 13:41 + **/ +public class Solution { + public List summaryRanges(int[] nums) { + List result = new LinkedList<>(); + + if (nums == null || nums.length < 1) { + return result; + } + + int idx = 0; + + while (idx < nums.length) { + int temp = idx; + String s = String.valueOf(nums[idx]); + idx++; + // 找第一个不连续的下标 + while (idx < nums.length && nums[idx - 1] + 1 == nums[idx]) { + idx++; + } + + // 判断是否连续 + if (temp < idx - 1) { + result.add(s + "->" + nums[idx - 1]); + } else { + result.add(s); + } + } + + return result; + } +} diff --git a/[0230][Kth Smallest Element in a BST]/[0230][Kth Smallest Element in a BST].iml b/[0230][Kth Smallest Element in a BST]/[0230][Kth Smallest Element in a BST].iml new file mode 100644 index 0000000..e62ca95 --- /dev/null +++ b/[0230][Kth Smallest Element in a BST]/[0230][Kth Smallest Element in a BST].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0230][Kth Smallest Element in a BST]/src/Main.java b/[0230][Kth Smallest Element in a BST]/src/Main.java new file mode 100644 index 0000000..2ad78c0 --- /dev/null +++ b/[0230][Kth Smallest Element in a BST]/src/Main.java @@ -0,0 +1,21 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-01 17:42 + **/ +public class Main { + @Test + public void test1() { + TreeNode root = new TreeNode(3); + root.left = new TreeNode(1); + root.left.right = new TreeNode(2); + root.right = new TreeNode(4); + Solution solution = new Solution(); + Assert.assertEquals(1, solution.kthSmallest(root, 1)); + Assert.assertEquals(2, solution.kthSmallest(root, 2)); + Assert.assertEquals(3, solution.kthSmallest(root, 3)); + Assert.assertEquals(4, solution.kthSmallest(root, 4)); + } +} diff --git a/[0230][Kth Smallest Element in a BST]/src/Solution.java b/[0230][Kth Smallest Element in a BST]/src/Solution.java new file mode 100644 index 0000000..134eff2 --- /dev/null +++ b/[0230][Kth Smallest Element in a BST]/src/Solution.java @@ -0,0 +1,37 @@ +import java.util.Deque; +import java.util.LinkedList; +import java.util.NoSuchElementException; + +public class Solution { + + public int kthSmallest(TreeNode root, int k) { + + int count = 0; + Deque deque = new LinkedList<>(); + + deque.addLast(root); + // 用于记录下一个需要开始遍历的结点 + TreeNode node = root; + while (node != null || !deque.isEmpty()) { + // 找最左节点 + while (node != null) { + deque.addLast(node); + node = node.left; + } + + // 如果还有结点,就出栈 + if (!deque.isEmpty()) { + node = deque.removeLast(); + count++; + if (count == k) { + return node.val; + } + + // 记录下一个待处理的节点 + node = node.right; + } + } + + throw new NoSuchElementException(); + } +} \ No newline at end of file diff --git a/[0230][Kth Smallest Element in a BST]/src/TreeNode.java b/[0230][Kth Smallest Element in a BST]/src/TreeNode.java new file mode 100644 index 0000000..73c7ed9 --- /dev/null +++ b/[0230][Kth Smallest Element in a BST]/src/TreeNode.java @@ -0,0 +1,15 @@ +/** + * Author: + * Date: 2015-06-18 + * Time: 10:02 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0231][Power of Two]/[0231][Power of Two].iml b/[0231][Power of Two]/[0231][Power of Two].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0231][Power of Two]/[0231][Power of Two].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0231][Power of Two]/src/Solution.java b/[0231][Power of Two]/src/Solution.java new file mode 100644 index 0000000..dee3309 --- /dev/null +++ b/[0231][Power of Two]/src/Solution.java @@ -0,0 +1,28 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 09:24 + **/ +public class Solution { + public boolean isPowerOfTwo(int n) { + if (n < 1) { + return false; + } + + int remainder; + boolean result = false; + while (n > 0) { + // 求余数 + remainder = n % 2; + n >>>= 1; + + if (n == 0 && remainder == 1) { + result = true; + break; + } else if (n > 0 && remainder == 1) { + break; + } + } + + return result; + } +} diff --git a/[0231][Power of Two]/src/Test.java b/[0231][Power of Two]/src/Test.java new file mode 100644 index 0000000..0b8841a --- /dev/null +++ b/[0231][Power of Two]/src/Test.java @@ -0,0 +1,16 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 09:28 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + System.out.println(solution.isPowerOfTwo(-1)); + System.out.println(solution.isPowerOfTwo(0)); + System.out.println(solution.isPowerOfTwo(1)); + System.out.println(solution.isPowerOfTwo(2)); + System.out.println(solution.isPowerOfTwo(16)); + System.out.println(solution.isPowerOfTwo(218)); + } +} diff --git a/[0232][Implement Queue using Stacks]/[0232][Implement Queue using Stacks].iml b/[0232][Implement Queue using Stacks]/[0232][Implement Queue using Stacks].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0232][Implement Queue using Stacks]/[0232][Implement Queue using Stacks].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0232][Implement Queue using Stacks]/src/MyQueue.java b/[0232][Implement Queue using Stacks]/src/MyQueue.java new file mode 100644 index 0000000..25f2f3c --- /dev/null +++ b/[0232][Implement Queue using Stacks]/src/MyQueue.java @@ -0,0 +1,55 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 09:37 + **/ +class MyQueue { + + private List list; + + /** + * Initialize your data structure here. + */ + public MyQueue() { + list = new LinkedList<>(); + } + + /** + * Push element x to the back of queue. + */ + public void push(int x) { + list.add(x); + } + + /** + * Removes the element from in front of queue and returns that element. + */ + public int pop() { + return list.remove(0); + } + + /** + * Get the front element. + */ + public int peek() { + return list.get(0); + } + + /** + * Returns whether the queue is empty. + */ + public boolean empty() { + return list.isEmpty(); + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ diff --git a/[0232][Implement Queue using Stacks]/src/Test.java b/[0232][Implement Queue using Stacks]/src/Test.java new file mode 100644 index 0000000..4adabf6 --- /dev/null +++ b/[0232][Implement Queue using Stacks]/src/Test.java @@ -0,0 +1,15 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 10:58 + **/ +public class Test { + public static void main(String[] args) { + MyQueue queue = new MyQueue(); + queue.push(1); + queue.push(2); + + System.out.println(queue.peek()); + System.out.println(queue.pop()); + System.out.println(queue.empty()); + } +} diff --git a/[0234][Palindrome Linked List]/[0234][Palindrome Linked List].iml b/[0234][Palindrome Linked List]/[0234][Palindrome Linked List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0234][Palindrome Linked List]/[0234][Palindrome Linked List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0234][Palindrome Linked List]/src/ListNode.java b/[0234][Palindrome Linked List]/src/ListNode.java new file mode 100644 index 0000000..4d4fcb5 --- /dev/null +++ b/[0234][Palindrome Linked List]/src/ListNode.java @@ -0,0 +1,12 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 11:03 + **/ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } +} diff --git a/[0234][Palindrome Linked List]/src/Solution.java b/[0234][Palindrome Linked List]/src/Solution.java new file mode 100644 index 0000000..65ba7ea --- /dev/null +++ b/[0234][Palindrome Linked List]/src/Solution.java @@ -0,0 +1,58 @@ +/** + * O(n) time and O(1) space + *
+ * 1->2->2->1
+ * 1->2->3->2->1
+ * 先找到第二个2的位置,将2及后面的链逆转,形成新的链A,再按A与原来的链,从头开开始比较
+ * 
+ * + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 11:02 + **/ +public class Solution { + public boolean isPalindrome(ListNode head) { + + // 没有节点或者只有一个结点 + if (head == null || head.next == null) { + return true; + } + + int count = 0; + ListNode node = head; + while (node != null) { + count++; + node = node.next; + } + + // 找反向链的起始位置 + count = (count + 1) / 2; + node = head; + while (count > 0) { + count--; + node = node.next; + } + + + ListNode reverseHead = new ListNode(0); + ListNode temp; + while (node != null) { + temp = node.next; + node.next = reverseHead.next; + reverseHead.next = node; + node = temp; + } + + reverseHead = reverseHead.next; + + while (reverseHead != null) { + if (head.val != reverseHead.val) { + return false; + } + + reverseHead = reverseHead.next; + head = head.next; + } + + return true; + } +} diff --git a/[0234][Palindrome Linked List]/src/Solution2.java b/[0234][Palindrome Linked List]/src/Solution2.java new file mode 100644 index 0000000..f6138f7 --- /dev/null +++ b/[0234][Palindrome Linked List]/src/Solution2.java @@ -0,0 +1,38 @@ +/** + * O(n) time and O(n) space + * + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 11:02 + **/ +public class Solution2 { + public boolean isPalindrome(ListNode head) { + + if (head == null) { + return true; + } + + // 反向链的头 + ListNode reverseHead = new ListNode(-1); + + ListNode temp = head; + ListNode node; + // 头插法构建反向链 + while (temp != null) { + node = new ListNode(temp.val); + node.next = reverseHead.next; + reverseHead.next = node; + temp = temp.next; + } + + reverseHead = reverseHead.next; + while (head != null) { + if (head.val != reverseHead.val) { + return false; + } + + head = head.next; + reverseHead = reverseHead.next; + } + return true; + } +} diff --git a/[0234][Palindrome Linked List]/src/Test.java b/[0234][Palindrome Linked List]/src/Test.java new file mode 100644 index 0000000..28f5ec5 --- /dev/null +++ b/[0234][Palindrome Linked List]/src/Test.java @@ -0,0 +1,42 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 11:10 + **/ +public class Test { + public static void main(String[] args) { + test1(); + test2(); + test3(); + } + + public static void test1() { + Solution solution = new Solution(); + ListNode head = new ListNode(1); + head.next = new ListNode(2); + System.out.println(solution.isPalindrome(head)); + } + + public static void test2() { + Solution solution = new Solution(); + + ListNode head = new ListNode(1); + head.next = new ListNode(2); + head.next.next = new ListNode(2); + head.next.next.next = new ListNode(1); + head.next.next.next.next = new ListNode(2); + head.next.next.next.next.next = new ListNode(2); + head.next.next.next.next.next.next = new ListNode(1); + System.out.println(solution.isPalindrome(head)); + } + + public static void test3() { + Solution solution = new Solution(); + + ListNode head = new ListNode(1); + head.next = new ListNode(2); + head.next.next = new ListNode(2); + head.next.next.next = new ListNode(1); + + System.out.println(solution.isPalindrome(head)); + } +} diff --git a/[0235][Lowest Common Ancestor of a Binary Search Tree]/[0235][Lowest Common Ancestor of a Binary Search Tree].iml b/[0235][Lowest Common Ancestor of a Binary Search Tree]/[0235][Lowest Common Ancestor of a Binary Search Tree].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0235][Lowest Common Ancestor of a Binary Search Tree]/[0235][Lowest Common Ancestor of a Binary Search Tree].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0235][Lowest Common Ancestor of a Binary Search Tree]/src/Solution.java b/[0235][Lowest Common Ancestor of a Binary Search Tree]/src/Solution.java new file mode 100644 index 0000000..632cf2f --- /dev/null +++ b/[0235][Lowest Common Ancestor of a Binary Search Tree]/src/Solution.java @@ -0,0 +1,56 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * Definition for a binary tree node. + *
+ * public class TreeNode {
+ *      int val;
+ *      TreeNode left;
+ *      TreeNode right;
+ *      TreeNode(int x) { val = x; }
+ * }
+ * 
+ * + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 11:32 + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + + List pPath = new ArrayList<>(); + List qPath = new ArrayList<>(); + + search(pPath, root, p); + search(qPath, root, q); + + TreeNode ancestor = pPath.get(0); + + int idx = 1; + while (idx < pPath.size() && idx < qPath.size()) { + p = pPath.get(idx); + q = qPath.get(idx); + if (p != null && q != null && p.val == q.val) { + ancestor = pPath.get(idx); + idx++; + } else { + break; + } + } + + return ancestor; + } + + public void search(List path, TreeNode root, TreeNode node) { + path.add(root); + + if (root != null) { + if (root.val > node.val) { + search(path, root.left, node); + } + if (root.val < node.val) { + search(path, root.right, node); + } + } + } +} diff --git a/[0235][Lowest Common Ancestor of a Binary Search Tree]/src/TreeNode.java b/[0235][Lowest Common Ancestor of a Binary Search Tree]/src/TreeNode.java new file mode 100644 index 0000000..141d430 --- /dev/null +++ b/[0235][Lowest Common Ancestor of a Binary Search Tree]/src/TreeNode.java @@ -0,0 +1,13 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-09 11:33 + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0237][Delete Node in a Linked List]/[0237][Delete Node in a Linked List].iml b/[0237][Delete Node in a Linked List]/[0237][Delete Node in a Linked List].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0237][Delete Node in a Linked List]/[0237][Delete Node in a Linked List].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0237][Delete Node in a Linked List]/src/ListNode.java b/[0237][Delete Node in a Linked List]/src/ListNode.java new file mode 100644 index 0000000..9e0f1da --- /dev/null +++ b/[0237][Delete Node in a Linked List]/src/ListNode.java @@ -0,0 +1,12 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 09:58 + **/ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } +} diff --git a/[0237][Delete Node in a Linked List]/src/Solution.java b/[0237][Delete Node in a Linked List]/src/Solution.java new file mode 100644 index 0000000..6c60753 --- /dev/null +++ b/[0237][Delete Node in a Linked List]/src/Solution.java @@ -0,0 +1,32 @@ +/** + *
+ * Definition for singly-linked list.
+ * public class ListNode {
+ *     int val;
+ *     ListNode next;
+ *     ListNode(int x) { val = x; }
+ * }
+ * 
+ * + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 09:57 + **/ +class Solution { + public void deleteNode(ListNode node) { + + if (node == null || node.next == null) { + return; + } + + ListNode prev = node; + while (node.next != null) { + node.val = node.next.val; + prev = node; + node = node.next; + + + } + + prev.next = null; + } +} \ No newline at end of file diff --git a/[0237][Delete Node in a Linked List]/src/Test.java b/[0237][Delete Node in a Linked List]/src/Test.java new file mode 100644 index 0000000..a6ee290 --- /dev/null +++ b/[0237][Delete Node in a Linked List]/src/Test.java @@ -0,0 +1,32 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 10:01 + **/ +public class Test { + public static void main(String[] args) { + ListNode node = new ListNode(4); + node.next = new ListNode(5); + node.next.next = new ListNode(1); + node.next.next.next = new ListNode(9); + + Solution solution = new Solution(); + solution.deleteNode(node.next); + + print(node); + } + + private static void print(ListNode node) { + do { + if (node == null) { + System.out.println("null"); + } else if (node.next != null) { + System.out.print(node.val + "->"); + node = node.next; + } else { + System.out.println(node.val + "->null"); + node = node.next; + } + + } while (node != null); + } +} diff --git a/[0238][Product of Array Except Self]/[0238][Product of Array Except Self].iml b/[0238][Product of Array Except Self]/[0238][Product of Array Except Self].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0238][Product of Array Except Self]/[0238][Product of Array Except Self].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0238][Product of Array Except Self]/src/Main.java b/[0238][Product of Array Except Self]/src/Main.java new file mode 100644 index 0000000..b2097c4 --- /dev/null +++ b/[0238][Product of Array Except Self]/src/Main.java @@ -0,0 +1,26 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 14:31 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{24, 12, 8, 6}, solution.productExceptSelf(new int[]{1, 2, 3, 4})); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{0, 0}, solution.productExceptSelf(new int[]{0, 0})); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{1, 0}, solution.productExceptSelf(new int[]{0, 1})); + } +} diff --git a/[0238][Product of Array Except Self]/src/Solution.java b/[0238][Product of Array Except Self]/src/Solution.java new file mode 100644 index 0000000..e0c6b32 --- /dev/null +++ b/[0238][Product of Array Except Self]/src/Solution.java @@ -0,0 +1,71 @@ +import java.util.HashSet; +import java.util.Set; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 14:29 + **/ +public class Solution { + /** + *
+     * Given an array nums of n integers where n > 1,
+     * return an array output such that output[i] is equal to the product of all the
+     * elements of nums except nums[i].
+     *
+     * Example:
+     *
+     * Input:  [1,2,3,4]
+     * Output: [24,12,8,6]
+     * Note: Please solve it without division and in O(n).
+     *
+     * Follow up:
+     * Could you solve it with constant space complexity? (The output array does not count as
+     * extra space for the purpose of space complexity analysis.)
+     * 
+ * + * @param nums + * @return + */ + public int[] productExceptSelf(int[] nums) { + int[] result = new int[nums.length]; + + // 记录为0的下票 + Set zero = new HashSet<>(); + + + long product = 1; + for (int i = 0; i < nums.length; i++) { + product *= nums[i]; + if (nums[i] == 0) { + zero.add(i); + } + } + + // 0的个数大于1个 + if (zero.size() > 1) { + return result; + } else if (zero.size() == 1) { + int firstZeroIndex = 0; + for (Integer i : zero) { + firstZeroIndex = i; + } + + result[firstZeroIndex] = 1; + for (int i = 0; i < nums.length; i++) { + if (i != firstZeroIndex) { + result[firstZeroIndex] *= nums[i]; + } + } + + return result; + } else { + // 没有0 + for (int i = 0; i < nums.length; i++) { + result[i] = (int) (product / nums[i]); + } + + return result; + } + + } +} diff --git a/[0240][Search a 2D Matrix II]/[0240][Search a 2D Matrix II].iml b/[0240][Search a 2D Matrix II]/[0240][Search a 2D Matrix II].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0240][Search a 2D Matrix II]/[0240][Search a 2D Matrix II].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0240][Search a 2D Matrix II]/src/Main.java b/[0240][Search a 2D Matrix II]/src/Main.java new file mode 100644 index 0000000..33fcd80 --- /dev/null +++ b/[0240][Search a 2D Matrix II]/src/Main.java @@ -0,0 +1,23 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 20:12 + **/ +public class Main { + @Test + public void test1() { + int[][] matrix = { + {1, 4, 7, 11, 15}, + {2, 5, 8, 12, 19}, + {3, 6, 9, 16, 22}, + {10, 13, 14, 17, 24}, + {18, 21, 23, 26, 30} + }; + Solution solution = new Solution(); + + Assert.assertEquals(true, solution.searchMatrix(matrix, 5)); + Assert.assertEquals(false, solution.searchMatrix(matrix, 20)); + } +} diff --git a/[0240][Search a 2D Matrix II]/src/Solution.java b/[0240][Search a 2D Matrix II]/src/Solution.java new file mode 100644 index 0000000..4b780fe --- /dev/null +++ b/[0240][Search a 2D Matrix II]/src/Solution.java @@ -0,0 +1,53 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 20:06 + **/ +public class Solution { + /** + *
+     * Write an efficient algorithm that searches for a value in an m x n matrix.
+     * This matrix has the following properties:
+     *
+     * Integers in each row are sorted in ascending from left to right.
+     * Integers in each column are sorted in ascending from top to bottom.
+     * Example:
+     *
+     * Consider the following matrix:
+     *
+     * [
+     *   [1,   4,  7, 11, 15],
+     *   [2,   5,  8, 12, 19],
+     *   [3,   6,  9, 16, 22],
+     *   [10, 13, 14, 17, 24],
+     *   [18, 21, 23, 26, 30]
+     * ]
+     * Given target = 5, return true.
+     *
+     * Given target = 20, return false.
+     * 
+ * + * @param matrix + * @param target + * @return + */ + public boolean searchMatrix(int[][] matrix, int target) { + + if (matrix == null || matrix.length == 0) { + return false; + } + + int i = 0; + int j = matrix[0].length - 1; + while (i < matrix.length && j > -1) { + if (matrix[i][j] == target) { + return true; + } else if (target < matrix[i][j]) { + j--; + } else { + i++; + } + } + + return false; + } +} diff --git a/[0241][Different Ways to Add Parentheses]/[0241][Different Ways to Add Parentheses].iml b/[0241][Different Ways to Add Parentheses]/[0241][Different Ways to Add Parentheses].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0241][Different Ways to Add Parentheses]/[0241][Different Ways to Add Parentheses].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0241][Different Ways to Add Parentheses]/src/Main.java b/[0241][Different Ways to Add Parentheses]/src/Main.java new file mode 100644 index 0000000..e2c34b5 --- /dev/null +++ b/[0241][Different Ways to Add Parentheses]/src/Main.java @@ -0,0 +1,25 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 20:59 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + System.out.println(solution.diffWaysToCompute("2-1-1")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + System.out.println(solution.diffWaysToCompute("2*3-4*5")); + } + + @Test + public void test3() { + Solution solution = new Solution(); + System.out.println(solution.diffWaysToCompute("2")); + } +} diff --git a/[0241][Different Ways to Add Parentheses]/src/Solution.java b/[0241][Different Ways to Add Parentheses]/src/Solution.java new file mode 100644 index 0000000..d996d4c --- /dev/null +++ b/[0241][Different Ways to Add Parentheses]/src/Solution.java @@ -0,0 +1,113 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 20:25 + **/ +public class Solution { + /** + *
+     * Given a string of numbers and operators, return all possible results from computing all the
+     * different possible ways to group numbers and operators. The valid operators are +, - and *.
+     *
+     * Example 1:
+     *
+     * Input: "2-1-1"
+     * Output: [0, 2]
+     * Explanation:
+     * ((2-1)-1) = 0
+     * (2-(1-1)) = 2
+     * Example 2:
+     *
+     * Input: "2*3-4*5"
+     * Output: [-34, -14, -10, -10, 10]
+     * Explanation:
+     * (2*(3-(4*5))) = -34
+     * ((2*3)-(4*5)) = -14
+     * ((2*(3-4))*5) = -10
+     * (2*((3-4)*5)) = -10
+     * (((2*3)-4)*5) = 10
+     * 
+ * + * @param input + * @return + */ + public List diffWaysToCompute(String input) { + List operator = new ArrayList<>(); + List operand = new ArrayList<>(); + + int start = 0; + int end; + while (start < input.length()) { + end = start + 1; + while (end < input.length() + && input.charAt(end) >= '0' + && input.charAt(end) <= '9') { + end++; + } + operand.add(Integer.parseInt(input.substring(start, end))); + + if (end < input.length()) { + operator.add(input.charAt(end)); + } + start = end + 1; + } + + return diffWaysToCompute(operand, operator); + } + + /** + * @param operand + * @param operator + * @return + */ + private List diffWaysToCompute(List operand, List operator) { + + List result = new LinkedList<>(); + + if (operator.isEmpty()) { + result.addAll(operand); + return result; + } + + + if (operator.size() == 1) { + result.add(calculate(operand.get(0), operand.get(1), operator.get(0))); + return result; + } + + for (int i = 0; i < operator.size(); i++) { + List left = diffWaysToCompute( + new ArrayList<>(operand.subList(0, i + 1)), + new ArrayList<>(operator.subList(0, i))); + List right = diffWaysToCompute( + new ArrayList<>(operand.subList(i + 1, operand.size())), + new ArrayList<>(operator.subList(i + 1, operator.size()))); + + for (int x : left) { + for (int y : right) { + result.add(calculate(x, y, operator.get(i))); + } + } + } + + return result; + + } + + private Integer calculate(Integer a, Integer b, Character op) { + + switch (op) { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + default: + throw new RuntimeException("no such " + a + op + b + " option exception"); + } + } +} diff --git a/[0242][Valid Anagram]/[0242][Valid Anagram].iml b/[0242][Valid Anagram]/[0242][Valid Anagram].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0242][Valid Anagram]/[0242][Valid Anagram].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0242][Valid Anagram]/src/Solution.java b/[0242][Valid Anagram]/src/Solution.java new file mode 100644 index 0000000..ace39c8 --- /dev/null +++ b/[0242][Valid Anagram]/src/Solution.java @@ -0,0 +1,48 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 10:28 + **/ +public class Solution { + public boolean isAnagram(String s, String t) { + + if (s == null && t == null) { + return true; + } else if (s == null || t == null) { + return false; + } + + Map map = new HashMap<>(); + + for (int i = 0; i < s.length(); i++) { + Character c = s.charAt(i); + if (map.containsKey(c)) { + map.put(c, map.get(c) + 1); + } else { + map.put(c, 1); + } + } + + for (int i = 0; i < t.length(); i++) { + Character c = t.charAt(i); + Integer count = map.get(c); + // t有s中不包含的字符串 + if (count == null) { + return false; + } else { + map.put(c, count - 1); + } + } + + // map中的值有非0的说明不合法 + for (Integer i : map.values()) { + if (i != 0) { + return false; + } + } + + return true; + } +} diff --git a/[0242][Valid Anagram]/src/Test.java b/[0242][Valid Anagram]/src/Test.java new file mode 100644 index 0000000..5282683 --- /dev/null +++ b/[0242][Valid Anagram]/src/Test.java @@ -0,0 +1,12 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 10:35 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + System.out.println(solution.isAnagram("anagram", "nagaram")); + System.out.println(solution.isAnagram("rat", "car")); + } +} diff --git a/[0257][Binary Tree Paths]/[0257][Binary Tree Paths].iml b/[0257][Binary Tree Paths]/[0257][Binary Tree Paths].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0257][Binary Tree Paths]/[0257][Binary Tree Paths].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0257][Binary Tree Paths]/src/Solution.java b/[0257][Binary Tree Paths]/src/Solution.java new file mode 100644 index 0000000..6480a96 --- /dev/null +++ b/[0257][Binary Tree Paths]/src/Solution.java @@ -0,0 +1,56 @@ +import java.util.LinkedList; +import java.util.List; + +/** + *
+ * Definition for a binary tree node.
+ * public class TreeNode {
+ *     int val;
+ *     TreeNode left;
+ *     TreeNode right;
+ *     TreeNode(int x) { val = x; }
+ * }
+ * 
+ * + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 11:16 + **/ +public class Solution { + public List binaryTreePaths(TreeNode root) { + List result = new LinkedList<>(); + binaryTreePaths(root, new LinkedList<>(), result); + + return result; + } + + private void binaryTreePaths(TreeNode root, LinkedList path, List result) { + + if (root == null) { + return; + } + + path.add(root); + + if (root.left == null && root.right == null) { + addResult(path, result); + } else { + binaryTreePaths(root.left, path, result); + binaryTreePaths(root.right, path, result); + } + + path.remove(path.size() - 1); + } + + private void addResult(LinkedList path, List result) { + StringBuilder builder = new StringBuilder(); + if (path != null) { + for (TreeNode node : path) { + builder.append("->").append(node.val); + } + } + + if (builder.length() > 0) { + result.add(builder.substring(2)); + } + } +} diff --git a/[0257][Binary Tree Paths]/src/Test.java b/[0257][Binary Tree Paths]/src/Test.java new file mode 100644 index 0000000..318a15c --- /dev/null +++ b/[0257][Binary Tree Paths]/src/Test.java @@ -0,0 +1,16 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 11:25 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.right = new TreeNode(5); + + System.out.println(solution.binaryTreePaths(root)); + } +} diff --git a/[0257][Binary Tree Paths]/src/TreeNode.java b/[0257][Binary Tree Paths]/src/TreeNode.java new file mode 100644 index 0000000..2e248fe --- /dev/null +++ b/[0257][Binary Tree Paths]/src/TreeNode.java @@ -0,0 +1,15 @@ +/** + * Author: 王俊超 + * Date: 2015-06-18 + * Time: 10:02 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0258][Add Digits]/[0258][Add Digits].iml b/[0258][Add Digits]/[0258][Add Digits].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0258][Add Digits]/[0258][Add Digits].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0258][Add Digits]/src/Solution.java b/[0258][Add Digits]/src/Solution.java new file mode 100644 index 0000000..ff595f5 --- /dev/null +++ b/[0258][Add Digits]/src/Solution.java @@ -0,0 +1,27 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 13:28 + **/ +public class Solution { + public int addDigits(int num) { + + if (num < 0) { + throw new IllegalArgumentException("input num :" + num + ", must not be negative"); + } + + int result = 0; + + while (num > 0) { + result += num % 10; + num /= 10; + + // 需要重新进行位相加 + if (num == 0 && result > 9) { + num = result; + result = 0; + } + } + + return result; + } +} diff --git a/[0258][Add Digits]/src/Test.java b/[0258][Add Digits]/src/Test.java new file mode 100644 index 0000000..d3afaa3 --- /dev/null +++ b/[0258][Add Digits]/src/Test.java @@ -0,0 +1,13 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 13:35 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + System.out.println(solution.addDigits(38)); + System.out.println(solution.addDigits(999999999)); + System.out.println(solution.addDigits(100000000)); + } +} diff --git a/[0260][Single Number III]/[0260][Single Number III].iml b/[0260][Single Number III]/[0260][Single Number III].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0260][Single Number III]/[0260][Single Number III].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0260][Single Number III]/src/Main.java b/[0260][Single Number III]/src/Main.java new file mode 100644 index 0000000..4341777 --- /dev/null +++ b/[0260][Single Number III]/src/Main.java @@ -0,0 +1,17 @@ +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 18:56 + **/ +public class Main { + @Test + public void test1() { + + Solution solution = new Solution(); + int[] diff = solution.singleNumber(new int[]{1, 2, 1, 3, 2, 5}); + System.out.println(Arrays.toString(diff)); + } +} diff --git a/[0260][Single Number III]/src/Solution.java b/[0260][Single Number III]/src/Solution.java new file mode 100644 index 0000000..03c702c --- /dev/null +++ b/[0260][Single Number III]/src/Solution.java @@ -0,0 +1,51 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 18:46 + **/ +public class Solution { + /** + *
+     * Given an array of numbers nums, in which exactly two elements appear only
+     * once and all the other elements appear exactly twice. Find the two elements that appear only once.
+     *
+     * Example:
+     *
+     * Input:  [1,2,1,3,2,5]
+     * Output: [3,5]
+     * Note:
+     *
+     * The order of the result is not important. So in the above example, [5, 3] is also correct.
+     * Your algorithm should run in linear runtime complexity. Could you implement it using
+     * only constant space complexity?
+     * 
+ * + * @param nums + * @return + */ + public int[] singleNumber(int[] nums) { + int xor = nums[0]; + for (int i = 1; i < nums.length; i++) { + xor ^= nums[i]; + } + + int temp = xor; + int count = 0; + while ((1 & (temp % 2)) != 1) { + count++; + temp >>>= 1; + } + + int x = 0; + int y = 0; + + for (int i : nums) { + if (((i >> count) & 1) == 1) { + x ^= i; + } else { + y ^= i; + } + } + + return new int[]{x, y}; + } +} diff --git a/[0263][Ugly Number]/[0263][Ugly Number].iml b/[0263][Ugly Number]/[0263][Ugly Number].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0263][Ugly Number]/[0263][Ugly Number].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0263][Ugly Number]/src/Solution.java b/[0263][Ugly Number]/src/Solution.java new file mode 100644 index 0000000..a05b03c --- /dev/null +++ b/[0263][Ugly Number]/src/Solution.java @@ -0,0 +1,28 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 13:45 + **/ +public class Solution { + public boolean isUgly(int num) { + + if (num < 1) { + return false; + } else if (num == 1) { + return true; + } + + while ((num % 2) == 0) { + num /= 2; + } + + while ((num % 3) == 0) { + num /= 3; + } + + while ((num % 5) == 0) { + num /= 5; + } + + return num == 1; + } +} diff --git a/[0263][Ugly Number]/src/Test.java b/[0263][Ugly Number]/src/Test.java new file mode 100644 index 0000000..dccb247 --- /dev/null +++ b/[0263][Ugly Number]/src/Test.java @@ -0,0 +1,16 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 13:50 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + System.out.println(solution.isUgly(-1)); + System.out.println(solution.isUgly(0)); + System.out.println(solution.isUgly(1)); + System.out.println(solution.isUgly(6)); + System.out.println(solution.isUgly(8)); + System.out.println(solution.isUgly(14)); + } +} diff --git a/[0268][Missing Number]/[0268][Missing Number].iml b/[0268][Missing Number]/[0268][Missing Number].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0268][Missing Number]/[0268][Missing Number].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0268][Missing Number]/src/Solution.java b/[0268][Missing Number]/src/Solution.java new file mode 100644 index 0000000..0ad6903 --- /dev/null +++ b/[0268][Missing Number]/src/Solution.java @@ -0,0 +1,39 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 14:02 + **/ +public class Solution { + public int missingNumber(int[] nums) { + + if (nums == null || nums.length < 1) { + throw new IllegalArgumentException("array should contain at least one element"); + } + + for (int i = 0; i < nums.length; i++) { + // 只会存在一个大于nums.length的数,将其放在数组最后一个位置 + if (nums[i] > nums.length) { + swap(nums, i, nums.length - 1); + } + + // 交换位置,直到nums[i] = i + while (nums[i] != i && nums[i] < nums.length) { + swap(nums, i, nums[i]); + } + } + + // 找出丢失的元素 + for (int i = 0; i < nums.length; i++) { + if (nums[i] != i) { + return i; + } + } + + return nums.length; + } + + private void swap(int[] nums, int x, int y) { + int temp = nums[x]; + nums[x] = nums[y]; + nums[y] = temp; + } +} diff --git a/[0268][Missing Number]/src/Test.java b/[0268][Missing Number]/src/Test.java new file mode 100644 index 0000000..a4452e8 --- /dev/null +++ b/[0268][Missing Number]/src/Test.java @@ -0,0 +1,21 @@ +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 14:14 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + missingNumber(solution, new int[]{0}); + missingNumber(solution, new int[]{3, 0, 1}); + missingNumber(solution, new int[]{9, 6, 4, 2, 3, 5, 7, 0, 1}); + missingNumber(solution, new int[]{8, 6, 4, 2, 3, 5, 7, 0, 1}); + } + + private static void missingNumber(Solution solution, int[] array) { + System.out.println(solution.missingNumber(array)); + System.out.println(Arrays.toString(array)); + } +} diff --git a/[0278][First Bad Version]/[0278][First Bad Version].iml b/[0278][First Bad Version]/[0278][First Bad Version].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0278][First Bad Version]/[0278][First Bad Version].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0278][First Bad Version]/src/Solution.java b/[0278][First Bad Version]/src/Solution.java new file mode 100644 index 0000000..2f344d1 --- /dev/null +++ b/[0278][First Bad Version]/src/Solution.java @@ -0,0 +1,39 @@ +/** + *
+ * The isBadVersion API is defined in the parent class VersionControl.
+ *       boolean isBadVersion(int version);
+ * 
+ * + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 14:26 + **/ +public class Solution extends VersionControl { + public int firstBadVersion(int n) { + + if (!isBadVersion(n)) { + return 0; + } + + int hi = n; + int lo = 1; + int mid; + + while (hi >= lo) { + mid = lo + (hi - lo) / 2; + if (isBadVersion(mid)) { + // 当前是1号版本,或者前一个是合法版本,那么当前版本就是第一个非法的版本 + if (mid == 1 || (mid > 1 && !isBadVersion(mid - 1))) { + return mid; + } else { + // 非法的版本在[lo, mid-1]间 + hi = mid - 1; + } + } else { + // 非法版本在[mid + 1, hi]间 + lo = mid + 1; + } + } + + return 0; + } +} diff --git a/[0278][First Bad Version]/src/Test.java b/[0278][First Bad Version]/src/Test.java new file mode 100644 index 0000000..3a57cd6 --- /dev/null +++ b/[0278][First Bad Version]/src/Test.java @@ -0,0 +1,12 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 16:55 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + solution.setBadVersion(new boolean[]{false, false, false, true, true}); + System.out.println(solution.firstBadVersion(5)); + } +} diff --git a/[0278][First Bad Version]/src/VersionControl.java b/[0278][First Bad Version]/src/VersionControl.java new file mode 100644 index 0000000..327bc14 --- /dev/null +++ b/[0278][First Bad Version]/src/VersionControl.java @@ -0,0 +1,20 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 14:27 + **/ +public class VersionControl { + + private boolean[] badVersion; + + public boolean isBadVersion(int version) { + return badVersion[version - 1]; + } + + public boolean[] getBadVersion() { + return badVersion; + } + + public void setBadVersion(boolean[] badVersion) { + this.badVersion = badVersion; + } +} diff --git a/[0283][Move Zeroes]/[0283][Move Zeroes].iml b/[0283][Move Zeroes]/[0283][Move Zeroes].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0283][Move Zeroes]/[0283][Move Zeroes].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0283][Move Zeroes]/src/Solution.java b/[0283][Move Zeroes]/src/Solution.java new file mode 100644 index 0000000..4afeb4a --- /dev/null +++ b/[0283][Move Zeroes]/src/Solution.java @@ -0,0 +1,44 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 17:04 + **/ +public class Solution { + public void moveZeroes(int[] nums) { + + if (nums == null || nums.length < 1) { + return; + } + + int idx = 0; + // 找第一个0的位置 + while (idx < nums.length && nums[idx] != 0) { + idx++; + } + + // 数组的值都非0 + if (idx >= nums.length) { + return; + } + + int temp = idx + 1; + + while (temp < nums.length) { + // 找temp开始第一个非0的位置 + while (temp < nums.length && nums[temp] == 0) { + temp++; + } + + // 找到非0值,移动到idx位置 + if (temp < nums.length) { + nums[idx] = nums[temp]; + idx++; + temp++; + } + } + + // 从[idx, nums.length-1]的长度都设置为0 + for (int i = idx; i < nums.length; i++) { + nums[i] = 0; + } + } +} diff --git a/[0283][Move Zeroes]/src/Test.java b/[0283][Move Zeroes]/src/Test.java new file mode 100644 index 0000000..1c5d20c --- /dev/null +++ b/[0283][Move Zeroes]/src/Test.java @@ -0,0 +1,20 @@ +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 17:11 + **/ +public class Test { + public static void main(String[] args) { + moveZeros(new int[]{0, 1, 0, 3, 12}); + moveZeros(new int[]{2, 1, 6, 3, 12}); + moveZeros(new int[]{2}); + moveZeros(new int[]{0}); + } + + private static void moveZeros(int[] a1) { + Solution solution = new Solution(); + solution.moveZeroes(a1); + System.out.println(Arrays.toString(a1)); + } +} diff --git a/[0287][Find the Duplicate Number]/[0287][Find the Duplicate Number].iml b/[0287][Find the Duplicate Number]/[0287][Find the Duplicate Number].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0287][Find the Duplicate Number]/[0287][Find the Duplicate Number].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0287][Find the Duplicate Number]/src/Main.java b/[0287][Find the Duplicate Number]/src/Main.java new file mode 100644 index 0000000..b69e3e5 --- /dev/null +++ b/[0287][Find the Duplicate Number]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 19:08 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(2, solution.findDuplicate(new int[]{1, 3, 4, 2, 2})); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(3, solution.findDuplicate(new int[]{3, 1, 3, 4, 2})); + } +} diff --git a/[0287][Find the Duplicate Number]/src/Solution.java b/[0287][Find the Duplicate Number]/src/Solution.java new file mode 100644 index 0000000..4ab1587 --- /dev/null +++ b/[0287][Find the Duplicate Number]/src/Solution.java @@ -0,0 +1,55 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 19:04 + **/ +public class Solution { + /** + *
+     * Given an array nums containing n + 1 integers where each integer is between 1
+     * and n (inclusive), prove that at least one duplicate number must exist. Assume
+     * that there is only one duplicate number, find the duplicate one.
+     *
+     * Example 1:
+     *
+     * Input: [1,3,4,2,2]
+     * Output: 2
+     * Example 2:
+     *
+     * Input: [3,1,3,4,2]
+     * Output: 3
+     * Note:
+     *
+     * You must not modify the array (assume the array is read only).
+     * You must use only constant, O(1) extra space.
+     * Your runtime complexity should be less than O(n2).
+     * There is only one duplicate number in the array, but it could be repeated more than once.
+     * 
+ * + * @param nums + * @return + */ + public int findDuplicate(int[] nums) { + + for (int i = 1; i <= nums.length; i++) { + // nums[i - 1] != i ; 当 num[8] = 9 的情况 + // nums[i - 1] != nums[nums[i - 1] - 1] ; 两个相同的数,位置被占用 + while (nums[i - 1] != i && nums[i - 1] != nums[nums[i - 1] - 1]) { + swap(nums, i - 1, nums[i - 1] - 1); + } + } + + for (int i = 1; i <= nums.length; i++) { + if (nums[i - 1] != i) { + return nums[i - 1]; + } + } + + return -1; + } + + private void swap(int[] nums, int x, int y) { + int temp = nums[x]; + nums[x] = nums[y]; + nums[y] = temp; + } +} diff --git a/[0290][Word Pattern]/[0290][Word Pattern].iml b/[0290][Word Pattern]/[0290][Word Pattern].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0290][Word Pattern]/[0290][Word Pattern].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0290][Word Pattern]/src/Solution.java b/[0290][Word Pattern]/src/Solution.java new file mode 100644 index 0000000..580d1c2 --- /dev/null +++ b/[0290][Word Pattern]/src/Solution.java @@ -0,0 +1,48 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 17:24 + **/ +public class Solution { + public boolean wordPattern(String pattern, String str) { + + if (pattern == null && str == null) { + return true; + } else if (pattern == null || str == null) { + return false; + } + + String[] parts = str.split("\\s+"); + + if (pattern.length() != parts.length) { + return false; + } + + Map map = new HashMap<>(); + Map rmap = new HashMap<>(); + + Character c; + for (int i = 0; i < pattern.length(); i++) { + c = pattern.charAt(i); + if (!map.containsKey(c)) { + map.put(c, parts[i]); + } else { + if (!parts[i].equals(map.get(c))) { + return false; + } + } + // 双射,两边都要验证 + if (!rmap.containsKey(parts[i])) { + rmap.put(parts[i], c); + } else { + if (!c.equals(rmap.get(parts[i]))) { + return false; + } + } + } + + return true; + } +} diff --git a/[0290][Word Pattern]/src/Test.java b/[0290][Word Pattern]/src/Test.java new file mode 100644 index 0000000..6c75500 --- /dev/null +++ b/[0290][Word Pattern]/src/Test.java @@ -0,0 +1,14 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-10 17:29 + **/ +public class Test { + public static void main(String[] args) { + Solution solution = new Solution(); + + System.out.println(solution.wordPattern("abba", "dog cat cat dog")); + System.out.println(solution.wordPattern("abba", "dog cat cat fish")); + System.out.println(solution.wordPattern("aaaa", "dog cat cat dog")); + System.out.println(solution.wordPattern("abba", "dog dog dog dog")); + } +} diff --git a/[0292][Nim Game]/[0292][Nim Game].iml b/[0292][Nim Game]/[0292][Nim Game].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0292][Nim Game]/[0292][Nim Game].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0292][Nim Game]/src/Solution.java b/[0292][Nim Game]/src/Solution.java new file mode 100644 index 0000000..a6fa330 --- /dev/null +++ b/[0292][Nim Game]/src/Solution.java @@ -0,0 +1,41 @@ +/** + * https://leetcode.com/problems/nim-game/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-08 18:39 + **/ +public class Solution { + /** + *
+     * You are playing the following Nim Game with your friend: There is a heap of stones on the table,
+     * each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will
+     * be the winner. You will take the first turn to remove the stones.
+     *
+     * Both of you are very clever and have optimal strategies for the game. Write a function to determine
+     * whether you can win the game given the number of stones in the heap.
+     *
+     * Example:
+     *
+     * Input: 4
+     * Output: false
+     * Explanation: If there are 4 stones in the heap, then you will never win the game;
+     *              No matter 1, 2, or 3 stones you remove, the last stone will always be
+     *              removed by your friend.
+     *
+     * 这题往小说可以追溯到小学奥数或者脑筋急转弯的书中,往大说可以深究到博弈论。然而编程在这里并没有卵用,
+     * 策略在于,因为每个人都取不到4个,假设自己后走,要保证每轮自己和对方取得数量的和是4,这样就能确保每
+     * 轮完后都有4的倍数个石头被取走。这样,如果我们先走的话,先把n除4的余数个石头拿走,这样不管怎样,到最
+     * 后都会留4个下来,对方取1个你就取3个,对方取2个你就取2个,就必赢了。
+     * 
+ * + * @param n + * @return + */ + public boolean canWinNim(int n) { + return (n & 0b11) > 0; + } + + public boolean canWinNim2(int n) { + return n % 4 != 0; + } +} diff --git a/[0299][Bulls and Cows]/[0299][Bulls and Cows].iml b/[0299][Bulls and Cows]/[0299][Bulls and Cows].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0299][Bulls and Cows]/[0299][Bulls and Cows].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0299][Bulls and Cows]/src/Solution.java b/[0299][Bulls and Cows]/src/Solution.java new file mode 100644 index 0000000..cb785ab --- /dev/null +++ b/[0299][Bulls and Cows]/src/Solution.java @@ -0,0 +1,85 @@ +//You are playing the following Bulls and Cows game with your friend: You write +//down a number and ask your friend to guess what the number is. Each time your fr +//iend makes a guess, you provide a hint that indicates how many digits in said gu +//ess match your secret number exactly in both digit and position (called "bulls") +// and how many digits match the secret number but locate in the wrong position (c +//alled "cows"). Your friend will use successive guesses and hints to eventually d +//erive the secret number. +// +// Write a function to return a hint according to the secret number and friend's +// guess, use A to indicate the bulls and B to indicate the cows. +// +// Please note that both secret number and friend's guess may contain duplicate +//digits. +// +// Example 1: +// +// +//Input: secret = "1807", guess = "7810" +// +//Output: "1A3B" +// +//Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7. +// +// Example 2: +// +// +//Input: secret = "1123", guess = "0111" +// +//Output: "1A1B" +// +//Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow. +// +// +// Note: You may assume that the secret number and your friend's guess only cont +//ain digits, and their lengths are always equal. Related Topics Hash Table + + +import java.util.HashMap; +import java.util.Map; + +//leetcode submit region begin(Prohibit modification and deletion) +class Solution { + public String getHint(String secret, String guess) { + + // 假如参数不合法 + if (secret == null || guess == null || secret.length() != guess.length()) { + throw new IllegalArgumentException("secret: " + secret + ", guess: " + guess); + } + + Map indexMap = new HashMap<>(); + Map countMap = new HashMap<>(); + + for (int i = 0; i < secret.length(); i++) { + char c = secret.charAt(i); + indexMap.put(i, c); + countMap.put(c, 1 + countMap.getOrDefault(c, 0)); // 记录字符出现的次数 + } + + int bull = 0; + int cows = 0; + + // 先计算bull + for (int i = 0; i < guess.length(); i++) { + char c = guess.charAt(i); + if (indexMap.get(i) == c) { + bull++; + indexMap.remove(i); // 删除已经匹配过的位置 + countMap.put(c, countMap.get(c) - 1); + } + } + + // 再计算cows + for (int i = 0; i < guess.length(); i++) { + char c = guess.charAt(i); + // 位置没有被匹配过,并且值大于0,说明猜测的值是有的,但是位置错误了 + if (indexMap.containsKey(i) && countMap.getOrDefault(c, 0) > 0) { + cows++; + countMap.put(c, countMap.get(c) - 1); + } + } + + return bull + "A" + cows + "B"; + } +} +//leetcode submit region end(Prohibit modification and deletion) diff --git a/[0299][Bulls and Cows]/src/TestSolution.java b/[0299][Bulls and Cows]/src/TestSolution.java new file mode 100644 index 0000000..edc42ed --- /dev/null +++ b/[0299][Bulls and Cows]/src/TestSolution.java @@ -0,0 +1,14 @@ +import org.junit.Assert; +import org.junit.Test; + +public class TestSolution { + @Test + public void test1() { + String[][] data = {{"1807", "7810", "1A3B"}, {"1123", "0111", "1A1B"}, {"11", "10", "1A0B"}}; + + for (String[] datum : data) { + String result = new Solution().getHint(datum[0], datum[1]); + Assert.assertEquals(result, datum[2]); + } + } +} diff --git a/[0303][Range Sum Query - Immutable]/[0303][Range Sum Query - Immutable].iml b/[0303][Range Sum Query - Immutable]/[0303][Range Sum Query - Immutable].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0303][Range Sum Query - Immutable]/[0303][Range Sum Query - Immutable].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0303][Range Sum Query - Immutable]/src/NumArray.java b/[0303][Range Sum Query - Immutable]/src/NumArray.java new file mode 100644 index 0000000..c64d89d --- /dev/null +++ b/[0303][Range Sum Query - Immutable]/src/NumArray.java @@ -0,0 +1,34 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-12 13:53 + **/ +public class NumArray { + private int[] nums; + + public NumArray(int[] nums) { + this.nums = nums; + } + + public int sumRange(int i, int j) { + + if (i > j) { + throw new IllegalArgumentException("i = " + i + ", j = " + j + ", i must not greater than j"); + } + + if (j < 0) { + throw new IllegalArgumentException("i = " + i + ", j = " + j + ", i must not less than 0"); + } + + i = i < 0 ? 0 : i; + j = j >= nums.length ? nums.length - 1 : j; + + int sum = 0; + + + for (int k = i; k <= j; k++) { + sum += nums[k]; + } + + return sum; + } +} diff --git a/[0303][Range Sum Query - Immutable]/src/Test.java b/[0303][Range Sum Query - Immutable]/src/Test.java new file mode 100644 index 0000000..470204f --- /dev/null +++ b/[0303][Range Sum Query - Immutable]/src/Test.java @@ -0,0 +1,12 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-10-12 14:17 + **/ +public class Test { + public static void main(String[] args) { + NumArray array = new NumArray(new int[]{-2, 0, 3, -5, 2, -1}); + System.out.println(array.sumRange(0, 2)); + System.out.println(array.sumRange(2, 5)); + System.out.println(array.sumRange(0, 5)); + } +} diff --git a/[0326][Power of Three]/[0326][Power of Three].iml b/[0326][Power of Three]/[0326][Power of Three].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0326][Power of Three]/[0326][Power of Three].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0326][Power of Three]/src/Solution.java b/[0326][Power of Three]/src/Solution.java new file mode 100644 index 0000000..71d743c --- /dev/null +++ b/[0326][Power of Three]/src/Solution.java @@ -0,0 +1,25 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-11-16 15:21 + **/ +public class Solution { + + public boolean isPowerOfThree(int n) { + double rst = (Math.log10(n) / Math.log10(3)); + return n > 0 && Double.doubleToLongBits((int) rst) == Double.doubleToLongBits(rst); + } + + public boolean isPowerOfThree2(int n) { + return (n > 0 && 1162261467 % n == 0); + } + + public boolean isPowerOfThree1(int n) { + while (n > 1 && n % 3 == 0) { + n /= 3; + } + + return n == 1; + } + + +} diff --git a/[0326][Power of Three]/src/Test.java b/[0326][Power of Three]/src/Test.java new file mode 100644 index 0000000..9cb8806 --- /dev/null +++ b/[0326][Power of Three]/src/Test.java @@ -0,0 +1,13 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-11-16 15:31 + **/ +public class Test { + public static void main(String[] args) { + System.out.println(Double.doubleToLongBits((int) 1.00000000001) + == Double.doubleToLongBits(1.00000000001)); + + System.out.println(Double.doubleToLongBits((int) 1.00000000000) + == Double.doubleToLongBits(1.00000000000)); + } +} diff --git a/[0338][Counting Bits ]/[0338][Counting Bits ].iml b/[0338][Counting Bits ]/[0338][Counting Bits ].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0338][Counting Bits ]/[0338][Counting Bits ].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0338][Counting Bits ]/src/Main.java b/[0338][Counting Bits ]/src/Main.java new file mode 100644 index 0000000..6fe5d61 --- /dev/null +++ b/[0338][Counting Bits ]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 20:50 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{0, 1, 1}, solution.countBits(2)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{0, 1, 1, 2, 1, 2}, solution.countBits(5)); + } +} diff --git a/[0338][Counting Bits ]/src/Solution.java b/[0338][Counting Bits ]/src/Solution.java new file mode 100644 index 0000000..901792b --- /dev/null +++ b/[0338][Counting Bits ]/src/Solution.java @@ -0,0 +1,60 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 20:38 + **/ +public class Solution { + + /** + *
+     * Given a non negative integer number num. For every numbers i in the range
+     * 0 ≤ i ≤ num calculate the number of 1's in their binary representation and
+     * return them as an array.
+     *
+     * Example 1:
+     *
+     * Input: 2
+     * Output: [0,1,1]
+     * Example 2:
+     *
+     * Input: 5
+     * Output: [0,1,1,2,1,2]
+     * Follow up:
+     *
+     * It is very easy to come up with a solution with run time O(n*sizeof(integer)).
+     * But can you do it in linear time O(n) /possibly in a single pass?
+     * Space complexity should be O(n).
+     * Can you do it like a boss? Do it without using any builtin function like
+     * __builtin_popcount in c++ or in any other language.
+     *
+     * 思路:
+     * 使用治法,
+     * i为偶数 bit(i) = bit(i/2)
+     * i为奇数 bit(i) = bit(i/2) + 1
+     * 
+ * + * @param num + * @return + */ + public int[] countBits(int num) { + if (num < 0) { + return new int[0]; + } else if (num == 0) { + return new int[]{0}; + } else if (num == 1) { + return new int[]{0, 1}; + } + + int[] dp = new int[num + 1]; + dp[0] = 0; + dp[1] = 1; + for (int i = 2; i <= num; i++) { + dp[i] += dp[i / 2]; + // 不是偶数,说明其比 i/2多一个一 + if (i % 2 != 0) { + dp[i]++; + } + } + + return dp; + } +} diff --git a/[0342][Power of Four]/[0342][Power of Four].iml b/[0342][Power of Four]/[0342][Power of Four].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0342][Power of Four]/[0342][Power of Four].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0342][Power of Four]/src/Solution.java b/[0342][Power of Four]/src/Solution.java new file mode 100644 index 0000000..1466de8 --- /dev/null +++ b/[0342][Power of Four]/src/Solution.java @@ -0,0 +1,29 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-11-16 15:43 + **/ +public class Solution { + + public boolean isPowerOfFour(int num) { + return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0; + } + + + public boolean isPowerOfFour3(int num) { + int n = 0b1010101_01010101_01010101_01010101; +// int n = 0x55555555; + return num > 0 && (num & (num - 1)) == 0 && (num & n) == num; + } + + public boolean isPowerOfFour2(int num) { + double rst = (Math.log10(num) / Math.log10(4)); + return num > 0 && Double.doubleToLongBits((int) rst) == Double.doubleToLongBits(rst); + } + + public boolean isPowerOfFour1(int num) { + while (num > 1 && (num % 4 == 0)) { + num /= 4; + } + return num == 1; + } +} diff --git a/[0344][Reverse String]/[0344][Reverse String].iml b/[0344][Reverse String]/[0344][Reverse String].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0344][Reverse String]/[0344][Reverse String].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0344][Reverse String]/src/Solution.java b/[0344][Reverse String]/src/Solution.java new file mode 100644 index 0000000..b7bc9c5 --- /dev/null +++ b/[0344][Reverse String]/src/Solution.java @@ -0,0 +1,25 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2018-11-16 16:04 + **/ +public class Solution { + public String reverseString(String s) { + if (s == null || s.length() < 1) { + return s; + } + + char[] chars = s.toCharArray(); + + for (int i = 0, j = chars.length - 1; i < j; i++, j--) { + swap(chars, i, j); + } + + return new String(chars); + } + + private void swap(char[] chars, int i, int j) { + char tmp = chars[i]; + chars[i] = chars[j]; + chars[j] = tmp; + } +} diff --git a/[0345][Reverse Vowels of a String]/[0345][Reverse Vowels of a String].iml b/[0345][Reverse Vowels of a String]/[0345][Reverse Vowels of a String].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0345][Reverse Vowels of a String]/[0345][Reverse Vowels of a String].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0345][Reverse Vowels of a String]/src/Main.java b/[0345][Reverse Vowels of a String]/src/Main.java new file mode 100644 index 0000000..e2549b8 --- /dev/null +++ b/[0345][Reverse Vowels of a String]/src/Main.java @@ -0,0 +1,14 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-27 20:03 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals("holle", solution.reverseVowels("hello")); + } +} diff --git a/[0345][Reverse Vowels of a String]/src/Solution.java b/[0345][Reverse Vowels of a String]/src/Solution.java new file mode 100644 index 0000000..0704432 --- /dev/null +++ b/[0345][Reverse Vowels of a String]/src/Solution.java @@ -0,0 +1,47 @@ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-27 19:58 + **/ +public class Solution { + public String reverseVowels(String s) { + if (s == null || s.length() == 0) { + return s; + } + + char[] chars = s.toCharArray(); + + int left = 0; + int right = s.length() - 1; + + String t = "aeiouAEIOU"; + + Set set = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); + + while (left < right) { + while (left < right && !set.contains(chars[left])) { + left++; + } + while (left < right && !set.contains(chars[right])) { + right--; + } + + if (left < right) { + swap(chars, left, right); + left++; + right--; + } + } + + return new String(chars); + } + + private void swap(char[] chars, int left, int right) { + char temp = chars[left]; + chars[left] = chars[right]; + chars[right] = temp; + } +} diff --git a/[0347][Top K Frequent Elements]/[0347][Top K Frequent Elements].iml b/[0347][Top K Frequent Elements]/[0347][Top K Frequent Elements].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0347][Top K Frequent Elements]/[0347][Top K Frequent Elements].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0347][Top K Frequent Elements]/src/Main.java b/[0347][Top K Frequent Elements]/src/Main.java new file mode 100644 index 0000000..a5c4d3e --- /dev/null +++ b/[0347][Top K Frequent Elements]/src/Main.java @@ -0,0 +1,19 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 21:13 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + System.out.println(solution.topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + System.out.println(solution.topKFrequent(new int[]{4, 1, -1, 2, -1, 2, 3}, 2)); + } +} diff --git a/[0347][Top K Frequent Elements]/src/Solution.java b/[0347][Top K Frequent Elements]/src/Solution.java new file mode 100644 index 0000000..31cf516 --- /dev/null +++ b/[0347][Top K Frequent Elements]/src/Solution.java @@ -0,0 +1,72 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 21:03 + **/ +public class Solution { + /** + *
+     * Given a non-empty array of integers, return the k most frequent elements.
+     *
+     * Example 1:
+     *
+     * Input: nums = [1,1,1,2,2,3], k = 2
+     * Output: [1,2]
+     * Example 2:
+     *
+     * Input: nums = [1], k = 1
+     * Output: [1]
+     * Note:
+     *
+     * You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
+     * Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
+     *
+     * 
+ * + * @param nums + * @param k + * @return + */ + public List topKFrequent(int[] nums, int k) { + // 用于记录每个数出现的次数 + Map map = new HashMap<>(); + // 按出现次数降序,统计出现X的数字有哪些 + SortedMap> counter = new TreeMap<>(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o2 - o1; + } + }); + + // 记录每个数字出现的次数 + for (int i : nums) { + map.merge(i, 1, Integer::sum); + } + + // 记录出现X次的数字有哪些 + for (Map.Entry entry : map.entrySet()) { + List list = counter.get(entry.getValue()); + if (list == null) { + list = new LinkedList<>(); + list.add(entry.getKey()); + counter.put(entry.getValue(), list); + } else { + list.add(entry.getKey()); + } + } + + // 取K个结果 + List result = new LinkedList<>(); + for (List list : counter.values()) { + if (result.size() < k) { + int size = Math.min(k - result.size(), list.size()); + result.addAll(list.subList(0, size)); + } else { + break; + } + } + + return result; + } +} diff --git a/[0349][Intersection of Two Arrays]/[0349][Intersection of Two Arrays].iml b/[0349][Intersection of Two Arrays]/[0349][Intersection of Two Arrays].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0349][Intersection of Two Arrays]/[0349][Intersection of Two Arrays].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0349][Intersection of Two Arrays]/src/Solution.java b/[0349][Intersection of Two Arrays]/src/Solution.java new file mode 100644 index 0000000..bf85d7c --- /dev/null +++ b/[0349][Intersection of Two Arrays]/src/Solution.java @@ -0,0 +1,36 @@ +import java.util.HashSet; +import java.util.Set; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 14:42 + **/ +public class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + + if (nums1 == null || nums1.length < 1 || nums2 == null || nums2.length < 1) { + return new int[0]; + } + + Set set = new HashSet<>(); + Set result = new HashSet<>(); + + for (int i : nums1) { + set.add(i); + } + + for (int i : nums2) { + if (set.contains(i)) { + result.add(i); + } + } + + int[] r = new int[result.size()]; + int i = 0; + for (int n : result) { + r[i++] = n; + } + + return r; + } +} diff --git a/[0350][Intersection of Two Arrays II]/[0350][Intersection of Two Arrays II].iml b/[0350][Intersection of Two Arrays II]/[0350][Intersection of Two Arrays II].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0350][Intersection of Two Arrays II]/[0350][Intersection of Two Arrays II].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0350][Intersection of Two Arrays II]/src/Solution.java b/[0350][Intersection of Two Arrays II]/src/Solution.java new file mode 100644 index 0000000..d8393f7 --- /dev/null +++ b/[0350][Intersection of Two Arrays II]/src/Solution.java @@ -0,0 +1,68 @@ +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 14:49 + **/ +public class Solution { + /** + *
+     * Given two arrays, write a function to compute their intersection.
+     *
+     * Example 1:
+     *
+     * Input: nums1 = [1,2,2,1], nums2 = [2,2]
+     * Output: [2,2]
+     * Example 2:
+     *
+     * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
+     * Output: [4,9]
+     * Note:
+     *
+     * Each element in the result should appear as many times as it shows in both arrays.
+     * The result can be in any order.
+     * Follow up:
+     *
+     * What if the given array is already sorted? How would you optimize your algorithm?
+     * What if nums1's size is small compared to nums2's size? Which algorithm is better?
+     * What if elements of nums2 are stored on disk, and the memory is limited such that
+     * you cannot load all elements into the memory at once?
+     * 
+ * + * @param nums1 + * @param nums2 + * @return + */ + public int[] intersect(int[] nums1, int[] nums2) { + + if (nums1 == null || nums1.length < 1 || nums2 == null || nums2.length < 1) { + return new int[0]; + } + + Map map = new HashMap<>(); + List result = new LinkedList<>(); + + for (int i : nums1) { + map.merge(i, 1, Integer::sum); + } + + for (int i : nums2) { + Integer v = map.get(i); + if (v != null && v > 0) { + result.add(i); + map.put(i, v - 1); + } + } + + int[] r = new int[result.size()]; + int i = 0; + for (int n : result) { + r[i++] = n; + } + + return r; + } +} diff --git a/[0367][Valid Perfect Square]/[0367][Valid Perfect Square].iml b/[0367][Valid Perfect Square]/[0367][Valid Perfect Square].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0367][Valid Perfect Square]/[0367][Valid Perfect Square].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0367][Valid Perfect Square]/src/Main.java b/[0367][Valid Perfect Square]/src/Main.java new file mode 100644 index 0000000..78690f1 --- /dev/null +++ b/[0367][Valid Perfect Square]/src/Main.java @@ -0,0 +1,32 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 15:18 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.isPerfectSquare(16)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isPerfectSquare(14)); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isPerfectSquare(5)); + } + + @Test + public void test4() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.isPerfectSquare(2147483647)); + } +} diff --git a/[0367][Valid Perfect Square]/src/Solution.java b/[0367][Valid Perfect Square]/src/Solution.java new file mode 100644 index 0000000..5b8ebe7 --- /dev/null +++ b/[0367][Valid Perfect Square]/src/Solution.java @@ -0,0 +1,34 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 15:10 + **/ +public class Solution { + public boolean isPerfectSquare(int num) { + if (num < 0) { + return false; + } + + if (num == 0 || num == 1) { + return true; + } + + int left = 0; + int right = num; + while (left <= right) { + int mid = left + (right - left) / 2; + + int sqrt = num / mid; + if (mid == sqrt && num % mid == 0) { + return true; + } else if (mid > sqrt) { + right = mid - 1; + } else { + left = mid + 1; + } + + + } + + return false; + } +} diff --git a/[0367][Valid Perfect Square]/src/Solution2.java b/[0367][Valid Perfect Square]/src/Solution2.java new file mode 100644 index 0000000..412343c --- /dev/null +++ b/[0367][Valid Perfect Square]/src/Solution2.java @@ -0,0 +1,41 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 15:32 + **/ +public class Solution2 { + public boolean isPerfectSquare(int num) { + if (num < 0) { + return false; + } + + if (num == 0 || num == 1) { + return true; + } + + int left = 0; + int right = num; + while (left <= right) { + int mid = left + (right - left) / 2; + + if (mid < 1) { + return false; + } + + int sqrt = num / mid; + if (mid == sqrt && num % mid == 0) { + return true; + } else if (mid < sqrt) { + + if (mid + 1 > num / (mid + 1)) { + return false; + } + + left = mid + 1; + } else { + right = mid - 1; + } + } + + return false; + } +} diff --git "a/\343\200\220003\343\200\221\343\200\220LongestSubstringWithoutRepeatingCharacters\343\200\221/\343\200\220003\343\200\221\343\200\220LongestSubstringWithoutRepeatingCharacters\343\200\221.iml" b/[0371][Sum of Two Integers]/[0371][Sum of Two Integers].iml similarity index 100% rename from "\343\200\220003\343\200\221\343\200\220LongestSubstringWithoutRepeatingCharacters\343\200\221/\343\200\220003\343\200\221\343\200\220LongestSubstringWithoutRepeatingCharacters\343\200\221.iml" rename to [0371][Sum of Two Integers]/[0371][Sum of Two Integers].iml diff --git a/[0371][Sum of Two Integers]/src/Solution.java b/[0371][Sum of Two Integers]/src/Solution.java new file mode 100644 index 0000000..411fe08 --- /dev/null +++ b/[0371][Sum of Two Integers]/src/Solution.java @@ -0,0 +1,52 @@ +//Calculate the sum of two integers a and b, but you are not allowed to use the +//operator + and -. +// +// +// Example 1: +// +// +//Input: a = 1, b = 2 +//Output: 3 +// +// +// +// Example 2: +// +// +//Input: a = -2, b = 3 +//Output: 1 +// +// +// +// Related Topics Bit Manipulation + + +//leetcode submit region begin(Prohibit modification and deletion) + +/** + * Author: 王俊超 + * Time: 2016-07-03 21-25 10:58 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + */ +public class Solution { + public int getSum(int a, int b) { + + // 保存不进位值,异或运算结果 + int xor; + // 保存进位结果,与运算,然后左移一位结果 + int and; + do { + xor = a ^ b; + and = a & b; + and <<= 1; + a = xor; + b = and; + + } while (and != 0); + + return xor; + } +} +//leetcode submit region end(Prohibit modification and deletion) diff --git a/[0371][Sum of Two Integers]/src/SolutionTest.java b/[0371][Sum of Two Integers]/src/SolutionTest.java new file mode 100644 index 0000000..275433e --- /dev/null +++ b/[0371][Sum of Two Integers]/src/SolutionTest.java @@ -0,0 +1,2 @@ +public class SolutionTest { +} diff --git a/[0374][Guess Number Higher or Lower]/[0374][Guess Number Higher or Lower].iml b/[0374][Guess Number Higher or Lower]/[0374][Guess Number Higher or Lower].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0374][Guess Number Higher or Lower]/[0374][Guess Number Higher or Lower].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0374][Guess Number Higher or Lower]/src/GuessGame.java b/[0374][Guess Number Higher or Lower]/src/GuessGame.java new file mode 100644 index 0000000..8ce64cd --- /dev/null +++ b/[0374][Guess Number Higher or Lower]/src/GuessGame.java @@ -0,0 +1,9 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 15:47 + **/ +public class GuessGame { + int guess(int num) { + return 0; + } +} diff --git a/[0374][Guess Number Higher or Lower]/src/Solution.java b/[0374][Guess Number Higher or Lower]/src/Solution.java new file mode 100644 index 0000000..05dec89 --- /dev/null +++ b/[0374][Guess Number Higher or Lower]/src/Solution.java @@ -0,0 +1,45 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 15:46 + **/ +public class Solution extends GuessGame { + /** + *
+     * We are playing the Guess Game. The game is as follows:
+     *
+     * I pick a number from 1 to n. You have to guess which number I picked.
+     *
+     * Every time you guess wrong, I'll tell you whether the number is higher or lower.
+     *
+     * You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
+     *
+     * -1 : My number is lower
+     *  1 : My number is higher
+     *  0 : Congrats! You got it!
+     * Example :
+     *
+     * Input: n = 10, pick = 6
+     * Output: 6
+     * 
+ * + * @param n + * @return + */ + public int guessNumber(int n) { + int left = 1; + int right = n; + while (left <= right) { + int mid = left + (right - left) / 2; + int result = guess(mid); + if (result == 0) { + return mid; + } else if (result < 0) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return 0; + } +} diff --git a/[0383][Ransom Note]/[0383][Ransom Note].iml b/[0383][Ransom Note]/[0383][Ransom Note].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0383][Ransom Note]/[0383][Ransom Note].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0383][Ransom Note]/src/Main.java b/[0383][Ransom Note]/src/Main.java new file mode 100644 index 0000000..c7e5008 --- /dev/null +++ b/[0383][Ransom Note]/src/Main.java @@ -0,0 +1,28 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 16:00 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.canConstruct("a", "b")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.canConstruct("aa", "ab")); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.canConstruct("aa", "aab")); + } + + +} diff --git a/[0383][Ransom Note]/src/Solution.java b/[0383][Ransom Note]/src/Solution.java new file mode 100644 index 0000000..77ec03f --- /dev/null +++ b/[0383][Ransom Note]/src/Solution.java @@ -0,0 +1,47 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-28 15:58 + **/ +public class Solution { + /** + *
+     * Given an arbitrary ransom note string and another string containing letters
+     * from all the magazines, write a function that will return true if the ransom
+     * note can be constructed from the magazines ; otherwise, it will return false.
+     *
+     * Each letter in the magazine string can only be used once in your ransom note.
+     *
+     * Note:
+     * You may assume that both strings contain only lowercase letters.
+     *
+     * canConstruct("a", "b") -> false
+     * canConstruct("aa", "ab") -> false
+     * canConstruct("aa", "aab") -> true
+     * 
+ * + * @param ransomNote + * @param magazine + * @return + */ + public boolean canConstruct(String ransomNote, String magazine) { + // 假设输入都是合法的 + + int[] chars = new int[26]; + + for (int i = 0; i < magazine.length(); i++) { + chars[magazine.charAt(i) - 'a']++; + } + + for (int i = 0; i < ransomNote.length(); i++) { + chars[ransomNote.charAt(i) - 'a']--; + } + + for (int n : chars) { + if (n < 0) { + return false; + } + } + + return true; + } +} diff --git a/[0384][Shuffle an Array]/[0384][Shuffle an Array].iml b/[0384][Shuffle an Array]/[0384][Shuffle an Array].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0384][Shuffle an Array]/[0384][Shuffle an Array].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0384][Shuffle an Array]/src/Main.java b/[0384][Shuffle an Array]/src/Main.java new file mode 100644 index 0000000..b5a927d --- /dev/null +++ b/[0384][Shuffle an Array]/src/Main.java @@ -0,0 +1,40 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 15:56 + **/ +public class Main { + @Test + public void test1() { + int[] nums = {1, 2, 3}; + Solution solution = new Solution(nums); + + int[] shuffle = solution.shuffle(); + System.out.println(Arrays.toString(shuffle)); + + int[] reset = solution.reset(); + Assert.assertArrayEquals(nums, reset); + + shuffle = solution.shuffle(); + System.out.println(Arrays.toString(shuffle)); + } + + @Test + public void test2() { + int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + Solution solution = new Solution(nums); + + int[] shuffle = solution.shuffle(); + System.out.println(Arrays.toString(shuffle)); + + int[] reset = solution.reset(); + Assert.assertArrayEquals(nums, reset); + + shuffle = solution.shuffle(); + System.out.println(Arrays.toString(shuffle)); + } +} diff --git a/[0384][Shuffle an Array]/src/Solution.java b/[0384][Shuffle an Array]/src/Solution.java new file mode 100644 index 0000000..2f16e89 --- /dev/null +++ b/[0384][Shuffle an Array]/src/Solution.java @@ -0,0 +1,61 @@ +import java.util.Arrays; +import java.util.Random; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 15:51 + **/ +public class Solution { + + private int[] original; + + /** + *
+     * // Init an array with set 1, 2, and 3.
+     * int[] nums = {1,2,3};
+     * Solution solution = new Solution(nums);
+     *
+     * // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3]
+     * must equally likely to be returned.
+     * solution.shuffle();
+     *
+     * // Resets the array back to its original configuration [1,2,3].
+     * solution.reset();
+     *
+     * // Returns the random shuffling of array [1,2,3].
+     * solution.shuffle();
+     * 
+ * + * @param nums + */ + public Solution(int[] nums) { + original = nums; + } + + /** + * Resets the array to its original configuration and return it. + */ + public int[] reset() { + return Arrays.copyOf(original, original.length); + } + + /** + * Returns a random shuffling of the array. + */ + public int[] shuffle() { + int[] copy = Arrays.copyOf(original, original.length); + + Random random = new Random(); + for (int i = 0; i < copy.length - 1; i++) { + swap(copy, i, i + random.nextInt(copy.length - i)); + } + + return copy; + } + + private void swap(int[] copy, int i, int j) { + int t = copy[i]; + copy[i] = copy[j]; + copy[j] = t; + } +} diff --git a/[0387][First Unique Character in a String]/[0387][First Unique Character in a String].iml b/[0387][First Unique Character in a String]/[0387][First Unique Character in a String].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0387][First Unique Character in a String]/[0387][First Unique Character in a String].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0387][First Unique Character in a String]/src/Main.java b/[0387][First Unique Character in a String]/src/Main.java new file mode 100644 index 0000000..4c695a9 --- /dev/null +++ b/[0387][First Unique Character in a String]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 13:50 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(0, solution.firstUniqChar("leetcode")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(2, solution.firstUniqChar("loveleetcode")); + } +} diff --git a/[0387][First Unique Character in a String]/src/Solution.java b/[0387][First Unique Character in a String]/src/Solution.java new file mode 100644 index 0000000..ea4eea0 --- /dev/null +++ b/[0387][First Unique Character in a String]/src/Solution.java @@ -0,0 +1,59 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 13:43 + **/ +public class Solution { + + /** + *
+     * Given a string, find the first non-repeating character in it and return it's index.
+     * If it doesn't exist, return -1.
+     *
+     * Examples:
+     *
+     * s = "leetcode"
+     * return 0.
+     *
+     * s = "loveleetcode",
+     * return 2.
+     * 
+ * + * @param s + * @return + */ + public int firstUniqChar(String s) { + if (s == null || s.length() < 1) { + return -1; + } + + + Map map = new HashMap<>(s.length()); + + for (int i = 0; i < s.length(); i++) { + // 标记字符已经重复 + if (map.containsKey(s.charAt(i))) { + map.put(s.charAt(i), -1); + } else { + // 记录位置 + map.put(s.charAt(i), i); + } + } + + Integer result = null; + + for (Integer n : map.values()) { + if (n >= 0) { + if (result == null) { + result = n; + } else { + result = Math.min(n, result); + } + } + } + + return result == null ? -1 : result; + } +} diff --git a/[0389][Find the Difference]/[0389][Find the Difference].iml b/[0389][Find the Difference]/[0389][Find the Difference].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0389][Find the Difference]/[0389][Find the Difference].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0389][Find the Difference]/src/Main.java b/[0389][Find the Difference]/src/Main.java new file mode 100644 index 0000000..e936514 --- /dev/null +++ b/[0389][Find the Difference]/src/Main.java @@ -0,0 +1,25 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 14:00 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals('e', solution.findTheDifference("abcd", "abcde")); + + } + + @Test + public void test2() { + String s = "ymbgaraibkfmvocpizdydugvalagaivdbfsfbepeyccqfepzvtpyxtbadkhmwmoswrcxnargtlswqemafandgkmydtimuzvjwxvlfwlhvkrgcsithaqlcvrihrwqkpjdhgfgreqoxzfvhjzojhghfwbvpfzectwwhexthbsndovxejsntmjihchaotbgcysfdaojkjldprwyrnischrgmtvjcorypvopfmegizfkvudubnejzfqffvgdoxohuinkyygbdzmshvyqyhsozwvlhevfepdvafgkqpkmcsikfyxczcovrmwqxxbnhfzcjjcpgzjjfateajnnvlbwhyppdleahgaypxidkpwmfqwqyofwdqgxhjaxvyrzupfwesmxbjszolgwqvfiozofncbohduqgiswuiyddmwlwubetyaummenkdfptjczxemryuotrrymrfdxtrebpbjtpnuhsbnovhectpjhfhahbqrfbyxggobsweefcwxpqsspyssrmdhuelkkvyjxswjwofngpwfxvknkjviiavorwyfzlnktmfwxkvwkrwdcxjfzikdyswsuxegmhtnxjraqrdchaauazfhtklxsksbhwgjphgbasfnlwqwukprgvihntsyymdrfovaszjywuqygpvjtvlsvvqbvzsmgweiayhlubnbsitvfxawhfmfiatxvqrcwjshvovxknnxnyyfexqycrlyksderlqarqhkxyaqwlwoqcribumrqjtelhwdvaiysgjlvksrfvjlcaiwrirtkkxbwgicyhvakxgdjwnwmubkiazdjkfmotglclqndqjxethoutvjchjbkoasnnfbgrnycucfpeovruguzumgmgddqwjgdvaujhyqsqtoexmnfuluaqbxoofvotvfoiexbnprrxptchmlctzgqtkivsilwgwgvpidpvasurraqfkcmxhdapjrlrnkbklwkrvoaziznlpor"; + String t = "qhxepbshlrhoecdaodgpousbzfcqjxulatciapuftffahhlmxbufgjuxstfjvljybfxnenlacmjqoymvamphpxnolwijwcecgwbcjhgdybfffwoygikvoecdggplfohemfypxfsvdrseyhmvkoovxhdvoavsqqbrsqrkqhbtmgwaurgisloqjixfwfvwtszcxwktkwesaxsmhsvlitegrlzkvfqoiiwxbzskzoewbkxtphapavbyvhzvgrrfriddnsrftfowhdanvhjvurhljmpxvpddxmzfgwwpkjrfgqptrmumoemhfpojnxzwlrxkcafvbhlwrapubhveattfifsmiounhqusvhywnxhwrgamgnesxmzliyzisqrwvkiyderyotxhwspqrrkeczjysfujvovsfcfouykcqyjoobfdgnlswfzjmyucaxuaslzwfnetekymrwbvponiaojdqnbmboldvvitamntwnyaeppjaohwkrisrlrgwcjqqgxeqerjrbapfzurcwxhcwzugcgnirkkrxdthtbmdqgvqxilllrsbwjhwqszrjtzyetwubdrlyakzxcveufvhqugyawvkivwonvmrgnchkzdysngqdibhkyboyftxcvvjoggecjsajbuqkjjxfvynrjsnvtfvgpgveycxidhhfauvjovmnbqgoxsafknluyimkczykwdgvqwlvvgdmufxdypwnajkncoynqticfetcdafvtqszuwfmrdggifokwmkgzuxnhncmnsstffqpqbplypapctctfhqpihavligbrutxmmygiyaklqtakdidvnvrjfteazeqmbgklrgrorudayokxptswwkcircwuhcavhdparjfkjypkyxhbgwxbkvpvrtzjaetahmxevmkhdfyidhrdeejapfbafwmdqjqszwnwzgclitdhlnkaiyldwkwwzvhyorgbysyjbxsspnjdewjxbhpsvj"; + Solution solution = new Solution(); + Assert.assertEquals('t', solution.findTheDifference(s, t)); + + } + +} diff --git a/[0389][Find the Difference]/src/Solution.java b/[0389][Find the Difference]/src/Solution.java new file mode 100644 index 0000000..a22ff15 --- /dev/null +++ b/[0389][Find the Difference]/src/Solution.java @@ -0,0 +1,54 @@ +import java.util.NoSuchElementException; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 13:53 + **/ +public class Solution { + /** + *
+     * Given two strings s and t which consist of only lowercase letters.
+     *
+     * String t is generated by random shuffling string s and then add one
+     * more letter at a random position.
+     *
+     * Find the letter that was added in t.
+     *
+     * Example:
+     *
+     * Input:
+     * s = "abcd"
+     * t = "abcde"
+     *
+     * Output:
+     * e
+     *
+     * Explanation:
+     * 'e' is the letter that was added.
+     * 
+ * + * @param s + * @param t + * @return + */ + public char findTheDifference(String s, String t) { + // 假设输入都是合法的 + int[] chars = new int[26]; + + for (int i = 0; i < s.length(); i++) { + chars[s.charAt(i) - 'a']++; + } + + for (int i = 0; i < t.length(); i++) { + chars[t.charAt(i) - 'a']--; + } + + for (int i = 0; i < chars.length; i++) { + if (chars[i] < 0) { + return (char) ('a' + i); + } + } + + throw new NoSuchElementException("could not find the difference"); + } +} diff --git a/[0392][Is Subsequence]/[0392][Is Subsequence].iml b/[0392][Is Subsequence]/[0392][Is Subsequence].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0392][Is Subsequence]/[0392][Is Subsequence].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0392][Is Subsequence]/src/Solution.java b/[0392][Is Subsequence]/src/Solution.java new file mode 100644 index 0000000..fd4ddb2 --- /dev/null +++ b/[0392][Is Subsequence]/src/Solution.java @@ -0,0 +1,81 @@ +//Given a string s and a string t, check if s is subsequence of t. +// +// A subsequence of a string is a new string which is formed from the original s +//tring by deleting some (can be none) of the characters without disturbing the re +//lative positions of the remaining characters. (ie, "ace" is a subsequence of "ab +//cde" while "aec" is not). +// +// Follow up: +//If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you w +//ant to check one by one to see if T has its subsequence. In this scenario, how w +//ould you change your code? +// +// Credits: +//Special thanks to @pbrother for adding this problem and creating all test case +//s. +// +// +// Example 1: +// Input: s = "abc", t = "ahbgdc" +//Output: true +// Example 2: +// Input: s = "axc", t = "ahbgdc" +//Output: false +// +// +// Constraints: +// +// +// 0 <= s.length <= 100 +// 0 <= t.length <= 10^4 +// Both strings consists only of lowercase characters. +// +// Related Topics Binary Search Dynamic Programming Greedy + + +//leetcode submit region begin(Prohibit modification and deletion) + +/** + * Author: 王俊超 + * Time: 2020-06-24 10:48 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public boolean isSubsequence(String s, String t) { + + if (s == null && t == null) { + return true; + } + + if (s == null || t == null) { + return false; + } + + if (s.length() == 0) { + return true; + } + + if (t.length() == 0) { + return false; + } + + int idxT = 0; + int idxS = 0; + while (idxS < s.length() && idxT < t.length()) { + + if (s.charAt(idxS) == t.charAt(idxT)) { + idxS++; + idxT++; + } else { + idxT++; + } + } + + + return idxS == s.length(); + + } +} +//leetcode submit region end(Prohibit modification and deletion) diff --git a/[0392][Is Subsequence]/src/SolutionTest.java b/[0392][Is Subsequence]/src/SolutionTest.java new file mode 100644 index 0000000..7cd621c --- /dev/null +++ b/[0392][Is Subsequence]/src/SolutionTest.java @@ -0,0 +1,29 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * Author: 王俊超 + * Time: 2020-06-25 14:03 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + @Test + public void test1() { + Object[][] data = { + + {"", "", true}, + {"", "ahbgdc", true}, + {"ahbgdc", "", false}, + {"abc", "ahbgdc", true}, + {"axc", "ahbgdc", false}, + {"leetcode", "lleettccooddee", true}, + }; + + for (Object[] datum : data) { + Solution s = new Solution(); + Assert.assertEquals(s.isSubsequence((String) datum[0], (String) datum[1]), datum[2]); + } + } +} diff --git a/[0400][Nth Digit]/[0400][Nth Digit].iml b/[0400][Nth Digit]/[0400][Nth Digit].iml new file mode 100644 index 0000000..f080bef --- /dev/null +++ b/[0400][Nth Digit]/[0400][Nth Digit].iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0400][Nth Digit]/src/Solution.java b/[0400][Nth Digit]/src/Solution.java new file mode 100644 index 0000000..24a8b8d --- /dev/null +++ b/[0400][Nth Digit]/src/Solution.java @@ -0,0 +1,80 @@ +/** + * https://leetcode.com/problems/nth-digit/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 15:56 + **/ +public class Solution { + /** + *
+     * Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
+     *
+     * Note:
+     * n is positive and will fit within the range of a 32-bit signed integer (n < 231).
+     *
+     * Example 1:
+     *
+     * Input:
+     * 3
+     *
+     * Output:
+     * 3
+     * Example 2:
+     *
+     * Input:
+     * 11
+     *
+     * Output:
+     * 0
+     *
+     * Explanation:
+     * The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0,
+     * which is part of the number 10.
+     *
+     * https://blog.csdn.net/yeqiuzs/article/details/52573876
+     *
+     * 思路:
+     * 1~9 9个数 9*1=9个digit
+     * 10~99 90个数 90*2=180个digit
+     * 100~999 900个数 900*3=2700个digit
+     * 10^k ~ k个9连成的数 9*10^k个数 (90*10^k)*k个digit
+     *
+     * 所以给点n,首先确定在几位数之间,如在1000~9999还是在其他之间?然后确定是该区间的哪个数?
+     * 最后确定是该数字的哪个digit?
+     * 注意防止溢出。
+     *
+     * 
+ * + * @param n + * @return + */ + public int findNthDigit(int n) { + // 记录用多少位 + int k = 1; + // 记录[10..0(k-1个0), ..., k个9]有多少个数字 + long length = 0; + while (n > length) { + + // 记录[0, ..., k个9]有多少位 + // [10..0(k-1个0), ..., k个9]有 (int) (9 * k * Math.pow(10, k - 1)) 个数字 + length += (int) (9 * k * Math.pow(10, k - 1)); + k++; + } + + k--; + // n >= 9..9, k个9,k取最大满足条件的值,计算有多少个数字 + length -= (int) (9 * k * Math.pow(10, k - 1)); + int num; + + if ((n - length) % k == 0) { + num = (int) ((int) Math.pow(10, k - 1) + (n - length) / k - 1); + String s = String.valueOf(num); + return s.charAt(s.length() - 1) - '0'; + } else { + num = (int) ((int) Math.pow(10, k - 1) + (n - length) / k); + String s = String.valueOf(num); + return s.charAt((int) ((n - length) % k - 1)) - '0'; + } + + } +} diff --git a/[0400][Nth Digit]/src/Solution2.java b/[0400][Nth Digit]/src/Solution2.java new file mode 100644 index 0000000..4a5b2c9 --- /dev/null +++ b/[0400][Nth Digit]/src/Solution2.java @@ -0,0 +1,53 @@ +/** + * https://leetcode.com/problems/nth-digit/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 15:56 + **/ +public class Solution2 { + /** + *
+     * Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
+     *
+     * Note:
+     * n is positive and will fit within the range of a 32-bit signed integer (n < 231).
+     *
+     * Example 1:
+     *
+     * Input:
+     * 3
+     *
+     * Output:
+     * 3
+     * Example 2:
+     *
+     * Input:
+     * 11
+     *
+     * Output:
+     * 0
+     *
+     * Explanation:
+     * The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
+     *
+     * https://www.cnblogs.com/grandyang/p/5891871.html
+     *  
+ * + * @param n + * @return + */ + public int findNthDigit(int n) { + long len = 1; + int cnt = 9; + int start = 1; + while (n > len * cnt) { + n -= len * cnt; + ++len; + cnt *= 10; + start *= 10; + } + start += (n - 1) / len; + String t = "" + start; + return t.charAt((int) ((n - 1) % len)) - '0'; + } +} diff --git a/[0401][Binary Watch]/[0401][Binary Watch].iml b/[0401][Binary Watch]/[0401][Binary Watch].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0401][Binary Watch]/[0401][Binary Watch].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0401][Binary Watch]/src/Main.java b/[0401][Binary Watch]/src/Main.java new file mode 100644 index 0000000..efea389 --- /dev/null +++ b/[0401][Binary Watch]/src/Main.java @@ -0,0 +1,19 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-01 14:32 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + System.out.println(solution.readBinaryWatch(1)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + System.out.println(solution.readBinaryWatch(2)); + } +} diff --git a/[0401][Binary Watch]/src/Solution.java b/[0401][Binary Watch]/src/Solution.java new file mode 100644 index 0000000..8d7c224 --- /dev/null +++ b/[0401][Binary Watch]/src/Solution.java @@ -0,0 +1,63 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-01 14:16 + **/ +public class Solution { + public List readBinaryWatch(int num) { + List result = new LinkedList<>(); + + if (num < 0 || num >= 9) { + return result; + } + + if (num == 0) { + result.add("0:00"); + return result; + } + + int[] values = {1, 2, 4, 8, 1, 2, 4, 8, 16, 32}; + + List current = new ArrayList<>(); + readBinaryWatch(values, 0, num, num, current, result); + + return result; + } + + private void readBinaryWatch(int[] values, int start, int left, int total, List current, List result) { + + if (left == 0) { + if (total != current.size()) { + return; + } + + int hour = 0; + int minute = 0; + for (int i : current) { + if (i < 4) { + hour += values[i]; + if (hour > 11) { + return; + } + } else { + minute += values[i]; + if (minute > 59) { + return; + } + } + } + + result.add(hour + ":" + (minute < 10 ? "0" + minute : minute)); + return; + } + + for (int i = start; i < values.length - left + 1; i++) { + current.add(i); + readBinaryWatch(values, i + 1, left - 1, total, current, result); + current.remove(current.size() - 1); + } + } +} diff --git a/[0404][Sum of Left Leaves]/[0404][Sum of Left Leaves].iml b/[0404][Sum of Left Leaves]/[0404][Sum of Left Leaves].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0404][Sum of Left Leaves]/[0404][Sum of Left Leaves].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0404][Sum of Left Leaves]/src/Main.java b/[0404][Sum of Left Leaves]/src/Main.java new file mode 100644 index 0000000..cf253ab --- /dev/null +++ b/[0404][Sum of Left Leaves]/src/Main.java @@ -0,0 +1,28 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 14:18 + **/ +public class Main { + @Test + public void test1() { + TreeNode root = new TreeNode(3); + root.left = new TreeNode(9); + root.right = new TreeNode(20); + root.right.left = new TreeNode(15); + root.right.right = new TreeNode(7); + + Solution solution = new Solution(); + Assert.assertEquals(24, solution.sumOfLeftLeaves(root)); + } + + @Test + public void test2() { + TreeNode root = new TreeNode(1); + + Solution solution = new Solution(); + Assert.assertEquals(0, solution.sumOfLeftLeaves(root)); + } +} diff --git a/[0404][Sum of Left Leaves]/src/Solution.java b/[0404][Sum of Left Leaves]/src/Solution.java new file mode 100644 index 0000000..d5a8ad8 --- /dev/null +++ b/[0404][Sum of Left Leaves]/src/Solution.java @@ -0,0 +1,50 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-06-30 14:11 + **/ +public class Solution { + /** + *
+     * Find the sum of all left leaves in a given binary tree.
+     *
+     * Example:
+     *
+     *     3
+     *    / \
+     *   9  20
+     *     /  \
+     *    15   7
+     *
+     * There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
+     * 
+ * + * @param root + * @return + */ + public int sumOfLeftLeaves(TreeNode root) { + int[] result = new int[1]; + sumOfLeftLeaves(root, false, result); + return result[0]; + } + + /** + * 计算所有左叶子的和 + * + * @param root + * @param result + */ + private void sumOfLeftLeaves(TreeNode root, boolean isLeftLeaf, int[] result) { + + if (root == null) { + return; + } + + if (root.left == null && root.right == null && isLeftLeaf) { + result[0] += root.val; + return; + } + + sumOfLeftLeaves(root.left, true, result); + sumOfLeftLeaves(root.right, false, result); + } +} diff --git a/[0404][Sum of Left Leaves]/src/TreeNode.java b/[0404][Sum of Left Leaves]/src/TreeNode.java new file mode 100644 index 0000000..9aec4dd --- /dev/null +++ b/[0404][Sum of Left Leaves]/src/TreeNode.java @@ -0,0 +1,15 @@ +/** + * Author: + * Date: 2015-08-19 + * Time: 06:45 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0405][Convert a Number to Hexadecimal]/[0405][Convert a Number to Hexadecimal].iml b/[0405][Convert a Number to Hexadecimal]/[0405][Convert a Number to Hexadecimal].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0405][Convert a Number to Hexadecimal]/[0405][Convert a Number to Hexadecimal].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0405][Convert a Number to Hexadecimal]/src/Main.java b/[0405][Convert a Number to Hexadecimal]/src/Main.java new file mode 100644 index 0000000..0e56b0e --- /dev/null +++ b/[0405][Convert a Number to Hexadecimal]/src/Main.java @@ -0,0 +1,26 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 03:59 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals("1a", solution.toHex(26)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals("ffffffff", solution.toHex(-1)); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals("10", solution.toHex(16)); + } +} diff --git a/[0405][Convert a Number to Hexadecimal]/src/Solution.java b/[0405][Convert a Number to Hexadecimal]/src/Solution.java new file mode 100644 index 0000000..28c3f8f --- /dev/null +++ b/[0405][Convert a Number to Hexadecimal]/src/Solution.java @@ -0,0 +1,54 @@ +/** + * https://leetcode.com/problems/convert-a-number-to-hexadecimal/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 03:55 + **/ +public class Solution { + /** + *
+     * Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
+     *
+     * Note:
+     *
+     * All letters in hexadecimal (a-f) must be in lowercase.
+     * The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
+     * The given number is guaranteed to fit within the range of a 32-bit signed integer.
+     * You must not use any method provided by the library which converts/formats the number to hex directly.
+     * Example 1:
+     *
+     * Input:
+     * 26
+     *
+     * Output:
+     * "1a"
+     * Example 2:
+     *
+     * Input:
+     * -1
+     *
+     * Output:
+     * "ffffffff"
+     * 
+ * + * @param num + * @return + */ + public String toHex(int num) { + String result = ""; + String hex = "0123456789abcdef"; + int mask = 0b1111; + + int i; + do { + // 取低四位的值 + i = num & mask; + // 转成16进制 + result = hex.charAt(i) + result; + // 无符号右移四位,直到0 + num >>>= 4; + } while (num > 0); + + return result; + } +} diff --git a/[0409][Longest Palindrome]/[0409][Longest Palindrome].iml b/[0409][Longest Palindrome]/[0409][Longest Palindrome].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0409][Longest Palindrome]/[0409][Longest Palindrome].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0409][Longest Palindrome]/src/Main.java b/[0409][Longest Palindrome]/src/Main.java new file mode 100644 index 0000000..61a21bb --- /dev/null +++ b/[0409][Longest Palindrome]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:15 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(7, solution.longestPalindrome("abccccdd")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(7, solution.longestPalindrome("aAaaaaaa")); + } +} diff --git a/[0409][Longest Palindrome]/src/Solution.java b/[0409][Longest Palindrome]/src/Solution.java new file mode 100644 index 0000000..6cfa418 --- /dev/null +++ b/[0409][Longest Palindrome]/src/Solution.java @@ -0,0 +1,54 @@ +/** + * https://leetcode.com/problems/longest-palindrome/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:08 + **/ +public class Solution { + /** + *
+     * Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
+     *
+     * This is case sensitive, for example "Aa" is not considered a palindrome here.
+     *
+     * Note:
+     * Assume the length of given string will not exceed 1,010.
+     *
+     * Example:
+     *
+     * Input:
+     * "abccccdd"
+     *
+     * Output:
+     * 7
+     *
+     * Explanation:
+     * One longest palindrome that can be built is "dccaccd", whose length is 7.
+     * 思路
+     * 1、先记录每个字符出现的次数
+     * 2、取每个字符出现的最大的偶数
+     * 3、如果还有剩下的单个字符,只取其中的一个
+     * 
+ */ + public int longestPalindrome(String s) { + if (s == null || s.length() < 1) { + return 0; + } + + int[] counter = new int[256]; + + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + counter[ch - 'A']++; + } + + int result = 0; + int left = 0; + for (int value : counter) { + result += 0xFFFFFFFE & value; + left |= 0b1 & value; + } + + return result + left; + } +} diff --git a/[0409][Longest Palindrome]/src/Solution1.java b/[0409][Longest Palindrome]/src/Solution1.java new file mode 100644 index 0000000..797d326 --- /dev/null +++ b/[0409][Longest Palindrome]/src/Solution1.java @@ -0,0 +1,60 @@ +/** + * https://leetcode.com/problems/longest-palindrome/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:08 + **/ +public class Solution1 { + /** + *
+     * Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
+     *
+     * This is case sensitive, for example "Aa" is not considered a palindrome here.
+     *
+     * Note:
+     * Assume the length of given string will not exceed 1,010.
+     *
+     * Example:
+     *
+     * Input:
+     * "abccccdd"
+     *
+     * Output:
+     * 7
+     *
+     * Explanation:
+     * One longest palindrome that can be built is "dccaccd", whose length is 7.
+     * 思路
+     * 1、先记录每个字符出现的次数
+     * 2、取每个字符出现的最大的偶数
+     * 3、如果还有剩下的单个字符,只取其中的一个
+     * 
+ */ + public int longestPalindrome(String s) { + if (s == null || s.length() < 1) { + return 0; + } + + int[] counter = new int[256]; + + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + counter[ch - 'A']++; + } + + int result = 0; + int left = 0; + for (int value : counter) { + if (value > 0) { + if (value % 2 == 0) { + result += value; + } else { + result += value - 1; + left = 1; + } + } + } + + return result + left; + } +} diff --git a/[0409][Longest Palindrome]/src/Solution2.java b/[0409][Longest Palindrome]/src/Solution2.java new file mode 100644 index 0000000..ad898f8 --- /dev/null +++ b/[0409][Longest Palindrome]/src/Solution2.java @@ -0,0 +1,67 @@ +/** + * https://leetcode.com/problems/longest-palindrome/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:08 + **/ +public class Solution2 { + /** + *
+     * Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
+     *
+     * This is case sensitive, for example "Aa" is not considered a palindrome here.
+     *
+     * Note:
+     * Assume the length of given string will not exceed 1,010.
+     *
+     * Example:
+     *
+     * Input:
+     * "abccccdd"
+     *
+     * Output:
+     * 7
+     *
+     * Explanation:
+     * One longest palindrome that can be built is "dccaccd", whose length is 7.
+     * 思路
+     * 1、先记录每个字符出现的次数
+     * 2、取每个字符出现的最大的偶数
+     * 3、如果还有剩下的单个字符,只取其中的一个
+     * 
+ */ + public int longestPalindrome(String s) { + if (s == null || s.length() < 1) { + return 0; + } + + int[] counter = new int[26]; + // TIP: 这里是大小写不敏感的 + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if (ch >= 'a' && ch <= 'z') { + counter[ch - 'a']++; + } else { + counter[ch - 'A']++; + } + } + + int result = 0; + int left = 0; + for (int value : counter) { + if (value > 0) { + if (value % 2 == 0) { + result += value; +// counter[i] = 0; + } else { + result += value - 1; +// counter[i] = 1; + // 记录还有剩下的1 + left = 1; + } + } + } + + return result + left; + } +} diff --git a/[0412][Fizz Buzz]/[0412][Fizz Buzz].iml b/[0412][Fizz Buzz]/[0412][Fizz Buzz].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0412][Fizz Buzz]/[0412][Fizz Buzz].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0412][Fizz Buzz]/src/Main.java b/[0412][Fizz Buzz]/src/Main.java new file mode 100644 index 0000000..d3164d9 --- /dev/null +++ b/[0412][Fizz Buzz]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 16:37 + **/ +public class Main { + @Test + public void test1() { + String[] array = {"1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"}; + + Solution solution = new Solution(); + + Assert.assertEquals(Arrays.asList(array), solution.fizzBuzz(15)); + + } +} diff --git a/[0412][Fizz Buzz]/src/Solution.java b/[0412][Fizz Buzz]/src/Solution.java new file mode 100644 index 0000000..12a2ebe --- /dev/null +++ b/[0412][Fizz Buzz]/src/Solution.java @@ -0,0 +1,63 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * https://leetcode.com/problems/fizz-buzz/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 16:34 + **/ +public class Solution { + /** + *
+     * Write a program that outputs the string representation of numbers from 1 to n.
+     *
+     * But for multiples of three it should output “Fizz” instead of the number and for
+     * the multiples of five output “Buzz”. For numbers which are multiples of both three
+     * and five output “FizzBuzz”.
+     *
+     * Example:
+     *
+     * n = 15,
+     *
+     * Return:
+     * [
+     *     "1",
+     *     "2",
+     *     "Fizz",
+     *     "4",
+     *     "Buzz",
+     *     "Fizz",
+     *     "7",
+     *     "8",
+     *     "Fizz",
+     *     "Buzz",
+     *     "11",
+     *     "Fizz",
+     *     "13",
+     *     "14",
+     *     "FizzBuzz"
+     * ]
+     * 
+ * + * @param n + * @return + */ + public List fizzBuzz(int n) { + List result = new LinkedList<>(); + + for (int i = 1; i <= n; i++) { + if (i % 15 == 0) { + result.add("FizzBuzz"); + } else if (i % 5 == 0) { + result.add("Buzz"); + } else if (i % 3 == 0) { + result.add("Fizz"); + } else { + result.add("" + i); + } + } + + return result; + } +} diff --git a/[0414][Third Maximum Number]/[0414][Third Maximum Number].iml b/[0414][Third Maximum Number]/[0414][Third Maximum Number].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0414][Third Maximum Number]/[0414][Third Maximum Number].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0414][Third Maximum Number]/src/Main.java b/[0414][Third Maximum Number]/src/Main.java new file mode 100644 index 0000000..ee6c47b --- /dev/null +++ b/[0414][Third Maximum Number]/src/Main.java @@ -0,0 +1,36 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 08:18 + **/ +public class Main { + @Test + public void test1() { + int[] arr = {3, 2, 1}; + Solution solution = new Solution(); + Assert.assertEquals(1, solution.thirdMax(arr)); + } + + @Test + public void test2() { + int[] arr = {2, 1}; + Solution solution = new Solution(); + Assert.assertEquals(2, solution.thirdMax(arr)); + } + + @Test + public void test3() { + int[] arr = {2, 3, 2, 1}; + Solution solution = new Solution(); + Assert.assertEquals(1, solution.thirdMax(arr)); + } + + @Test + public void test4() { + int[] arr = {1, 2, 2, 5, 3, 5}; + Solution solution = new Solution(); + Assert.assertEquals(2, solution.thirdMax(arr)); + } +} diff --git a/[0414][Third Maximum Number]/src/Solution.java b/[0414][Third Maximum Number]/src/Solution.java new file mode 100644 index 0000000..e64ea97 --- /dev/null +++ b/[0414][Third Maximum Number]/src/Solution.java @@ -0,0 +1,56 @@ +import java.util.SortedSet; +import java.util.TreeSet; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 08:09 + **/ +public class Solution { + /** + *
+     * Given a non-empty array of integers, return the third maximum number in this array.
+     * If it does not exist, return the maximum number. The time complexity must be in O(n).
+     *
+     * Example 1:
+     * Input: [3, 2, 1]
+     *
+     * Output: 1
+     *
+     * Explanation: The third maximum is 1.
+     * Example 2:
+     * Input: [1, 2]
+     *
+     * Output: 2
+     *
+     * Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
+     * Example 3:
+     * Input: [2, 2, 3, 1]
+     *
+     * Output: 1
+     *
+     * Explanation: Note that the third maximum here means the third maximum distinct number.
+     * Both numbers with value 2 are both considered as second maximum.
+     * 
+ * + * @param nums + * @return + */ + public int thirdMax(int[] nums) { + SortedSet result = new TreeSet<>(); + + for (int i : nums) { + addResult(i, result); + } + + return result.size() == 3 ? result.first() : result.last(); + } + + private void addResult(int i, SortedSet result) { + if (result.size() < 3) { + result.add(i); + } else if (result.size() == 3 && result.first() < i && !result.contains(i)) { + result.remove(result.first()); + result.add(i); + } + } +} diff --git a/[0415][Add Strings]/[0415][Add Strings].iml b/[0415][Add Strings]/[0415][Add Strings].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0415][Add Strings]/[0415][Add Strings].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0415][Add Strings]/src/Main.java b/[0415][Add Strings]/src/Main.java new file mode 100644 index 0000000..41dfd7a --- /dev/null +++ b/[0415][Add Strings]/src/Main.java @@ -0,0 +1,26 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:35 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals("10000", solution.addStrings("9999", "1")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals("10098", solution.addStrings("9999", "99")); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals("9133", solution.addStrings("9133", "0")); + } +} diff --git a/[0415][Add Strings]/src/Solution.java b/[0415][Add Strings]/src/Solution.java new file mode 100644 index 0000000..6c1cdab --- /dev/null +++ b/[0415][Add Strings]/src/Solution.java @@ -0,0 +1,67 @@ +/** + * https://leetcode.com/problems/add-strings/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:26 + **/ +public class Solution { + /** + *
+     * Given two non-negative integers num1 and num2 represented as string, return the sum of
+     * num1 and num2.
+     *
+     * Note:
+     *
+     * The length of both num1 and num2 is < 5100.
+     * Both num1 and num2 contains only digits 0-9.
+     * Both num1 and num2 does not contain any leading zero.
+     * You must not use any built-in BigInteger library or convert the inputs to integer directly.
+     * 
+ * + * @param num1 + * @param num2 + * @return + */ + public String addStrings(String num1, String num2) { + if (num1.length() > num2.length()) { + // 保证第两个字符串不短于第一个 + return addStrings(num2, num1); + } + + int[] result = new int[num2.length()]; + + int idx1 = num1.length() - 1; + int idx2 = num2.length() - 1; + int idx3 = result.length - 1; + int carry = 0; + while (idx1 >= 0) { + int a = num1.charAt(idx1) - '0'; + int b = num2.charAt(idx2) - '0'; + result[idx3] = (a + b + carry) % 10; + carry = (a + b + carry) / 10; + idx1--; + idx2--; + idx3--; + } + + + // num2还未处理完 + while (idx2 >= 0) { + int a = num2.charAt(idx2) - '0'; + result[idx3] = (a + carry) % 10; + carry = (a + carry) / 10; + idx2--; + idx3--; + } + + StringBuilder builder = new StringBuilder(); + if (carry > 0) { + builder.append(carry); + } + + for (int i : result) { + builder.append(i); + } + return builder.toString(); + } +} diff --git a/[0419][Battleships in a Board]/[0419][Battleships in a Board].iml b/[0419][Battleships in a Board]/[0419][Battleships in a Board].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0419][Battleships in a Board]/[0419][Battleships in a Board].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0419][Battleships in a Board]/src/Main.java b/[0419][Battleships in a Board]/src/Main.java new file mode 100644 index 0000000..1b46aca --- /dev/null +++ b/[0419][Battleships in a Board]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 13:34 + **/ +public class Main { + @Test + public void test1() { + char[][] board = { + {'X', '.', ',', 'X'}, + {'.', '.', ',', 'X'}, + {'.', '.', ',', 'X'} + }; + + Solution solution = new Solution(); + Assert.assertEquals(2, solution.countBattleships(board)); + } +} diff --git a/[0419][Battleships in a Board]/src/Solution.java b/[0419][Battleships in a Board]/src/Solution.java new file mode 100644 index 0000000..0452809 --- /dev/null +++ b/[0419][Battleships in a Board]/src/Solution.java @@ -0,0 +1,34 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 13:23 + **/ +public class Solution { + public int countBattleships(char[][] board) { + + if (board == null || board.length < 1) { + return 0; + } + + int result = 0; + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + // 当前位置是X + if (board[i][j] == 'X') { + // 如果左边一个并且上面一个不是X,说明是战舰的起点 + // 考虑边界情况 + if (i > 0 && j > 0 && board[i - 1][j] != board[i][j] && board[i][j - 1] != board[i][j]) { + result++; + } else if (i > 0 && j == 0 && board[i - 1][j] != board[i][j]) { + result++; + } else if (i == 0 && j > 0 && board[i][j - 1] != board[i][j]) { + result++; + } else if (i == 0 && j == 0) { + result++; + } + } + } + } + + return result; + } +} diff --git a/[0427][Construct Quad Tree]/[0427][Construct Quad Tree].iml b/[0427][Construct Quad Tree]/[0427][Construct Quad Tree].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0427][Construct Quad Tree]/[0427][Construct Quad Tree].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0427][Construct Quad Tree]/src/Main.java b/[0427][Construct Quad Tree]/src/Main.java new file mode 100644 index 0000000..3ff129b --- /dev/null +++ b/[0427][Construct Quad Tree]/src/Main.java @@ -0,0 +1,35 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 21:40 + **/ +public class Main { + @Test + public void test1() { + int[][] grid = { + {1, 1, 1, 1, 0, 0, 0, 0}, + {1, 1, 1, 1, 0, 0, 0, 0}, + {1, 1, 1, 1, 1, 1, 1, 1}, + {1, 1, 1, 1, 1, 1, 1, 1}, + {1, 1, 1, 1, 0, 0, 0, 0}, + {1, 1, 1, 1, 0, 0, 0, 0}, + {1, 1, 1, 1, 0, 0, 0, 0}, + {1, 1, 1, 1, 0, 0, 0, 0}, + }; + + Solution solution = new Solution(); + Node node = solution.construct(grid); + print(node); + } + + private static void print(Node node) { + if (node != null) { + System.out.println("(" + node.isLeaf + ", " + node.val + ")"); + print(node.topLeft); + print(node.topRight); + print(node.bottomLeft); + print(node.bottomRight); + } + } +} diff --git a/[0427][Construct Quad Tree]/src/Node.java b/[0427][Construct Quad Tree]/src/Node.java new file mode 100644 index 0000000..6dbf8a7 --- /dev/null +++ b/[0427][Construct Quad Tree]/src/Node.java @@ -0,0 +1,24 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 21:28 + **/ +public class Node { + public boolean val; + public boolean isLeaf; + public Node topLeft; + public Node topRight; + public Node bottomLeft; + public Node bottomRight; + + public Node() { + } + + public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) { + this.val = val; + this.isLeaf = isLeaf; + this.topLeft = topLeft; + this.topRight = topRight; + this.bottomLeft = bottomLeft; + this.bottomRight = bottomRight; + } +} diff --git a/[0427][Construct Quad Tree]/src/Solution.java b/[0427][Construct Quad Tree]/src/Solution.java new file mode 100644 index 0000000..7489596 --- /dev/null +++ b/[0427][Construct Quad Tree]/src/Solution.java @@ -0,0 +1,62 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 21:27 + **/ +public class Solution { + public Node construct(int[][] grid) { + + if (grid == null) { + return null; + } + + Node node = new Node(); + + construct(node, grid, 0, 0, grid.length); + return node; + } + + private void construct(Node node, int[][] grid, int x, int y, int size) { + + if (size <= 0) { + return; + } + + if (size == 1) { + node.isLeaf = true; + node.val = grid[x][y] == 1; + return; + } + + int half = size / 2; + + Node topLeft = new Node(); + Node topRight = new Node(); + Node bottomLeft = new Node(); + Node bottomRight = new Node(); + + + construct(topLeft, grid, x, y, half); + construct(topRight, grid, x, y + half, half); + construct(bottomLeft, grid, x + half, y, half); + construct(bottomRight, grid, x + half, y + half, half); + + // 四个孩子都是叶子节点,并且值都相等 + if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf) { + if (topLeft.val && topRight.val && bottomLeft.val && bottomRight.val) { + node.isLeaf = true; + node.val = true; + return; + } else if (!topLeft.val && !topRight.val && !bottomLeft.val && !bottomRight.val) { + node.isLeaf = true; + node.val = false; + return; + } + } + + node.isLeaf = false; + node.topLeft = topLeft; + node.topRight = topRight; + node.bottomLeft = bottomLeft; + node.bottomRight = bottomRight; + } +} diff --git a/[0429][N-ary Tree Level Order Traversal]/[0429][N-ary Tree Level Order Traversal].iml b/[0429][N-ary Tree Level Order Traversal]/[0429][N-ary Tree Level Order Traversal].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0429][N-ary Tree Level Order Traversal]/[0429][N-ary Tree Level Order Traversal].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0429][N-ary Tree Level Order Traversal]/src/Main.java b/[0429][N-ary Tree Level Order Traversal]/src/Main.java new file mode 100644 index 0000000..45d4d16 --- /dev/null +++ b/[0429][N-ary Tree Level Order Traversal]/src/Main.java @@ -0,0 +1,47 @@ +import org.junit.Test; + +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-01 14:50 + **/ +public class Main { + @Test + public void test1() { + Node root = new Node(); + root.val = 1; + List children = new LinkedList<>(); + Node n1 = new Node(); + n1.val = 3; + Node n2 = new Node(); + n2.val = 2; + Node n3 = new Node(); + n3.val = 4; + children.add(n1); + children.add(n2); + children.add(n3); + root.children = children; + + List children2 = new LinkedList<>(); + Node n4 = new Node(); + n4.val = 5; + Node n5 = new Node(); + n5.val = 6; + + children2.add(n4); + children2.add(n5); + root.children.get(0).children = children2; + + Solution solution = new Solution(); + System.out.println(solution.levelOrder(root)); + } + + @Test + public void test2() { + + Solution solution = new Solution(); + System.out.println(solution.levelOrder(null)); + } +} diff --git a/[0429][N-ary Tree Level Order Traversal]/src/Node.java b/[0429][N-ary Tree Level Order Traversal]/src/Node.java new file mode 100644 index 0000000..4a21647 --- /dev/null +++ b/[0429][N-ary Tree Level Order Traversal]/src/Node.java @@ -0,0 +1,18 @@ +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-01 14:44 + **/ +public class Node { + public int val; + public List children; + + public Node() { + } + + public Node(int val, List children) { + this.val = val; + this.children = children; + } +} diff --git a/[0429][N-ary Tree Level Order Traversal]/src/Solution.java b/[0429][N-ary Tree Level Order Traversal]/src/Solution.java new file mode 100644 index 0000000..029474e --- /dev/null +++ b/[0429][N-ary Tree Level Order Traversal]/src/Solution.java @@ -0,0 +1,37 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-01 14:44 + **/ +public class Solution { + public List> levelOrder(Node root) { + List> result = new LinkedList<>(); + List currLayer = new LinkedList<>(); + List nextLayer = new LinkedList<>(); + + + if (root != null) { + currLayer.add(root); + } + while (!currLayer.isEmpty()) { + + List layer = new LinkedList<>(); + for (Node node : currLayer) { + layer.add(node.val); + if (node.children != null && !node.children.isEmpty()) { + nextLayer.addAll(node.children); + } + } + + result.add(layer); + currLayer.clear(); + List temp = currLayer; + currLayer = nextLayer; + nextLayer = temp; + } + + return result; + } +} diff --git a/[0434][Number of Segments in a String]/[0434][Number of Segments in a String].iml b/[0434][Number of Segments in a String]/[0434][Number of Segments in a String].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0434][Number of Segments in a String]/[0434][Number of Segments in a String].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0434][Number of Segments in a String]/src/Main.java b/[0434][Number of Segments in a String]/src/Main.java new file mode 100644 index 0000000..2c05cb7 --- /dev/null +++ b/[0434][Number of Segments in a String]/src/Main.java @@ -0,0 +1,15 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 16:51 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + Assert.assertEquals(5, solution.countSegments("Hello, my name is John")); + } +} diff --git a/[0434][Number of Segments in a String]/src/Solution.java b/[0434][Number of Segments in a String]/src/Solution.java new file mode 100644 index 0000000..8fd15cf --- /dev/null +++ b/[0434][Number of Segments in a String]/src/Solution.java @@ -0,0 +1,49 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 16:44 + **/ +public class Solution { + /** + *
+     * Count the number of segments in a string, where a segment is defined to be a
+     * contiguous sequence of non-space characters.
+     *
+     * Please note that the string does not contain any non-printable characters.
+     *
+     * Example:
+     *
+     * Input: "Hello, my name is John"
+     * Output: 5
+     * 
+ * + * @param s + * @return + */ + public int countSegments(String s) { + int count = 0; + if (s == null || s.length() < 1) { + return count; + } + + int start = 0; + int end; + while (start < s.length()) { + while (start < s.length() && s.charAt(start) == ' ') { + start++; + } + + end = start + 1; + while (end < s.length() && s.charAt(end) != ' ') { + end++; + } + + if (start < s.length()) { + count++; + } + + start = end + 1; + } + + return count; + } +} diff --git a/[0437][Path Sum III]/[0437][Path Sum III].iml b/[0437][Path Sum III]/[0437][Path Sum III].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0437][Path Sum III]/[0437][Path Sum III].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0437][Path Sum III]/src/Main.java b/[0437][Path Sum III]/src/Main.java new file mode 100644 index 0000000..30b8b7d --- /dev/null +++ b/[0437][Path Sum III]/src/Main.java @@ -0,0 +1,98 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:56 + **/ +public class Main { + @Test + public void test1() { + TreeNode root = new TreeNode(10); + root.left = new TreeNode(5); + root.right = new TreeNode(-3); + root.left.left = new TreeNode(3); + root.left.right = new TreeNode(2); + root.left.left.left = new TreeNode(3); + root.left.left.right = new TreeNode(-2); + root.left.right.right = new TreeNode(1); + root.right.right = new TreeNode(11); + + Solution solution = new Solution(); + Assert.assertEquals(3, solution.pathSum(root, 8)); + } + + @Test + public void test2() { + TreeNode root = new TreeNode(10); + root.left = new TreeNode(5); + root.right = new TreeNode(-3); + root.left.left = new TreeNode(3); + root.left.right = new TreeNode(2); + root.left.left.left = new TreeNode(3); + root.left.left.right = new TreeNode(-2); + root.left.right.right = new TreeNode(1); + root.right.right = new TreeNode(11); + + Solution solution = new Solution(); + Assert.assertEquals(2, solution.pathSum(root.left, 8)); + } + + @Test + public void test3() { + TreeNode root = new TreeNode(10); + root.left = new TreeNode(5); + root.right = new TreeNode(-3); + root.left.left = new TreeNode(3); + root.left.right = new TreeNode(2); + root.left.left.left = new TreeNode(3); + root.left.left.right = new TreeNode(-2); + root.left.right.right = new TreeNode(1); + root.right.right = new TreeNode(11); + + Solution solution = new Solution(); + Assert.assertEquals(1, solution.pathSum(root.left.right, 3)); + } + + @Test + public void test4() { + TreeNode root = new TreeNode(10); + root.left = new TreeNode(5); + root.right = new TreeNode(-3); + root.left.left = new TreeNode(3); + root.left.right = new TreeNode(2); + root.left.left.left = new TreeNode(3); + root.left.left.right = new TreeNode(-2); + root.left.right.right = new TreeNode(1); + root.right.right = new TreeNode(11); + + Solution solution = new Solution(); + Assert.assertEquals(1, solution.pathSum(root.right, 8)); + } + + @Test + public void test5() { + TreeNode root = new TreeNode(1); + root.left = new TreeNode(-2); + root.left.left = new TreeNode(1); + root.left.right = new TreeNode(3); + root.left.left.left = new TreeNode(-1); + root.right = new TreeNode(-3); + root.right.left = new TreeNode(-2); + + Solution solution = new Solution(); + Assert.assertEquals(3, solution.pathSum(root, 1)); + + } + + @Test + public void test6() { + TreeNode root = new TreeNode(1); + root.left = new TreeNode(0); + root.right = new TreeNode(0); + + Solution solution = new Solution(); + Assert.assertEquals(3, solution.pathSum(root, 1)); + + } +} diff --git a/[0437][Path Sum III]/src/Solution.java b/[0437][Path Sum III]/src/Solution.java new file mode 100644 index 0000000..bbbf7ae --- /dev/null +++ b/[0437][Path Sum III]/src/Solution.java @@ -0,0 +1,55 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:50 + **/ + +public class Solution { + + // 自身不作为结果的部分,为了防止向上冒泡出错 + public int pathSum(TreeNode root, int sum) { + return pathSumHelp(root, sum, false); + } + + /** + * @param root + * @param sum + * @param withParent 父节点是否是结果的一部分 + * @return + */ + private int pathSumHelp(TreeNode root, int sum, boolean withParent) { + if (root == null) { + return 0; + } + + int result = 0; + if (sum == root.val) { + // 到不当前不向下走,是一种方案 + result++; + if (root.left == null && root.right == null) { + return result; + } + } + + if (withParent) { + if (root.left != null) { + result += pathSumHelp(root.left, sum - root.val, true); + } + + if (root.right != null) { + result += pathSumHelp(root.right, sum - root.val, true); + } + } else { + if (root.left != null) { + result += pathSumHelp(root.left, sum - root.val, true); + result += pathSumHelp(root.left, sum, false); + } + + if (root.right != null) { + result += pathSumHelp(root.right, sum - root.val, true); + result += pathSumHelp(root.right, sum, false); + } + } + return result; + } + +} diff --git a/[0437][Path Sum III]/src/TreeNode.java b/[0437][Path Sum III]/src/TreeNode.java new file mode 100644 index 0000000..23d0f71 --- /dev/null +++ b/[0437][Path Sum III]/src/TreeNode.java @@ -0,0 +1,14 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 04:50 + **/ +public class TreeNode { + + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} \ No newline at end of file diff --git a/[0438][Find All Anagrams in a String]/[0438][Find All Anagrams in a String].iml b/[0438][Find All Anagrams in a String]/[0438][Find All Anagrams in a String].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0438][Find All Anagrams in a String]/[0438][Find All Anagrams in a String].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0438][Find All Anagrams in a String]/src/Main.java b/[0438][Find All Anagrams in a String]/src/Main.java new file mode 100644 index 0000000..9dbfbc2 --- /dev/null +++ b/[0438][Find All Anagrams in a String]/src/Main.java @@ -0,0 +1,22 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-08 20:07 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(Arrays.asList(0, 6), solution.findAnagrams("cbaebabacd", "abc")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(Arrays.asList(0, 1, 2), solution.findAnagrams("abab", "ab")); + } +} diff --git a/[0438][Find All Anagrams in a String]/src/Solution.java b/[0438][Find All Anagrams in a String]/src/Solution.java new file mode 100644 index 0000000..8e32c89 --- /dev/null +++ b/[0438][Find All Anagrams in a String]/src/Solution.java @@ -0,0 +1,78 @@ +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-08 18:59 + **/ +public class Solution { + /** + *
+     * Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
+     *
+     * Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
+     *
+     * The order of output does not matter.
+     *
+     * Example 1:
+     *
+     * Input:
+     * s: "cbaebabacd" p: "abc"
+     *
+     * Output:
+     * [0, 6]
+     *
+     * Explanation:
+     * The substring with start index = 0 is "cba", which is an anagram of "abc".
+     * The substring with start index = 6 is "bac", which is an anagram of "abc".
+     * Example 2:
+     *
+     * Input:
+     * s: "abab" p: "ab"
+     *
+     * Output:
+     * [0, 1, 2]
+     *
+     * Explanation:
+     * The substring with start index = 0 is "ab", which is an anagram of "ab".
+     * The substring with start index = 1 is "ba", which is an anagram of "ab".
+     * The substring with start index = 2 is "ab", which is an anagram of "ab".
+     * 
+ * + * @param s + * @param p + * @return + */ + public List findAnagrams(String s, String p) { + List result = new LinkedList<>(); + + if (s.length() < p.length()) { + return result; + } + + int[] pArr = new int[26]; + int[] sArr = new int[26]; + + for (int i = 0; i < p.length(); i++) { + pArr[p.charAt(i) - 'a']++; + } + + for (int i = 0; i < p.length(); i++) { + sArr[s.charAt(i) - 'a']++; + } + + for (int i = 0; i <= s.length() - p.length(); i++) { + if (i > 0) { + sArr[s.charAt(i - 1) - 'a']--; + sArr[s.charAt(i + p.length() - 1) - 'a']++; + } + + if (Arrays.equals(sArr, pArr)) { + result.add(i); + } + } + + return result; + } +} diff --git a/[0438][Find All Anagrams in a String]/src/Solution2.java b/[0438][Find All Anagrams in a String]/src/Solution2.java new file mode 100644 index 0000000..1f805b7 --- /dev/null +++ b/[0438][Find All Anagrams in a String]/src/Solution2.java @@ -0,0 +1,114 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-08 18:59 + **/ +public class Solution2 { + /** + *
+     * Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
+     *
+     * Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
+     *
+     * The order of output does not matter.
+     *
+     * Example 1:
+     *
+     * Input:
+     * s: "cbaebabacd" p: "abc"
+     *
+     * Output:
+     * [0, 6]
+     *
+     * Explanation:
+     * The substring with start index = 0 is "cba", which is an anagram of "abc".
+     * The substring with start index = 6 is "bac", which is an anagram of "abc".
+     * Example 2:
+     *
+     * Input:
+     * s: "abab" p: "ab"
+     *
+     * Output:
+     * [0, 1, 2]
+     *
+     * Explanation:
+     * The substring with start index = 0 is "ab", which is an anagram of "ab".
+     * The substring with start index = 1 is "ba", which is an anagram of "ab".
+     * The substring with start index = 2 is "ab", which is an anagram of "ab".
+     * 
+ * + * @param s + * @param p + * @return + */ + public List findAnagrams(String s, String p) { + List result = new LinkedList<>(); + + if (s.length() < p.length()) { + return result; + } + + Map map1 = getMap(p); + Map map2 = getMap(s.substring(0, p.length())); + for (int i = 0; i <= s.length() - p.length(); i++) { + + char lastChar = s.charAt(i + p.length() - 1); + char prevChar; + if (i > 0 && (prevChar = s.charAt(i - 1)) != lastChar) { + Integer val = map2.get(prevChar); + if (val <= 1) { + map2.remove(prevChar); + } else { + map2.put(prevChar, val - 1); + } + + val = map2.get(lastChar); + if (val == null) { + map2.put(lastChar, 1); + } else { + map2.put(lastChar, val + 1); + } + } + + if (equals(map1, map2)) { + result.add(i); + } + } + return result; + } + + private boolean equals(Map map1, Map map2) { + if (map1.size() == map2.size()) { + return contains(map1, map2) && contains(map2, map1); + } + return false; + } + + /** + * map1是否包含map2,即map2中的(k, v)都在map1中 + * + * @param map1 + * @param map2 + * @return + */ + private boolean contains(Map map1, Map map2) { + for (Map.Entry e : map2.entrySet()) { + Integer v2 = map1.get(e.getKey()); + if (!map1.containsKey(e.getKey()) || !Objects.equals(e.getValue(), v2)) { + return false; + } + } + return true; + } + + + public Map getMap(String s) { + Map map = new HashMap<>(); + + for (int i = 0; i < s.length(); i++) { + map.merge(s.charAt(i), 1, Integer::sum); + } + return map; + } +} diff --git a/[0441][Arranging Coins]/[0441][Arranging Coins].iml b/[0441][Arranging Coins]/[0441][Arranging Coins].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0441][Arranging Coins]/[0441][Arranging Coins].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0441][Arranging Coins]/src/Solution.java b/[0441][Arranging Coins]/src/Solution.java new file mode 100644 index 0000000..f1c8291 --- /dev/null +++ b/[0441][Arranging Coins]/src/Solution.java @@ -0,0 +1,83 @@ +//You have a total of n coins that you want to form in a staircase shape, where +//every k-th row must have exactly k coins. +// +// Given n, find the total number of full staircase rows that can be formed. +// +// n is a non-negative integer and fits within the range of a 32-bit signed inte +//ger. +// +// Example 1: +// +//n = 5 +// +//The coins can form the following rows: +//¤ +//¤ ¤ +//¤ ¤ +// +//Because the 3rd row is incomplete, we return 2. +// +// +// +// Example 2: +// +//n = 8 +// +//The coins can form the following rows: +//¤ +//¤ ¤ +//¤ ¤ ¤ +//¤ ¤ +// +//Because the 4th row is incomplete, we return 3. +// +// Related Topics Math Binary Search + + +//leetcode submit region begin(Prohibit modification and deletion) + +/** + * Author: 王俊超 + * Time: 2020-06-25 14:22 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 本质是求最大的整数x,使得 x >= n - x(x + 1)/2 >= 0 + * ==> + * 2x >= 2n - x^2 - x >= 0 + * ==> + * x^2 + 3x >= 2n >= x^2 + x + * + * @param n + * @return + */ + public int arrangeCoins(int n) { + + if (n <= 0) { + return 0; + } + + long t = 2 * (long) (n); + + long x = (long) Math.sqrt(t); + + while (true) { + if (x * x + 3 * x < t) { + x++; + continue; + } + if (x * x + x > t) { + x--; + continue; + } + + break; + } + + return (int) x; + } +} +//leetcode submit region end(Prohibit modification and deletion) diff --git a/[0441][Arranging Coins]/src/SolutionTest.java b/[0441][Arranging Coins]/src/SolutionTest.java new file mode 100644 index 0000000..378df37 --- /dev/null +++ b/[0441][Arranging Coins]/src/SolutionTest.java @@ -0,0 +1,35 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * Author: 王俊超 + * Time: 2020-06-25 14:32 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + @Test + public void test1() { + Solution s = new Solution(); + + int[][] data = { + {-1, 0}, + {0, 0}, + {1, 1}, + {2, 1}, + {5, 2}, + {8, 3}, + {10, 4}, + {11, 4}, + {12, 4}, + {13, 4}, + {14, 4}, + {15, 5}, + }; + + for (int[] d : data) { + Assert.assertEquals(s.arrangeCoins(d[0]), d[1]); + } + } +} diff --git a/[0442][Find All Duplicates in an Array]/[0442][Find All Duplicates in an Array].iml b/[0442][Find All Duplicates in an Array]/[0442][Find All Duplicates in an Array].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0442][Find All Duplicates in an Array]/[0442][Find All Duplicates in an Array].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0442][Find All Duplicates in an Array]/src/Main.java b/[0442][Find All Duplicates in an Array]/src/Main.java new file mode 100644 index 0000000..77f2555 --- /dev/null +++ b/[0442][Find All Duplicates in an Array]/src/Main.java @@ -0,0 +1,17 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 14:08 + **/ +public class Main { + @Test + public void test1() { + int[] nums = {4, 3, 2, 7, 8, 2, 3, 1}; + Solution solution = new Solution(); + Assert.assertEquals(Arrays.asList(2, 3), solution.findDuplicates(nums)); + } +} diff --git a/[0442][Find All Duplicates in an Array]/src/Solution.java b/[0442][Find All Duplicates in an Array]/src/Solution.java new file mode 100644 index 0000000..15e0aea --- /dev/null +++ b/[0442][Find All Duplicates in an Array]/src/Solution.java @@ -0,0 +1,28 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 13:49 + **/ +public class Solution { + public List findDuplicates(int[] nums) { + List result = new ArrayList<>(); + + if (nums == null || nums.length < 1) { + return result; + } + + Set set = new HashSet<>(); + + for (int i : nums) { + if (set.contains(i)) { + result.add(i); + } else { + set.add(i); + } + } + + Collections.sort(result); + return result; + } +} diff --git a/[0442][Find All Duplicates in an Array]/src/Solution2.java b/[0442][Find All Duplicates in an Array]/src/Solution2.java new file mode 100644 index 0000000..3a26109 --- /dev/null +++ b/[0442][Find All Duplicates in an Array]/src/Solution2.java @@ -0,0 +1,44 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 13:49 + **/ +public class Solution2 { + public List findDuplicates(int[] nums) { + List result = new ArrayList<>(); + + if (nums == null || nums.length < 1) { + return result; + } + + int idx = 1; + + while (idx <= nums.length) { + // 如果nums[9-1] != 9 说明还没有调整到位置 + // nums[idx-1] == nums[nums[idx-1] - 1]说明有同样的值出现 + while (nums[idx - 1] != idx && nums[idx - 1] != nums[nums[idx - 1] - 1]) { + swap(nums, idx - 1, nums[idx - 1] - 1); + } + + idx++; + } + + for (int i = 1; i <= nums.length; i++) { + if (nums[i - 1] != i) { + result.add(nums[i - 1]); + } + } + + Collections.sort(result); + return result; + } + + private void swap(int[] nums, int x, int y) { + int temp = nums[x]; + nums[x] = nums[y]; + nums[y] = temp; + } +} diff --git a/[0443][String Compression]/[0443][String Compression].iml b/[0443][String Compression]/[0443][String Compression].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0443][String Compression]/[0443][String Compression].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0443][String Compression]/src/Solution.java b/[0443][String Compression]/src/Solution.java new file mode 100644 index 0000000..487f236 --- /dev/null +++ b/[0443][String Compression]/src/Solution.java @@ -0,0 +1,76 @@ +/** + * Author: 王俊超 + * Time: 2020-06-26 07:29 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 从向前处理 + * + * @param chars + * @return + */ + public int compress(char[] chars) { + if (chars == null || chars.length == 0) { + return 0; + } + + int end; + int start = 0; + int length = 0; + while (start < chars.length) { + end = start + 1; + while (end < chars.length && chars[start] == chars[end]) { + end++; + } + + String num = "" + (end - start); + + length += 1; + if (end - start > 1) { // 有重复的字符 + length += num.length(); // 重复字符的个数 + int tmp = start + 1; + for (int i = 0; i < num.length(); i++) { + chars[tmp] = num.charAt(i); + tmp++; + } + + while (tmp < end) { // 不需要的字符清零 + chars[tmp] = 0; + tmp++; + } + } + + start = end; // 开始处理下一个字符 + + } + + + // 找第一个0值的字符位置 + start = 0; + while (start < chars.length && chars[start] != 0) { + start++; + } + + end = start; + while (end < chars.length) { + // 找start位置之后第一个值不为0的位置 + while (end < chars.length && chars[end] == 0) { + end++; + } + + // 将end及之后不为0的值向前移动 + while (end < chars.length && chars[end] != 0) { + chars[start] = chars[end]; + start++; + end++; + } + + } + + + return length; + } +} diff --git a/[0443][String Compression]/src/SolutionTest.java b/[0443][String Compression]/src/SolutionTest.java new file mode 100644 index 0000000..278614c --- /dev/null +++ b/[0443][String Compression]/src/SolutionTest.java @@ -0,0 +1,41 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * Author: 王俊超 + * Time: 2020-06-26 07:51 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + @Test + public void test1() { + Solution s = new Solution(); + Object[][] data = { +// {null,null, 0}, +// {"","", 0}, +// {"a","a", 1}, +// {"aabbccc", "a2b2c3", 6}, +// {"abbbbbbbbbbbb","ab12", 4}, +// {"abcdefg","abcdefg", 7}, +// {"aaab","a3b", 3}, +// {"aaabcccc","a3bc4", 5}, + {"aaabbbccc", "a3b3c3", 6}, + }; + + for (Object[] d : data) { + + if (d[0] == null) { + Assert.assertNull(d[1]); + Assert.assertEquals(0, d[2]); + continue; + } + + char[] arr = ((String) (d[0])).toCharArray(); + int length = s.compress(arr); + Assert.assertEquals(length, d[2]); + Assert.assertEquals(new String(arr, 0, length), d[1]); + } + } +} diff --git a/[0447][Number of Boomerangs]/[0447][Number of Boomerangs].iml b/[0447][Number of Boomerangs]/[0447][Number of Boomerangs].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0447][Number of Boomerangs]/[0447][Number of Boomerangs].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0447][Number of Boomerangs]/src/Solution.java b/[0447][Number of Boomerangs]/src/Solution.java new file mode 100644 index 0000000..102a1df --- /dev/null +++ b/[0447][Number of Boomerangs]/src/Solution.java @@ -0,0 +1,69 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * Author: 王俊超 + * Time: 2020-06-26 16:47 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int numberOfBoomerangs(int[][] points) { + int count = 0; + if (points == null || points.length < 2) { + return count; + } + Map map = new HashMap<>(); + + for (int i = 0; i < points.length; i++) { + for (int j = 0; j < points.length; j++) { + + if (i == j) { + continue; + } + int square = square(points[i], points[j]); + if (!map.containsKey(square)) { + map.put(square, 1); + } else { + count += map.get(square) * 2; // A + int oldCount = map.get(square); + map.put(square, oldCount + 1); + } + } + + // 如果不在A处理,那么对于大于1的value,取组合值 + // C(2, n) * 2 = 1*2*...*(n-2)*2 + // 放在A处理进行了分散处理 + + map.clear(); + } + + return count; + + } + + public int numberOfBoomerangsSlow(int[][] points) { + + int answer = 0; + for (int i = 0; i < points.length; i++) { + for (int j = i + 1; j < points.length; j++) { + for (int k = 0; k < points.length; k++) { + if (k != i && k != j && square(points[k], points[i]) == square(points[k], points[j])) { + answer += 2; + } + } + } + } + + return answer; + } + + public int square(int[] a, int[] b) { + int x = a[0] - b[0]; + int y = a[1] - b[1]; + + return x * x + y * y; + } + +} diff --git a/[0447][Number of Boomerangs]/src/SolutionTest.java b/[0447][Number of Boomerangs]/src/SolutionTest.java new file mode 100644 index 0000000..b961285 --- /dev/null +++ b/[0447][Number of Boomerangs]/src/SolutionTest.java @@ -0,0 +1,26 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * Author: 王俊超 + * Time: 2020-06-26 16:55 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + @Test + public void test1() { + Solution s = new Solution(); + Object[][] data = { +// {new int[][]{{0, 0}, {1, 0}, {2, 0}}, 2}, +// {new int[][]{{1, 1}, {2, 2}, {3, 3}}, 2}, + {new int[][]{{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}}, 20} + }; + + for (Object[] d : data) { + Assert.assertEquals(d[1], s.numberOfBoomerangs((int[][]) d[0])); + } + + } +} diff --git a/[0448][Find All Numbers Disappeared in an Array]/[0448][Find All Numbers Disappeared in an Array].iml b/[0448][Find All Numbers Disappeared in an Array]/[0448][Find All Numbers Disappeared in an Array].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0448][Find All Numbers Disappeared in an Array]/[0448][Find All Numbers Disappeared in an Array].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0448][Find All Numbers Disappeared in an Array]/src/Main.java b/[0448][Find All Numbers Disappeared in an Array]/src/Main.java new file mode 100644 index 0000000..bf39e15 --- /dev/null +++ b/[0448][Find All Numbers Disappeared in an Array]/src/Main.java @@ -0,0 +1,14 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 08:38 + **/ +public class Main { + @Test + public void test1() { + int[] arr = {4, 3, 2, 7, 8, 2, 3, 1}; + Solution solution = new Solution(); + System.out.println(solution.findDisappearedNumbers(arr)); + } +} diff --git a/[0448][Find All Numbers Disappeared in an Array]/src/Solution.java b/[0448][Find All Numbers Disappeared in an Array]/src/Solution.java new file mode 100644 index 0000000..b85015a --- /dev/null +++ b/[0448][Find All Numbers Disappeared in an Array]/src/Solution.java @@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 08:29 + **/ +public class Solution { + /** + *
+     * Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear
+     * twice and others appear once.
+     *
+     * Find all the elements of [1, n] inclusive that do not appear in this array.
+     *
+     * Could you do it without extra space and in O(n) runtime? You may assume the returned list
+     * does not count as extra space.
+     *
+     * Example:
+     *
+     * Input:
+     * [4,3,2,7,8,2,3,1]
+     *
+     * Output:
+     * [5,6]
+     * 
+ * + * @param nums + * @return + */ + public List findDisappearedNumbers(int[] nums) { + + // i表示第几个元素,从1开始计数 + for (int i = 1; i <= nums.length; i++) { + // nums[idx - 1] != idx 对于nums[8] = 9的情况 + // nums[idx - 1] == nums[nums[idx - 1] - 1] 位置被占用了,表示有相同的数 + while (nums[i - 1] != i && nums[i - 1] != nums[nums[i - 1] - 1]) { + swap(nums, i - 1, nums[i - 1] - 1); + } + } + + List result = new ArrayList<>(); + for (int i = 1; i <= nums.length; i++) { + if (nums[i - 1] != i) { + result.add(i); + } + } + + return result; + } + + private void swap(int[] nums, int x, int y) { + int tmp = nums[x]; + nums[x] = nums[y]; + nums[y] = tmp; + } +} diff --git a/[0453][Minimum Moves to Equal Array Elements]/[0453][Minimum Moves to Equal Array Elements].iml b/[0453][Minimum Moves to Equal Array Elements]/[0453][Minimum Moves to Equal Array Elements].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0453][Minimum Moves to Equal Array Elements]/[0453][Minimum Moves to Equal Array Elements].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0453][Minimum Moves to Equal Array Elements]/src/Solution.java b/[0453][Minimum Moves to Equal Array Elements]/src/Solution.java new file mode 100644 index 0000000..395fde3 --- /dev/null +++ b/[0453][Minimum Moves to Equal Array Elements]/src/Solution.java @@ -0,0 +1,40 @@ +/** + * Author: 王俊超 + * Time: 2020-06-28 21:38 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 解题思路: + * 假设数组最小的值是xmin,一共加了k次,加完后的值是W,元素个数是n + * 则:W <= xmin + k + * k(n-1) + sum(nums) = W*n + * ==> + * k(n-1) + sum(nums) <= (xmin + k)n + * ==> + * sum(nums) - n*xmin <= k + * + * @param nums + * @return + */ + public int minMoves(int[] nums) { + + if (nums == null) { + return 0; + } + + int sum = 0; + int min = Integer.MAX_VALUE; + + for (int i : nums) { + sum += i; + if (i < min) { + min = i; + } + } + + return sum - min * nums.length; + } +} diff --git a/[0453][Minimum Moves to Equal Array Elements]/src/SolutionTest.java b/[0453][Minimum Moves to Equal Array Elements]/src/SolutionTest.java new file mode 100644 index 0000000..1b8b239 --- /dev/null +++ b/[0453][Minimum Moves to Equal Array Elements]/src/SolutionTest.java @@ -0,0 +1,27 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.lang.annotation.Target; + +/** + * Author: 王俊超 + * Time: 2020-06-28 22:09 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + @Test + public void test1() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{1, 2, 3}, 3}, + {new int[]{1, 1, 1}, 0}, + {new int[]{1, 1, 2}, 1}, + }; + + for (Object[] d : data) { + Assert.assertEquals(s.minMoves((int[]) d[0]), d[1]); + } + } +} diff --git a/[0455][Assign Cookies]/[0455][Assign Cookies].iml b/[0455][Assign Cookies]/[0455][Assign Cookies].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0455][Assign Cookies]/[0455][Assign Cookies].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0455][Assign Cookies]/src/Main.java b/[0455][Assign Cookies]/src/Main.java new file mode 100644 index 0000000..3fa2f79 --- /dev/null +++ b/[0455][Assign Cookies]/src/Main.java @@ -0,0 +1,24 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 08:39 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] g = {1, 2, 3}; + int[] s = {1, 1}; + Assert.assertEquals(1, solution.findContentChildren(g, s)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + int[] g = {1, 2}; + int[] s = {1, 2, 3}; + Assert.assertEquals(2, solution.findContentChildren(g, s)); + } +} diff --git a/[0455][Assign Cookies]/src/Solution.java b/[0455][Assign Cookies]/src/Solution.java new file mode 100644 index 0000000..58f164e --- /dev/null +++ b/[0455][Assign Cookies]/src/Solution.java @@ -0,0 +1,82 @@ +import java.util.Arrays; + +/** + * https://leetcode.com/problems/assign-cookies/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 08:30 + **/ +public class Solution { + /** + *
+     * Assume you are an awesome parent and want to give your children some cookies.
+     * But, you should give each child at most one cookie. Each child i has a greed
+     * factor gi, which is the minimum size of a cookie that the child will be content
+     * with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j
+     * to the child i, and the child i will be content. Your goal is to maximize the
+     * number of your content children and output the maximum number.
+     *
+     * Note:
+     * You may assume the greed factor is always positive.
+     * You cannot assign more than one cookie to one child.
+     *
+     * Example 1:
+     * Input: [1,2,3], [1,1]
+     *
+     * Output: 1
+     *
+     * Explanation: You have 3 children and 2 cookies. The greed factors of 3 children
+     * are 1, 2, 3.
+     * And even though you have 2 cookies, since their size is both 1, you could only
+     * make the child whose greed factor is 1 content.
+     * You need to output 1.
+     * Example 2:
+     * Input: [1,2], [1,2,3]
+     *
+     * Output: 2
+     *
+     * Explanation: You have 2 children and 3 cookies. The greed factors of 2 children
+     * are 1, 2.
+     * You have 3 cookies and their sizes are big enough to gratify all of the children,
+     * You need to output 2.
+     * 思路:
+     * 先将饼干尺寸和小孩需求都排个序,然后从小到大去遍历地给。
+     * 
+ * + * @param g + * @param s + * @return + */ + public int findContentChildren(int[] g, int[] s) { + if (g == null || g.length < 1 || s == null || s.length < 1) { + return 0; + } + + int result = 0; + + // 先对两个数组进行排序 + Arrays.sort(g); + Arrays.sort(s); + + int gIdx = 0; + int sIdx = 0; + + while (gIdx < g.length && sIdx < s.length) { + while (sIdx < s.length && g[gIdx] > s[sIdx]) { + sIdx++; + } + + // 说明对于gIdx的贪婪值,sIdx可以满足 + if (sIdx < s.length) { + result++; + } + + // 如下一一个小孩的贪婪值 + gIdx++; + // 下一个饼干的位置 + sIdx++; + } + + return result; + } +} diff --git a/[0459][Repeated Substring Pattern]/[0459][Repeated Substring Pattern].iml b/[0459][Repeated Substring Pattern]/[0459][Repeated Substring Pattern].iml new file mode 100644 index 0000000..73f33e3 --- /dev/null +++ b/[0459][Repeated Substring Pattern]/[0459][Repeated Substring Pattern].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0459][Repeated Substring Pattern]/src/Main.java b/[0459][Repeated Substring Pattern]/src/Main.java new file mode 100644 index 0000000..b0b82c3 --- /dev/null +++ b/[0459][Repeated Substring Pattern]/src/Main.java @@ -0,0 +1,26 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 17:10 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.repeatedSubstringPattern("abab")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(false, solution.repeatedSubstringPattern("abb")); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals(true, solution.repeatedSubstringPattern("abcabcabcabc")); + } +} diff --git a/[0459][Repeated Substring Pattern]/src/Solution.java b/[0459][Repeated Substring Pattern]/src/Solution.java new file mode 100644 index 0000000..9dca883 --- /dev/null +++ b/[0459][Repeated Substring Pattern]/src/Solution.java @@ -0,0 +1,68 @@ +import java.util.Objects; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 17:37 + **/ +public class Solution { + /** + *
+     * Given a non-empty string check if it can be constructed by taking a substring of it
+     * and appending multiple copies of the substring together. You may assume the given
+     * string consists of lowercase English letters only and its length will not exceed 10000.
+     *
+     *
+     *
+     * Example 1:
+     *
+     * Input: "abab"
+     * Output: True
+     * Explanation: It's the substring "ab" twice.
+     * Example 2:
+     *
+     * Input: "aba"
+     * Output: False
+     * Example 3:
+     *
+     * Input: "abcabcabcabc"
+     * Output: True
+     * Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
+     * 思路:
+     * 从[half, 1]到时如某个数可以被整除,假定其是s.substring(0, k)的子串的重复,进行验证
+     * 
+ * + * @param s + * @return + */ + public boolean repeatedSubstringPattern(String s) { + + if (s == null || s.length() < 2) { + return false; + } + + int i = s.length() / 2; + while (i > 0) { + if (s.length() % i == 0) { + boolean repeated = true; + for (int j = i; j < s.length(); j += i) { + // 如果不相等于,退出for循环 + if (!equals(s.substring(0, i), s.substring(j, j + i))) { + repeated = false; + break; + } + } + if (repeated) { + return true; + } + } + + i--; + } + + return false; + } + + private boolean equals(String s, String t) { + return Objects.equals(s, t); + } +} diff --git a/[0461][Hamming Distance]/[0461][Hamming Distance].iml b/[0461][Hamming Distance]/[0461][Hamming Distance].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0461][Hamming Distance]/[0461][Hamming Distance].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0461][Hamming Distance]/src/Main.java b/[0461][Hamming Distance]/src/Main.java new file mode 100644 index 0000000..9504141 --- /dev/null +++ b/[0461][Hamming Distance]/src/Main.java @@ -0,0 +1,14 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 09:29 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(2, solution.hammingDistance(4, 1)); + } +} diff --git a/[0461][Hamming Distance]/src/Solution.java b/[0461][Hamming Distance]/src/Solution.java new file mode 100644 index 0000000..7204175 --- /dev/null +++ b/[0461][Hamming Distance]/src/Solution.java @@ -0,0 +1,56 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 09:25 + **/ +public class Solution { + /** + *
+     * The Hamming distance between two integers is the number of positions at which
+     * the corresponding bits are different.
+     *
+     * Given two integers x and y, calculate the Hamming distance.
+     *
+     * Note:
+     * 0 ≤ x, y < 231.
+     *
+     * Example:
+     *
+     * Input: x = 1, y = 4
+     *
+     * Output: 2
+     *
+     * Explanation:
+     * 1   (0 0 0 1)
+     * 4   (0 1 0 0)
+     *        ↑   ↑
+     *
+     * The above arrows point to positions where the corresponding bits are different.
+     * 
+ * + * @param x + * @param y + * @return + */ + public int hammingDistance(int x, int y) { + int result = 0; + while (x > 0 && y > 0) { + int xLeft = x % 2; + int yLeft = y % 2; + x /= 2; + y /= 2; + + result += xLeft ^ yLeft; + } + + if (y > 0) { + x = y; + } + + while (x > 0) { + result += x % 2; + x /= 2; + } + + return result; + } +} diff --git a/[0463][Island Perimeter]/[0463][Island Perimeter].iml b/[0463][Island Perimeter]/[0463][Island Perimeter].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0463][Island Perimeter]/[0463][Island Perimeter].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0463][Island Perimeter]/src/Main.java b/[0463][Island Perimeter]/src/Main.java new file mode 100644 index 0000000..9b79f56 --- /dev/null +++ b/[0463][Island Perimeter]/src/Main.java @@ -0,0 +1,30 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 13:07 + **/ +public class Main { + @Test + public void test1() { + int[][] grid = { + {0, 1, 0, 0}, + {1, 1, 1, 0}, + {0, 1, 0, 0}, + {1, 1, 0, 0}}; + Solution solution = new Solution(); + Assert.assertEquals(16, solution.islandPerimeter(grid)); + } + + @Test + public void test2() { + int[][] grid = { + {1, 1, 1, 1}, + {1, 1, 1, 1}, + {1, 1, 1, 1}, + {1, 1, 1, 1}}; + Solution solution = new Solution(); + Assert.assertEquals(16, solution.islandPerimeter(grid)); + } +} diff --git a/[0463][Island Perimeter]/src/Solution.java b/[0463][Island Perimeter]/src/Solution.java new file mode 100644 index 0000000..c17b74f --- /dev/null +++ b/[0463][Island Perimeter]/src/Solution.java @@ -0,0 +1,86 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 12:58 + **/ +public class Solution { + + /** + *
+     * You are given a map in form of a two-dimensional integer grid where 1 represents
+     * land and 0 represents water.
+     *
+     * Grid cells are connected horizontally/vertically (not diagonally). The grid is
+     * completely surrounded by water, and there is exactly one island (i.e., one or more
+     * connected land cells).
+     *
+     * The island doesn't have "lakes" (water inside that isn't connected to the water around
+     * the island). One cell is a square with side length 1. The grid is rectangular, width
+     * and height don't exceed 100. Determine the perimeter of the island.
+     *
+     * Example:
+     *
+     * Input:
+     * [[0,1,0,0],
+     *  [1,1,1,0],
+     *  [0,1,0,0],
+     *  [1,1,0,0]]
+     *
+     * Output: 16
+     *
+     * Explanation: The perimeter is the 16 yellow stripes in the image below:
+     * 
+ * + * @param grid + * @return + */ + public int islandPerimeter(int[][] grid) { + + // 假定输入都是合法的 + + int perimeter = 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 0) { + // 上一格 + if (i > 0 && grid[i - 1][j] == 1) { + perimeter++; + } + + // 下一格 + if (i + 1 < grid.length && grid[i + 1][j] == 1) { + perimeter++; + } + + // 左一格 + if (j > 0 && grid[i][j - 1] == 1) { + perimeter++; + } + + // 右一格 + if (j + 1 < grid[0].length && grid[i][j + 1] == 1) { + perimeter++; + } + } + } + } + + // 如果在第一列和最后一列,第一行和最后一行有一,要再加上1出现的数次数 + + for (int i = 0; i < grid.length; i++) { + // 第一列有一 + perimeter += grid[i][0]; + // 最后一列有一 + perimeter += grid[i][grid[0].length - 1]; + } + + for (int i = 0; i < grid[0].length; i++) { + // 第一行有一 + perimeter += grid[0][i]; + // 最后一行有一 + perimeter += grid[grid.length - 1][i]; + } + + return perimeter; + } +} diff --git a/[0463][Island Perimeter]/src/Solution2.java b/[0463][Island Perimeter]/src/Solution2.java new file mode 100644 index 0000000..bde8363 --- /dev/null +++ b/[0463][Island Perimeter]/src/Solution2.java @@ -0,0 +1,96 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 12:58 + **/ +public class Solution2 { + + /** + *
+     * You are given a map in form of a two-dimensional integer grid where 1 represents
+     * land and 0 represents water.
+     *
+     * Grid cells are connected horizontally/vertically (not diagonally). The grid is
+     * completely surrounded by water, and there is exactly one island (i.e., one or more
+     * connected land cells).
+     *
+     * The island doesn't have "lakes" (water inside that isn't connected to the water around
+     * the island). One cell is a square with side length 1. The grid is rectangular, width
+     * and height don't exceed 100. Determine the perimeter of the island.
+     *
+     * Example:
+     *
+     * Input:
+     * [[0,1,0,0],
+     *  [1,1,1,0],
+     *  [0,1,0,0],
+     *  [1,1,0,0]]
+     *
+     * Output: 16
+     *
+     * Explanation: The perimeter is the 16 yellow stripes in the image below:
+     * 
+ * + * @param grid + * @return + */ + public int islandPerimeter(int[][] grid) { + + // 假定输入都是合法的 + + int perimeter = 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 0) { + // 上一格 + if (i > 0 && grid[i - 1][j] == 1) { + perimeter++; + } + + // 下一格 + if (i + 1 < grid.length && grid[i + 1][j] == 1) { + perimeter++; + } + + // 左一格 + if (j > 0 && grid[i][j - 1] == 1) { + perimeter++; + } + + // 右一格 + if (j + 1 < grid[0].length && grid[i][j + 1] == 1) { + perimeter++; + } + } + } + } + + // 如果在第一列和最后一列,第一行和最后一行有一,要再加上1出现的数次数 + + for (int i = 0; i < grid.length; i++) { + // 第一列有一 + if (grid[i][0] == 1) { + perimeter++; + } + + // 最后一列有一 + if (grid[i][grid[0].length - 1] == 1) { + perimeter++; + } + } + + for (int i = 0; i < grid[0].length; i++) { + // 第一行有一 + if (grid[0][i] == 1) { + perimeter++; + } + + // 最后一行有一 + if (grid[grid.length - 1][i] == 1) { + perimeter++; + } + } + + return perimeter; + } +} diff --git a/[0463][Island Perimeter]/src/island.png b/[0463][Island Perimeter]/src/island.png new file mode 100644 index 0000000..76254a7 Binary files /dev/null and b/[0463][Island Perimeter]/src/island.png differ diff --git a/[0475][Heaters]/[0475][Heaters].iml b/[0475][Heaters]/[0475][Heaters].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0475][Heaters]/[0475][Heaters].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0475][Heaters]/src/Main.java b/[0475][Heaters]/src/Main.java new file mode 100644 index 0000000..e675886 --- /dev/null +++ b/[0475][Heaters]/src/Main.java @@ -0,0 +1,17 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 09:30 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + int[] houses = {1, 2, 3, 4}; + int[] heaters = {1, 4}; + Assert.assertEquals(1, solution.findRadius(houses, heaters)); + } +} diff --git a/[0475][Heaters]/src/Solution.java b/[0475][Heaters]/src/Solution.java new file mode 100644 index 0000000..e353380 --- /dev/null +++ b/[0475][Heaters]/src/Solution.java @@ -0,0 +1,75 @@ +import java.util.Arrays; + +/** + * https://leetcode.com/problems/heaters/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 08:58 + **/ +public class Solution { + /** + *
+     * Winter is coming! Your first job during the contest is to design a standard heater
+     * with fixed warm radius to warm all the houses.
+     *
+     * Now, you are given positions of houses and heaters on a horizontal line, find out
+     * minimum radius of heaters so that all houses could be covered by those heaters.
+     *
+     * So, your input will be the positions of houses and heaters seperately, and your
+     * expected output will be the minimum radius standard of heaters.
+     *
+     * Note:
+     *
+     * Numbers of houses and heaters you are given are non-negative and will not exceed
+     * 25000.
+     * Positions of houses and heaters you are given are non-negative and will not exceed
+     * 10^9.
+     * As long as a house is in the heaters' warm radius range, it can be warmed.
+     * All the heaters follow your radius standard and the warm radius will the same.
+     *
+     *
+     * Example 1:
+     *
+     * Input: [1,2,3],[2]
+     * Output: 1
+     * Explanation: The only heater was placed in the position 2, and if we use the
+     * radius 1 standard, then all the houses can be warmed.
+     *
+     *
+     * Example 2:
+     *
+     * Input: [1,2,3,4],[1,4]
+     * Output: 1
+     * Explanation: The two heater was placed in the position 1 and 4. We need to use
+     * radius 1 standard, then all the houses can be warmed.
+     * 
+ */ + public int findRadius(int[] houses, int[] heaters) { + if (houses == null || houses.length < 1 || heaters == null || heaters.length < 1) { + return 0; + } + + // 对houses和heaters位置进行排序 + Arrays.sort(houses); + Arrays.sort(heaters); + + int result = 0; + int idx = 0; + + for (int h : houses) { + // 找离house最近的heater位置 + // A----X------B => 取A + // A------X----B => 取B + // A-----X-----B => 取B + while (idx < heaters.length - 1 && heaters[idx] + heaters[idx + 1] <= h * 2) { + idx++; + } + + // 更新最小的结果 + // Math.abs(heaters[idx] - h) 表示h的最小加热半径 + result = Math.max(result, Math.abs(heaters[idx] - h)); + } + + return result; + } +} diff --git a/[0476][Number Complement]/[0476][Number Complement].iml b/[0476][Number Complement]/[0476][Number Complement].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0476][Number Complement]/[0476][Number Complement].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0476][Number Complement]/src/Main.java b/[0476][Number Complement]/src/Main.java new file mode 100644 index 0000000..e8b1722 --- /dev/null +++ b/[0476][Number Complement]/src/Main.java @@ -0,0 +1,27 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 16:17 + **/ +public class Main { + + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals(2, solution.findComplement(5)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals(1, solution.findComplement(0)); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals(0, solution.findComplement(1)); + } +} diff --git a/[0476][Number Complement]/src/Solution.java b/[0476][Number Complement]/src/Solution.java new file mode 100644 index 0000000..a992057 --- /dev/null +++ b/[0476][Number Complement]/src/Solution.java @@ -0,0 +1,41 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 16:06 + **/ +public class Solution { + /** + *
+     * Given a positive integer, output its complement number. The complement strategy is to
+     * flip the bits of its binary representation.
+     *
+     * Note:
+     * The given integer is guaranteed to fit within the range of a 32-bit signed integer.
+     * You could assume no leading zero bit in the integer’s binary representation.
+     * Example 1:
+     * Input: 5
+     * Output: 2
+     * Explanation: The binary representation of 5 is 101 (no leading zero bits), and its
+     * complement is 010. So you need to output 2.
+     * Example 2:
+     * Input: 1
+     * Output: 0
+     * Explanation: The binary representation of 1 is 1 (no leading zero bits), and its
+     * complement is 0. So you need to output 0.
+     * 
+ * + * @param num + * @return + */ + public int findComplement(int num) { + int result = 0; + int move = 0; + + do { + result += (1 ^ (num % 2)) << move; + move++; + num >>>= 1; + } while (num > 0); + + return result; + } +} diff --git a/[0482][License Key Formatting]/[0482][License Key Formatting].iml b/[0482][License Key Formatting]/[0482][License Key Formatting].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0482][License Key Formatting]/[0482][License Key Formatting].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0482][License Key Formatting]/src/Main.java b/[0482][License Key Formatting]/src/Main.java new file mode 100644 index 0000000..98414b8 --- /dev/null +++ b/[0482][License Key Formatting]/src/Main.java @@ -0,0 +1,38 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 09:49 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals("5F3Z-2E9W", solution.licenseKeyFormatting("5F3Z-2e-9-w", 4)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals("2-5G-3J", solution.licenseKeyFormatting("2-5g-3-J", 2)); + } + + @Test + public void test3() { + Solution solution = new Solution(); + Assert.assertEquals("2-5-G-3-J", solution.licenseKeyFormatting("2-5g-3-J", 1)); + } + + @Test + public void test4() { + Solution solution = new Solution(); + Assert.assertEquals("25G3J", solution.licenseKeyFormatting("2-5g-3-J", 10)); + } + + @Test + public void test5() { + Solution solution = new Solution(); + Assert.assertEquals("", solution.licenseKeyFormatting("---", 3)); + } +} diff --git a/[0482][License Key Formatting]/src/Solution.java b/[0482][License Key Formatting]/src/Solution.java new file mode 100644 index 0000000..d9e9120 --- /dev/null +++ b/[0482][License Key Formatting]/src/Solution.java @@ -0,0 +1,80 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 09:38 + **/ +public class Solution { + /** + *
+     * You are given a license key represented as a string S which consists only alphanumeric
+     * character and dashes. The string is separated into N+1 groups by N dashes.
+     *
+     * Given a number K, we would want to reformat the strings such that each group contains
+     * exactly K characters, except for the first group which could be shorter than K, but
+     * still must contain at least one character. Furthermore, there must be a dash inserted
+     * between two groups and all lowercase letters should be converted to uppercase.
+     *
+     * Given a non-empty string S and a number K, format the string according to the rules
+     * described above.
+     *
+     * Example 1:
+     * Input: S = "5F3Z-2e-9-w", K = 4
+     *
+     * Output: "5F3Z-2E9W"
+     *
+     * Explanation: The string S has been split into two parts, each part has 4 characters.
+     * Note that the two extra dashes are not needed and can be removed.
+     * Example 2:
+     * Input: S = "2-5g-3-J", K = 2
+     *
+     * Output: "2-5G-3J"
+     *
+     * Explanation: The string S has been split into three parts, each part has 2 characters
+     * except the first part as it could be shorter as mentioned above.
+     * Note:
+     * The length of string S will not exceed 12,000, and K is a positive integer.
+     * String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
+     * String S is non-empty.
+     *
+     * 思路:
+     * 从后向前处理,每k个分成一个组
+     * 
+ * + * @param s + * @param k + * @return + */ + public String licenseKeyFormatting(String s, int k) { + if (k < 1 || s == null || s.length() < 1) { + throw new IllegalArgumentException("s: " + s + ", k: " + k); + } + + StringBuilder builder = new StringBuilder(s.length()); + + + int idx = s.length() - 1; + while (idx >= 0) { + int count = 0; + while (idx >= 0 && count < k) { + char ch = s.charAt(idx); + if (Character.isLetterOrDigit(ch)) { + builder.append(Character.toUpperCase(ch)); + count++; + } + + idx--; + } + + if (count == k) { + builder.append('-'); + } + } + + String result = builder.reverse().toString(); + + if (result.isEmpty()) { + return ""; + } + + return result.charAt(0) == '-' ? result.substring(1) : result; + } +} diff --git a/[0485][Max Consecutive Ones]/[0485][Max Consecutive Ones].iml b/[0485][Max Consecutive Ones]/[0485][Max Consecutive Ones].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0485][Max Consecutive Ones]/[0485][Max Consecutive Ones].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0485][Max Consecutive Ones]/src/Main.java b/[0485][Max Consecutive Ones]/src/Main.java new file mode 100644 index 0000000..7a42c82 --- /dev/null +++ b/[0485][Max Consecutive Ones]/src/Main.java @@ -0,0 +1,22 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 19:20 + **/ +public class Main { + @Test + public void test1() { + int[] nums = {1, 1, 0, 1, 1, 1}; + Solution solution = new Solution(); + Assert.assertEquals(3, solution.findMaxConsecutiveOnes(nums)); + } + + @Test + public void test2() { + int[] nums = {0}; + Solution solution = new Solution(); + Assert.assertEquals(0, solution.findMaxConsecutiveOnes(nums)); + } +} diff --git a/[0485][Max Consecutive Ones]/src/Solution.java b/[0485][Max Consecutive Ones]/src/Solution.java new file mode 100644 index 0000000..0003950 --- /dev/null +++ b/[0485][Max Consecutive Ones]/src/Solution.java @@ -0,0 +1,47 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 19:16 + **/ +public class Solution { + /** + *
+     * Given a binary array, find the maximum number of consecutive 1s in this array.
+     *
+     * Example 1:
+     * Input: [1,1,0,1,1,1]
+     * Output: 3
+     * Explanation: The first two digits or the last three digits are consecutive 1s.
+     *     The maximum number of consecutive 1s is 3.
+     * Note:
+     *
+     * The input array will only contain 0 and 1.
+     * The length of input array is a positive integer and will not exceed 10,000
+     * 
+ * + * @param nums + * @return + */ + public int findMaxConsecutiveOnes(int[] nums) { + + int result = 0; + int start = 0; + int end; + while (start < nums.length) { + while (start < nums.length && nums[start] != 1) { + start++; + } + + end = start + 1; + while (end < nums.length && nums[end] == 1) { + end++; + } + + if (start < nums.length) { + result = Math.max(result, end - start); + } + start = end; + } + + return result; + } +} diff --git a/[0492][Construct the Rectangle]/[0492][Construct the Rectangle].iml b/[0492][Construct the Rectangle]/[0492][Construct the Rectangle].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0492][Construct the Rectangle]/[0492][Construct the Rectangle].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0492][Construct the Rectangle]/src/Main.java b/[0492][Construct the Rectangle]/src/Main.java new file mode 100644 index 0000000..c1d633d --- /dev/null +++ b/[0492][Construct the Rectangle]/src/Main.java @@ -0,0 +1,14 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 10:02 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{2, 2}, solution.constructRectangle(4)); + } +} diff --git a/[0492][Construct the Rectangle]/src/Solution.java b/[0492][Construct the Rectangle]/src/Solution.java new file mode 100644 index 0000000..834f7ce --- /dev/null +++ b/[0492][Construct the Rectangle]/src/Solution.java @@ -0,0 +1,58 @@ +/** + * https://leetcode.com/problems/construct-the-rectangle/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-10 09:59 + **/ +public class Solution { + /** + *
+     * For a web developer, it is very important to know how to design a web page's size.
+     * So, given a specific rectangular web page’s area, your job by now is to design a
+     * rectangular web page, whose length L and width W satisfy the following requirements:
+     *
+     * 1. The area of the rectangular web page you designed must equal to the given target area.
+     *
+     * 2. The width W should not be larger than the length L, which means L >= W.
+     *
+     * 3. The difference between length L and width W should be as small as possible.
+     * You need to output the length L and the width W of the web page you designed in sequence.
+     * Example:
+     * Input: 4
+     * Output: [2, 2]
+     * Explanation: The target area is 4, and all the possible ways to construct it are
+     * [1,4], [2,2], [4,1].
+     * But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1]
+     * is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
+     * Note:
+     * The given area won't exceed 10,000,000 and is a positive integer
+     * The web page's width and length you designed must be positive integers.
+     * 
+ * + * @param area + * @return + */ + public int[] constructRectangle(int area) { + if (area < 1) { + throw new IllegalArgumentException("area: " + area); + } + + int[] result = {0, 0}; + + // 求平方根 + int width = (int) Math.sqrt(area); + + // width从平方根开始减少 + while (width > 0) { + if (area % width == 0) { + result[0] = area / width; + result[1] = width; + break; + } + + width--; + } + + return result; + } +} diff --git a/[0496][Next Greater Element I]/[0496][Next Greater Element I].iml b/[0496][Next Greater Element I]/[0496][Next Greater Element I].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0496][Next Greater Element I]/[0496][Next Greater Element I].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0496][Next Greater Element I]/src/Main.java b/[0496][Next Greater Element I]/src/Main.java new file mode 100644 index 0000000..e328516 --- /dev/null +++ b/[0496][Next Greater Element I]/src/Main.java @@ -0,0 +1,24 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 19:35 + **/ +public class Main { + @Test + public void test1() { + int[] nums1 = {4, 1, 2}; + int[] nums2 = {1, 3, 4, 2}; + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{-1, 3, -1}, solution.nextGreaterElement(nums1, nums2)); + } + + @Test + public void test2() { + int[] nums1 = {2, 4}; + int[] nums2 = {1, 2, 3, 4}; + Solution solution = new Solution(); + Assert.assertArrayEquals(new int[]{3, -1}, solution.nextGreaterElement(nums1, nums2)); + } +} diff --git a/[0496][Next Greater Element I]/src/Solution.java b/[0496][Next Greater Element I]/src/Solution.java new file mode 100644 index 0000000..922c812 --- /dev/null +++ b/[0496][Next Greater Element I]/src/Solution.java @@ -0,0 +1,65 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 19:30 + **/ +public class Solution { + /** + *
+     * You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements
+     * are subset of nums2. Find all the next greater numbers for nums1's elements in the
+     * corresponding places of nums2.
+     *
+     * The Next Greater Number of a number x in nums1 is the first greater number to its
+     * right in nums2. If it does not exist, output -1 for this number.
+     *
+     * Example 1:
+     * Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
+     * Output: [-1,3,-1]
+     * Explanation:
+     *     For number 4 in the first array, you cannot find the next greater number for it
+     *     in the second array, so output -1.
+     *
+     *     For number 1 in the first array, the next greater number for it in the second
+     *     array is 3.
+     *
+     *     For number 2 in the first array, there is no next greater number for it in the
+     *     second array, so output -1.
+     * Example 2:
+     * Input: nums1 = [2,4], nums2 = [1,2,3,4].
+     * Output: [3,-1]
+     * Explanation:
+     *     For number 2 in the first array, the next greater number for it in the second
+     *     array is 3.
+     *
+     *     For number 4 in the first array, there is no next greater number for it in the
+     *     second array, so output -1.
+     * 
+ */ + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + + Map map = new HashMap<>(); + for (int i = 0; i < nums2.length; i++) { + map.put(nums2[i], i); + } + + int[] result = new int[nums1.length]; + + for (int i = 0; i < nums1.length; i++) { + int n = -1; + boolean find = false; + for (int j = map.get(nums1[i]) + 1; j < nums2.length && !find; j++) { + if (nums1[i] < nums2[j]) { + n = nums2[j]; + find = true; + } + } + + result[i] = n; + } + + return result; + } +} diff --git a/[0500][Keyboard Row]/[0500][Keyboard Row].iml b/[0500][Keyboard Row]/[0500][Keyboard Row].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0500][Keyboard Row]/[0500][Keyboard Row].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0500][Keyboard Row]/src/Main.java b/[0500][Keyboard Row]/src/Main.java new file mode 100644 index 0000000..d761a70 --- /dev/null +++ b/[0500][Keyboard Row]/src/Main.java @@ -0,0 +1,15 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 10:39 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + Assert.assertArrayEquals(new String[]{"Alaska", "Dad"}, solution.findWords(new String[]{"Hello", "Alaska", "Dad", "Peace"})); + } +} diff --git a/[0500][Keyboard Row]/src/Solution.java b/[0500][Keyboard Row]/src/Solution.java new file mode 100644 index 0000000..d0cf17b --- /dev/null +++ b/[0500][Keyboard Row]/src/Solution.java @@ -0,0 +1,46 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * https://leetcode.com/problems/keyboard-row/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 10:25 + **/ +public class Solution { + + + public String[] findWords(String[] words) { + String[] lines = { + "`1234567890-=~!@#$%^&*()_+", + "qwertyuiop[]\\QWERTYUIOP{}|", + "asdfghjkl;'ASDFGHJKL:\"", + "zxcvbnm,./ZXCVBNM<>?"}; + + if (words == null || words.length < 1) { + return words; + } + + List result = new LinkedList<>(); + for (String s : words) { + for (String l : lines) { + if (contains(l, s)) { + result.add(s); + break; + } + } + } + + return result.toArray(new String[0]); + } + + private boolean contains(String s, String t) { + for (int i = 0; i < t.length(); i++) { + if (s.indexOf(t.charAt(i)) < 0) { + return false; + } + + } + return true; + } +} diff --git a/[0501][Find Mode in Binary Search Tree]/[0501][Find Mode in Binary Search Tree].iml b/[0501][Find Mode in Binary Search Tree]/[0501][Find Mode in Binary Search Tree].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0501][Find Mode in Binary Search Tree]/[0501][Find Mode in Binary Search Tree].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0501][Find Mode in Binary Search Tree]/src/Main.java b/[0501][Find Mode in Binary Search Tree]/src/Main.java new file mode 100644 index 0000000..862d639 --- /dev/null +++ b/[0501][Find Mode in Binary Search Tree]/src/Main.java @@ -0,0 +1,19 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 11:26 + **/ +public class Main { + @Test + public void test1() { + TreeNode root = new TreeNode(1); + root.right = new TreeNode(2); + root.right.right = new TreeNode(2); + + Solution solution = new Solution(); + + Assert.assertArrayEquals(new int[]{2}, solution.findMode(root)); + } +} diff --git a/[0501][Find Mode in Binary Search Tree]/src/Solution.java b/[0501][Find Mode in Binary Search Tree]/src/Solution.java new file mode 100644 index 0000000..5b104f5 --- /dev/null +++ b/[0501][Find Mode in Binary Search Tree]/src/Solution.java @@ -0,0 +1,47 @@ +import java.util.*; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-11 11:08 + **/ +public class Solution { + public int[] findMode(TreeNode root) { + SortedMap map = new TreeMap<>(); + + findMode(root, map); + + int max = 0; + for (int v : map.values()) { + if (max < v) { + max = v; + } + } + + List list = new LinkedList<>(); + for (Map.Entry e : map.entrySet()) { + if (e.getValue() == max) { + list.add(e.getKey()); + } + } + + int[] result = new int[list.size()]; + int i = 0; + for (int v : list) { + result[i] = v; + i++; + } + return result; + } + + private void findMode(TreeNode root, SortedMap map) { + if (root == null) { + return; + } + + Integer count = map.get(root.val); + map.put(root.val, count == null ? 1 : count + 1); + findMode(root.left, map); + findMode(root.right, map); + + } +} diff --git a/[0501][Find Mode in Binary Search Tree]/src/TreeNode.java b/[0501][Find Mode in Binary Search Tree]/src/TreeNode.java new file mode 100644 index 0000000..8b88e24 --- /dev/null +++ b/[0501][Find Mode in Binary Search Tree]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Date: 2015-08-21 + * Time: 18:45 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} + diff --git a/[0504][Base 7]/[0504][Base 7].iml b/[0504][Base 7]/[0504][Base 7].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0504][Base 7]/[0504][Base 7].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0504][Base 7]/src/Main.java b/[0504][Base 7]/src/Main.java new file mode 100644 index 0000000..beb80aa --- /dev/null +++ b/[0504][Base 7]/src/Main.java @@ -0,0 +1,20 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 20:00 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + Assert.assertEquals("202", solution.convertToBase7(100)); + } + + @Test + public void test2() { + Solution solution = new Solution(); + Assert.assertEquals("-10", solution.convertToBase7(-7)); + } +} diff --git a/[0504][Base 7]/src/Solution.java b/[0504][Base 7]/src/Solution.java new file mode 100644 index 0000000..62947d6 --- /dev/null +++ b/[0504][Base 7]/src/Solution.java @@ -0,0 +1,34 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-06 19:59 + **/ +public class Solution { + /** + *
+     * Given an integer, return its base 7 string representation.
+     *
+     * Example 1:
+     * Input: 100
+     * Output: "202"
+     * Example 2:
+     * Input: -7
+     * Output: "-10"
+     * Note: The input will be in range of [-1e7, 1e7].
+     * 
+ * + * @param num + * @return + */ + public String convertToBase7(int num) { + String result = ""; + boolean positive = num >= 0; + num = Math.abs(num); + + do { + result = (num % 7) + result; + num /= 7; + } while (num > 0); + + return positive ? result : "-" + result; + } +} diff --git a/[0506][Relative Ranks]/[0506][Relative Ranks].iml b/[0506][Relative Ranks]/[0506][Relative Ranks].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0506][Relative Ranks]/[0506][Relative Ranks].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0506][Relative Ranks]/src/Solution.java b/[0506][Relative Ranks]/src/Solution.java new file mode 100644 index 0000000..3cc25f6 --- /dev/null +++ b/[0506][Relative Ranks]/src/Solution.java @@ -0,0 +1,139 @@ +import java.util.*; + +/** + * Author: 王俊超 + * Time: 2020-06-29 07:34 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + + class Rank { + Rank(int s, int i) { + this.Score = s; + this.Index = i; + } + int Score; + int Index; + } + + /** + * 题解思路: + * 1、记录分数对应的下标; + * 2、对分数进行排序,求行排名 + * 3、再根据分数将原始数组的下标和排名对应起来 + * + * @param nums + * @return + */ + public String[] findRelativeRanks(int[] nums) { + if (nums == null) { + return null; + } + + Rank[] ranks = new Rank[nums.length]; + for (int i = 0; i < nums.length; i++) { + ranks[i] = new Rank(nums[i], i); + } + + Arrays.sort(ranks, new Comparator() { + @Override + public int compare(Rank o1, Rank o2) { + return -(o1.Score - o2.Score); + } + }); + + String[] result = new String[nums.length]; + for (int i = 0; i < ranks.length; i++) { + switch (i) { + case 0: + result[ranks[i].Index] = "Gold Medal"; + break; + case 1: + result[ranks[i].Index] = "Silver Medal"; + break; + + case 2: + result[ranks[i].Index] = "Bronze Medal"; + break; + default: + result[ranks[i].Index] = "" + (i + 1); + } + } + return result; + } + + public String[] findRelativeRanks3(int[] nums) { + if (nums == null) { + return null; + } + + Map map = new HashMap<>(); + Queue queue = new PriorityQueue<>(nums.length + 1); // 使用优先堆,加1是为了防止参数为0 + + for (int i = 0; i < nums.length; i++) { + map.put(nums[i], i); + queue.add(nums[i]); // 创建小顶堆 + } + + + String[] result = new String[nums.length]; + int i = nums.length + 1; + while (!queue.isEmpty()) { + int score = queue.poll(); + i--; + switch (i) { + case 1: + result[map.get(score)] = "Gold Medal"; + break; + case 2: + result[map.get(score)] = "Silver Medal"; + break; + case 3: + result[map.get(score)] = "Bronze Medal"; + break; + default: + result[map.get(score)] = "" + i; + } + + } + + return result; + } + + public String[] findRelativeRanks2(int[] nums) { + if (nums == null) { + return null; + } + + Map map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + map.put(nums[i], i); + } + + String[] result = new String[nums.length]; + Arrays.sort(nums); + + for (int i = 0; i < nums.length; i++) { + int score = nums[nums.length - 1 - i]; + switch (i) { + case 0: + result[map.get(score)] = "Gold Medal"; + break; + case 1: + result[map.get(score)] = "Silver Medal"; + break; + + case 2: + result[map.get(score)] = "Bronze Medal"; + break; + default: + result[map.get(score)] = "" + (i + 1); + } + } + + return result; + } +} diff --git a/[0506][Relative Ranks]/src/SolutionTest.java b/[0506][Relative Ranks]/src/SolutionTest.java new file mode 100644 index 0000000..6af869f --- /dev/null +++ b/[0506][Relative Ranks]/src/SolutionTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * Author: 王俊超 + * Time: 2020-06-29 07:46 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @Test + public void test1() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{5, 4, 3, 2, 1}, new String[]{"Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"}}, + {new int[]{1, 2, 3, 4, 5}, new String[]{"5", "4", "Bronze Medal", "Silver Medal", "Gold Medal"}}, + }; + + for (Object[] d: data) { + Assert.assertArrayEquals(s.findRelativeRanks((int[]) d[0]), (Object[]) d[1]); + } + } +} diff --git a/[0507][Perfect Number]/[0507][Perfect Number].iml b/[0507][Perfect Number]/[0507][Perfect Number].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0507][Perfect Number]/[0507][Perfect Number].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0507][Perfect Number]/src/Solution.java b/[0507][Perfect Number]/src/Solution.java new file mode 100644 index 0000000..036581e --- /dev/null +++ b/[0507][Perfect Number]/src/Solution.java @@ -0,0 +1,26 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 08:33 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public boolean checkPerfectNumber(int num) { + if (num < 6) { + return false; + } + + int sum = 1; + int sqrt = (int) Math.sqrt(num); + + for (int i = 2; i <= sqrt; i++) { + if (num % i == 0) { + sum += i; + sum += num / i; + } + } + + return sum == num; + } +} diff --git a/[0507][Perfect Number]/src/SolutionTest.java b/[0507][Perfect Number]/src/SolutionTest.java new file mode 100644 index 0000000..287f91d --- /dev/null +++ b/[0507][Perfect Number]/src/SolutionTest.java @@ -0,0 +1,29 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-06-29 08:36 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void checkPerfectNumber() { + Solution s = new Solution(); + Object[][] data = { + {28, true}, + {-1, false}, + {0, false}, + {1, false}, + {6, true}, + {7, false}, + {8, false}, + }; + + for (Object[] d: data) { + Assert.assertEquals(s.checkPerfectNumber((Integer) d[0]), d[1]); + } + } +} \ No newline at end of file diff --git a/[0509][Fibonacci Number]/[0509][Fibonacci Number].iml b/[0509][Fibonacci Number]/[0509][Fibonacci Number].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0509][Fibonacci Number]/[0509][Fibonacci Number].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0509][Fibonacci Number]/src/Solution.java b/[0509][Fibonacci Number]/src/Solution.java new file mode 100644 index 0000000..4e5fa95 --- /dev/null +++ b/[0509][Fibonacci Number]/src/Solution.java @@ -0,0 +1,27 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 08:44 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int fib(int N) { + if (N <= 0) { + return 0; + } else if (N == 1) { + return 1; + } + + int n2 = 0; + int n1 = 1; + int n0; + for (int i = 2; i <= N; i++) { + n0 = n1 + n2; + n2 = n1; + n1 = n0; + } + + return n1; + } +} diff --git a/[0509][Fibonacci Number]/src/SolutionTest.java b/[0509][Fibonacci Number]/src/SolutionTest.java new file mode 100644 index 0000000..c959dd8 --- /dev/null +++ b/[0509][Fibonacci Number]/src/SolutionTest.java @@ -0,0 +1,26 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-06-29 08:48 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void fib() { + Solution s = new Solution(); + Object[][] data = { + {0, 0}, + {1, 1}, + {2, 1}, + {3, 2}, + }; + + for (Object[] d : data) { + Assert.assertEquals(s.fib((Integer) d[0]), d[1]); + } + } +} \ No newline at end of file diff --git "a/\343\200\220004\343\200\221\343\200\220MedianofTwoSortedArrays\343\200\221/\343\200\220004\343\200\221\343\200\220MedianofTwoSortedArrays\343\200\221.iml" b/[0520][Detect Capital]/[0520][Detect Capital].iml similarity index 100% rename from "\343\200\220004\343\200\221\343\200\220MedianofTwoSortedArrays\343\200\221/\343\200\220004\343\200\221\343\200\220MedianofTwoSortedArrays\343\200\221.iml" rename to [0520][Detect Capital]/[0520][Detect Capital].iml diff --git a/[0520][Detect Capital]/src/Solution.java b/[0520][Detect Capital]/src/Solution.java new file mode 100644 index 0000000..c8c6c13 --- /dev/null +++ b/[0520][Detect Capital]/src/Solution.java @@ -0,0 +1,73 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 08:42 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + *
+     * Given a word, you need to judge whether the usage of capitals in it is right or not.
+     *
+     * We define the usage of capitals in a word to be right when one of the following
+     * cases holds:
+     *
+     * All letters in this word are capitals, like "USA".
+     * All letters in this word are not capitals, like "leetcode".
+     * Only the first letter in this word is capital, like "Google".
+     * Otherwise, we define that this word doesn't use capitals in a right way.
+     *
+     *
+     * Example 1:
+     *
+     * Input: "USA"
+     * Output: True
+     *
+     *
+     * Example 2:
+     *
+     * Input: "FlaG"
+     * Output: False
+     *
+     *
+     * Note: The input will be a non-empty word consisting of uppercase
+     * and lowercase latin letters.
+     * 
+ * + * @param word + * @return + */ + public boolean detectCapitalUse(String word) { + + if (Character.isUpperCase(word.charAt(0))) { + return isAllUpperCase(word.substring(1)) || isAllLowerCase(word.substring(1)); + } else if (Character.isLowerCase(word.charAt(0))) { + return isAllLowerCase(word.substring(1)); + } + + return false; + } + + private boolean isAllLowerCase(String s) { + for (int i = 0; i < s.length(); i++) { + if (!Character.isLowerCase(s.charAt(i))) { + return false; + } + } + + return true; + } + + private boolean isAllUpperCase(String s) { + + for (int i = 0; i < s.length(); i++) { + if (!Character.isUpperCase(s.charAt(i))) { + return false; + } + } + + return true; + } +} + diff --git "a/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221.iml" b/[0521][Longest Uncommon Subsequence I]/[0521][Longest Uncommon Subsequence I].iml similarity index 100% rename from "\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221.iml" rename to [0521][Longest Uncommon Subsequence I]/[0521][Longest Uncommon Subsequence I].iml diff --git a/[0521][Longest Uncommon Subsequence I]/src/Solution.java b/[0521][Longest Uncommon Subsequence I]/src/Solution.java new file mode 100644 index 0000000..7f99841 --- /dev/null +++ b/[0521][Longest Uncommon Subsequence I]/src/Solution.java @@ -0,0 +1,20 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 08:55 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * @param a + * @param b + * @return + */ + public int findLUSlength(String a, String b) { + if (a.equals(b)) { + return -1; + } + return Math.max(a.length(), b.length()); + } +} diff --git a/[0523][K Diff Pairs In An Array]/[0523][K Diff Pairs In An Array].iml b/[0523][K Diff Pairs In An Array]/[0523][K Diff Pairs In An Array].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0523][K Diff Pairs In An Array]/[0523][K Diff Pairs In An Array].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0523][K Diff Pairs In An Array]/src/Solution.java b/[0523][K Diff Pairs In An Array]/src/Solution.java new file mode 100644 index 0000000..c461f31 --- /dev/null +++ b/[0523][K Diff Pairs In An Array]/src/Solution.java @@ -0,0 +1,40 @@ +import java.util.Arrays; + +/** + * Author: 王俊超 + * Time: 2020-06-30 08:52 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int findPairs(int[] nums, int k) { + if (nums == null || nums.length < 2 || k < 0) { + return 0; + } + + int result = 0; + + Arrays.sort(nums); + + for (int i = 0; i < nums.length - 1;i++) { + + for (int j = i + 1; j < nums.length && nums[j] - nums[i] <= k; j++) { + while (j + 1 < nums.length && nums[j] == nums[j + 1]) { + j++; + } + + if (nums[j] - nums[i] == k) { + result++; + } + } + + while (i + 1 < nums.length && nums[i] == nums[i + 1]) { + i++; + } + + } + + return result; + } +} diff --git a/[0523][K Diff Pairs In An Array]/src/SolutionTest.java b/[0523][K Diff Pairs In An Array]/src/SolutionTest.java new file mode 100644 index 0000000..2e368fa --- /dev/null +++ b/[0523][K Diff Pairs In An Array]/src/SolutionTest.java @@ -0,0 +1,27 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-06-30 08:56 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findPairs() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{3, 1, 4, 1, 5}, 2, 2}, + {new int[]{1, 2, 3, 4, 5}, 1, 4}, + {new int[]{1, 3, 1, 5, 4}, 0, 1}, + {new int[]{1, 1, 1, 1, 1}, 0, 1}, + {new int[]{1, 1, 2, 2, 1}, 0, 2}, + }; + + for (Object[] d: data) { + Assert.assertEquals(d[2], s.findPairs((int[]) d[0], (Integer) d[1])); + } + } +} \ No newline at end of file diff --git a/[0530][Minimum Absolute Difference in BST]/[0530][Minimum Absolute Difference in BST].iml b/[0530][Minimum Absolute Difference in BST]/[0530][Minimum Absolute Difference in BST].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0530][Minimum Absolute Difference in BST]/[0530][Minimum Absolute Difference in BST].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0530][Minimum Absolute Difference in BST]/src/Solution.java b/[0530][Minimum Absolute Difference in BST]/src/Solution.java new file mode 100644 index 0000000..603e965 --- /dev/null +++ b/[0530][Minimum Absolute Difference in BST]/src/Solution.java @@ -0,0 +1,92 @@ +import java.util.*; + +/** + * Author: 王俊超 + * Time: 2020-06-29 10:09 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 解题思路 + * root提个二叉搜索树 + * 二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: + * 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; + * 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; + * 它的左、右子树也分别为二叉排序树。 + * + * @param root + * @return + */ + public int getMinimumDifference(TreeNode root) { + + if (root == null) { + return 0; + } + Deque s = new LinkedList<>(); + int min = Integer.MAX_VALUE; + int prev = 0; + boolean first = true; + while (root != null || !s.isEmpty()) { + while (root != null) { + s.push(root);//先访问再入栈 + root = root.left; + } + root = s.pop(); + + if (first) { + first = false; + } else { + min = Math.min(min, root.val - prev); + } + + prev = root.val; + root = root.right;//如果是null,出栈并处理右子树 + } + + return min; + } + + public int getMinimumDifference2(TreeNode root) { + + if (root == null) { + return 0; + } + + List list = new ArrayList<>(); + + Deque queue = new LinkedList<>(); + queue.add(root); + while (!queue.isEmpty()) { + TreeNode node = queue.poll(); + list.add(node.val); + if (node.right != null) { + queue.addFirst(node.right); + } + if (node.left != null) { + queue.addFirst(node.left); + } + } + + + if (list.size() == 1) { + return list.get(0); + } + + list.sort(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return o1 - o2; + } + }); + + int min = Integer.MAX_VALUE; + + for (int i = 1; i < list.size(); i++) { + min = Math.min(min, Math.abs(list.get(i - 1) - list.get(i))); + } + + return min; + } +} diff --git a/[0530][Minimum Absolute Difference in BST]/src/SolutionTest.java b/[0530][Minimum Absolute Difference in BST]/src/SolutionTest.java new file mode 100644 index 0000000..b0523af --- /dev/null +++ b/[0530][Minimum Absolute Difference in BST]/src/SolutionTest.java @@ -0,0 +1,35 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-06-29 11:33 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void getMinimumDifference() { + TreeNode root = new TreeNode(1); + root.right = new TreeNode(3); + root.right.left = new TreeNode(2); + + Solution s = new Solution(); + Assert.assertEquals(s.getMinimumDifference(root), 1); + } + +// [236,104,701,null,227,null,911] + + @org.junit.Test + public void getMinimumDifference2() { + TreeNode root = new TreeNode(236); + root.left = new TreeNode(104); + root.left.right = new TreeNode(227); + root.right = new TreeNode(701); + root.right.right = new TreeNode(911); + + Solution s = new Solution(); + Assert.assertEquals(s.getMinimumDifference(root), 9); + } +} \ No newline at end of file diff --git a/[0530][Minimum Absolute Difference in BST]/src/TreeNode.java b/[0530][Minimum Absolute Difference in BST]/src/TreeNode.java new file mode 100644 index 0000000..bff99a6 --- /dev/null +++ b/[0530][Minimum Absolute Difference in BST]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 11:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0538][Convert BST to Greater Tree]/[0538][Convert BST to Greater Tree].iml b/[0538][Convert BST to Greater Tree]/[0538][Convert BST to Greater Tree].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0538][Convert BST to Greater Tree]/[0538][Convert BST to Greater Tree].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0538][Convert BST to Greater Tree]/src/Solution.java b/[0538][Convert BST to Greater Tree]/src/Solution.java new file mode 100644 index 0000000..0e52f13 --- /dev/null +++ b/[0538][Convert BST to Greater Tree]/src/Solution.java @@ -0,0 +1,52 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * Author: 王俊超 + * Time: 2020-06-30 10:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 解题思路 + * root提个二叉搜索树 + * 二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: + * 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; + * 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; + * 它的左、右子树也分别为二叉排序树。 + * 先处理右子树,再处理自己,再处理左子树 + * + * @param root + * @return + */ + public TreeNode convertBST(TreeNode root) { + + if (root == null) { + return null; + } + Deque s = new LinkedList<>(); + TreeNode prev = null; + TreeNode curr = root; + + while (curr != null || !s.isEmpty()) { + while (curr != null) { + s.push(curr);//先访问再入栈 + curr = curr.right; + } + curr = s.pop(); + + if (prev == null) { + prev = curr; + } else { + curr.val += prev.val; + } + + prev = curr; + curr = curr.left;//如果是null,出栈并处理左子树 + } + + return root; + } +} diff --git a/[0538][Convert BST to Greater Tree]/src/SolutionTest.java b/[0538][Convert BST to Greater Tree]/src/SolutionTest.java new file mode 100644 index 0000000..5b181bf --- /dev/null +++ b/[0538][Convert BST to Greater Tree]/src/SolutionTest.java @@ -0,0 +1,39 @@ +import static org.junit.Assert.*; + +/** + * Author: 王俊超 + * Time: 2020-06-30 10:14 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void convertBST() { + Solution s = new Solution(); + + TreeNode root = new TreeNode(4); + root.left = new TreeNode(2); + root.left.left = new TreeNode(1); + root.left.right = new TreeNode(3); + root.right =new TreeNode(6); + root.right.left = new TreeNode(5); + root.right.right = new TreeNode(7); + + s.convertBST(root); + + print(root); + } + + private void print(TreeNode root) { + if (root == null) { + return; + } + + print(root.left); + System.out.println(root.val); + print(root.right); + + } +} \ No newline at end of file diff --git a/[0538][Convert BST to Greater Tree]/src/TreeNode.java b/[0538][Convert BST to Greater Tree]/src/TreeNode.java new file mode 100644 index 0000000..bff99a6 --- /dev/null +++ b/[0538][Convert BST to Greater Tree]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 11:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0541][Reverse String II]/[0541][Reverse String II].iml b/[0541][Reverse String II]/[0541][Reverse String II].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0541][Reverse String II]/[0541][Reverse String II].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0541][Reverse String II]/src/Solution.java b/[0541][Reverse String II]/src/Solution.java new file mode 100644 index 0000000..df9a379 --- /dev/null +++ b/[0541][Reverse String II]/src/Solution.java @@ -0,0 +1,32 @@ +/** + * Author: 王俊超 + * Time: 2020-06-30 12:50 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public String reverseStr(String s, int k) { + if (s == null || s.length() < 2 || k < 1) { + return s; + } + char[] chars = s.toCharArray(); + int index = 0; + while (index < chars.length) { + swap(chars, index, Math.min(chars.length - 1, index + k - 1)); + index += 2 * k; + } + + return new String(chars); + } + + public void swap(char[] chars, int i, int j) { + while (i < j) { + char ch = chars[i]; + chars[i] = chars[j]; + chars[j] = ch; + i++; + j--; + } + } +} diff --git a/[0541][Reverse String II]/src/SolutionTest.java b/[0541][Reverse String II]/src/SolutionTest.java new file mode 100644 index 0000000..373a1d1 --- /dev/null +++ b/[0541][Reverse String II]/src/SolutionTest.java @@ -0,0 +1,24 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-06-30 12:54 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void reverseStr() { + Solution s = new Solution(); + Object[][] data = { + {"abcdefg", 2, "bacdfeg"}, + {"abcdefgh", 2, "bacdfegh"}, + }; + + for (Object[] d : data) { + Assert.assertEquals(d[2], s.reverseStr((String) d[0], (Integer) d[1])); + } + } +} \ No newline at end of file diff --git a/[0542][01 Matrix]/[0542][01 Matrix].iml b/[0542][01 Matrix]/[0542][01 Matrix].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0542][01 Matrix]/[0542][01 Matrix].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0542][01 Matrix]/src/Main.java b/[0542][01 Matrix]/src/Main.java new file mode 100644 index 0000000..984cd23 --- /dev/null +++ b/[0542][01 Matrix]/src/Main.java @@ -0,0 +1,92 @@ +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 14:54 + **/ +public class Main { + @Test + public void test1() { + int[][] matrix = { + {0, 0, 0}, + {0, 1, 0}, + {1, 1, 1}}; + Solution solution = new Solution(); + matrix = solution.updateMatrix(matrix); + + for (int[] row : matrix) { + System.out.println(Arrays.toString(row)); + } + System.out.println(); + } + + @Test + public void test2() { + int[][] matrix = { + {1, 1, 1}, + {1, 0, 1}, + {1, 1, 1}}; + Solution solution = new Solution(); + matrix = solution.updateMatrix(matrix); + + for (int[] row : matrix) { + System.out.println(Arrays.toString(row)); + } + System.out.println(); + + } + + @Test + public void test3() { + int[][] matrix = { + {1, 1, 1, 1, 1}, + {1, 1, 1, 1, 1}, + {1, 1, 0, 1, 1}, + {1, 1, 1, 1, 1}, + {1, 1, 1, 1, 1}}; + Solution solution = new Solution(); + matrix = solution.updateMatrix(matrix); + + for (int[] row : matrix) { + System.out.println(Arrays.toString(row)); + } + System.out.println(); + + } + + @Test + public void test4() { + int[][] matrix = { + {0, 0, 0, 0, 0}, + {0, 1, 1, 1, 1}, + {0, 1, 0, 1, 1}, + {0, 1, 1, 1, 1}, + {0, 1, 1, 1, 1}}; + Solution solution = new Solution(); + matrix = solution.updateMatrix(matrix); + + for (int[] row : matrix) { + System.out.println(Arrays.toString(row)); + } + System.out.println(); + } + + @Test + public void test5() { + int[][] matrix = { + {0, 0, 0, 0, 0}, + {0, 1, 1, 1, 1}, + {0, 1, 1, 1, 1}, + {0, 1, 1, 1, 1}, + {0, 1, 1, 1, 1}}; + Solution solution = new Solution(); + matrix = solution.updateMatrix(matrix); + + for (int[] row : matrix) { + System.out.println(Arrays.toString(row)); + } + System.out.println(); + } +} diff --git a/[0542][01 Matrix]/src/Solution.java b/[0542][01 Matrix]/src/Solution.java new file mode 100644 index 0000000..5d30dcc --- /dev/null +++ b/[0542][01 Matrix]/src/Solution.java @@ -0,0 +1,115 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-02 13:25 + **/ +public class Solution { + /** + *
+     * Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
+     *
+     * The distance between two adjacent cells is 1.
+     *
+     *
+     *
+     * Example 1:
+     *
+     * Input:
+     * [[0,0,0],
+     *  [0,1,0],
+     *  [0,0,0]]
+     *
+     * Output:
+     * [[0,0,0],
+     *  [0,1,0],
+     *  [0,0,0]]
+     * Example 2:
+     *
+     * Input:
+     * [[0,0,0],
+     *  [0,1,0],
+     *  [1,1,1]]
+     *
+     * Output:
+     * [[0,0,0],
+     *  [0,1,0],
+     *  [1,2,1]]
+     *
+     *  Note:
+     *
+     * The number of elements of the given matrix will not exceed 10,000.
+     * There are at least one 0 in the given matrix.
+     * The cells are adjacent in only four directions: up, down, left and right.
+     * 类似广度优化遍历
+     * 
+ * + * @param matrix + * @return + */ + public int[][] updateMatrix(int[][] matrix) { + + boolean[][] visit = new boolean[matrix.length][]; + Deque deque = new LinkedList<>(); + + for (int i = 0; i < visit.length; i++) { + visit[i] = new boolean[matrix[i].length]; + } + + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] == 0) { + visit[i][j] = true; + deque.addLast(i); + deque.addLast(j); + deque.addLast(0); + } + } + } + + while (!deque.isEmpty()) { + int i = deque.removeFirst(); + int j = deque.removeFirst(); + int v = deque.removeFirst(); + + // 上一个 + if (i - 1 >= 0 && !visit[i - 1][j]) { + visit[i - 1][j] = true; + matrix[i - 1][j] = v + 1; + deque.addLast(i - 1); + deque.addLast(j); + deque.addLast(v + 1); + } + + // 下一个 + if (i + 1 < matrix.length && !visit[i + 1][j]) { + visit[i + 1][j] = true; + matrix[i + 1][j] = v + 1; + deque.addLast(i + 1); + deque.addLast(j); + deque.addLast(v + 1); + } + + // 左一个 + if (j - 1 >= 0 && !visit[i][j - 1]) { + visit[i][j - 1] = true; + matrix[i][j - 1] = v + 1; + deque.addLast(i); + deque.addLast(j - 1); + deque.addLast(v + 1); + } + + // 右一个 + if (j + 1 < matrix[0].length && !visit[i][j + 1]) { + visit[i][j + 1] = true; + matrix[i][j + 1] = v + 1; + deque.addLast(i); + deque.addLast(j + 1); + deque.addLast(v + 1); + } + } + + return matrix; + } +} diff --git a/[0543][Diameter of Binary Tree]/[0543][Diameter of Binary Tree].iml b/[0543][Diameter of Binary Tree]/[0543][Diameter of Binary Tree].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0543][Diameter of Binary Tree]/[0543][Diameter of Binary Tree].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0543][Diameter of Binary Tree]/src/Solution.java b/[0543][Diameter of Binary Tree]/src/Solution.java new file mode 100644 index 0000000..5bca04a --- /dev/null +++ b/[0543][Diameter of Binary Tree]/src/Solution.java @@ -0,0 +1,59 @@ +/** + * Author: 王俊超 + * Time: 2020-07-01 08:53 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int diameterOfBinaryTree(TreeNode root) { + return layerAndDiameter(root)[1]; + } + + /** + * 解题思路: + * 最大直径的三种情况: + * 1、在左子树中 + * 2、在右子树中 + * 3、对过root节点,如果经过root节点,那么直径就是 Height(root.left) + Height(root.right) + 2 + * 对每个节点都是同样的。所以可以使用递归求解,先求左右子树的高度和最大直径,再求通过root的高度和直径,再找出最大的直径 + * + * + * 第一个反回参数表示root最大有多少层, + * 第二个返回参数表示root的最大直径 + * + * @param root + * @return + */ + public int[] layerAndDiameter(TreeNode root) { + if (root == null) { // 边界条件 + return new int[]{0, 0}; + } + + if (root.left == null && root.right == null) { // 边界条件 + return new int[]{0, 0}; + } else if (root.left != null && root.right == null) { + int[] result = layerAndDiameter(root.left); + result[0] += 1; // 层升高1 + result[1] = Math.max(result[0], result[1]); // 因为没有右子树,最大直径要么经过root,要么不经过 + + return result; + } else if (root.left == null && root.right != null) { + int[] result = layerAndDiameter(root.right); + result[0] += 1; // 层升高1 + result[1] = Math.max(result[0], result[1]); // 因为没有左子树,最大直径要么经过root,要么不经过 + return result; + } + + int[] left = layerAndDiameter(root.left); + int[] right = layerAndDiameter(root.right); + + int[] result = {0, 0}; + result[0] = 1 + Math.max(left[0], right[0]); // 层升高1 + + result[1] = Math.max(left[1], right[1]); // 最大直径可能在左子树或者右子树中 + result[1] = Math.max(result[1], 2 + left[0] + right[0]); // 最大直径可能经过root + + return result; + } +} diff --git a/[0543][Diameter of Binary Tree]/src/SolutionTest.java b/[0543][Diameter of Binary Tree]/src/SolutionTest.java new file mode 100644 index 0000000..c3cab02 --- /dev/null +++ b/[0543][Diameter of Binary Tree]/src/SolutionTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; + +import static org.junit.Assert.*; + +/** + * Author: 王俊超 + * Time: 2020-07-01 08:57 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void diameterOfBinaryTree() { + Solution s = new Solution(); + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.left = new TreeNode(4); + root.left.right = new TreeNode(5); + + Assert.assertEquals(3, s.diameterOfBinaryTree(root)); + } +} \ No newline at end of file diff --git a/[0543][Diameter of Binary Tree]/src/TreeNode.java b/[0543][Diameter of Binary Tree]/src/TreeNode.java new file mode 100644 index 0000000..bff99a6 --- /dev/null +++ b/[0543][Diameter of Binary Tree]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 11:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0551][Student Attendance Record I]/[0551][Student Attendance Record I].iml b/[0551][Student Attendance Record I]/[0551][Student Attendance Record I].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0551][Student Attendance Record I]/[0551][Student Attendance Record I].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0551][Student Attendance Record I]/src/Solution.java b/[0551][Student Attendance Record I]/src/Solution.java new file mode 100644 index 0000000..3ca6969 --- /dev/null +++ b/[0551][Student Attendance Record I]/src/Solution.java @@ -0,0 +1,41 @@ +/** + * Author: 王俊超 + * Time: 2020-07-02 08:05 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public boolean checkRecord(String s) { + int a = 0; + int l = 0; + int preLIndex = -1; + if (s != null) { + for (int i = 0; i < s.length(); i++) { + switch (s.charAt(i)) { + case 'A': + a++; + break; + case 'L': + if (l < 3) { // 连续两个L后面步不用记录了 + if (preLIndex == -1) { // 刚开始记录 + preLIndex = i; + l = 1; + } else if (preLIndex + 1 == i) { // 当前和前一个都是L + l++; + preLIndex = i; + } else { // 前一个不是L,重新记数 + preLIndex = i; + l = 1; + } + } + break; + default: + // do nothing + } + } + } + + return a <= 1 && l < 3; + } +} diff --git a/[0551][Student Attendance Record I]/src/SolutionTest.java b/[0551][Student Attendance Record I]/src/SolutionTest.java new file mode 100644 index 0000000..4c102f4 --- /dev/null +++ b/[0551][Student Attendance Record I]/src/SolutionTest.java @@ -0,0 +1,27 @@ +import org.junit.Assert; +import org.junit.Test; + + +/** + * Author: 王俊超 + * Time: 2020-07-02 08:12 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @Test + public void checkRecord() { + Solution s = new Solution(); + Object[][] data = { + {"PPALLP", true}, + {"PPALLL", false}, + }; + + for (Object[] d : data) { + Assert.assertEquals(d[1], s.checkRecord((String) d[0])); + } + } + +} \ No newline at end of file diff --git a/[0557][Reverse Words in a String III]/[0557][Reverse Words in a String III].iml b/[0557][Reverse Words in a String III]/[0557][Reverse Words in a String III].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0557][Reverse Words in a String III]/[0557][Reverse Words in a String III].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0557][Reverse Words in a String III]/src/Main.java b/[0557][Reverse Words in a String III]/src/Main.java new file mode 100644 index 0000000..b182605 --- /dev/null +++ b/[0557][Reverse Words in a String III]/src/Main.java @@ -0,0 +1,24 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 17:51 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + Assert.assertEquals("s'teL ekat edoCteeL tsetnoc", + solution.reverseWords("Let's take LeetCode contest")); + } + + @Test + public void test2() { + Solution solution = new Solution(); + + Assert.assertEquals(" cba", + solution.reverseWords(" abc")); + } +} diff --git a/[0557][Reverse Words in a String III]/src/Solution.java b/[0557][Reverse Words in a String III]/src/Solution.java new file mode 100644 index 0000000..402ed4b --- /dev/null +++ b/[0557][Reverse Words in a String III]/src/Solution.java @@ -0,0 +1,58 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-03 17:45 + **/ +public class Solution { + /** + *
+     * Given a string, you need to reverse the order of characters in each word
+     * within a sentence while still preserving whitespace and initial word order.
+     *
+     * Example 1:
+     * Input: "Let's take LeetCode contest"
+     * Output: "s'teL ekat edoCteeL tsetnoc"
+     * Note: In the string, each word is separated by single space and there will
+     * not be any extra space in the string.
+     * 
+ * + * @param s + * @return + */ + public String reverseWords(String s) { + if (s == null || s.length() < 2) { + return s; + } + + char[] chars = s.toCharArray(); + + int start = 0; + int end = 0; + while (start < chars.length) { + // 找第一个非空白字符 + while (start < chars.length && chars[start] == ' ') { + start++; + } + // 找第一个空白字符 + end = start + 1; + while (end < chars.length && chars[end] != ' ') { + end++; + } + + // 翻转字符串 + swap(chars, start, end - 1); + start = end; + } + + return new String(chars); + } + + private void swap(char[] chars, int start, int end) { + while (start < end) { + char ch = chars[start]; + chars[start] = chars[end]; + chars[end] = ch; + start++; + end--; + } + } +} diff --git a/[0559][Maximum Depth of N-ary Tree]/[0559][Maximum Depth of N-ary Tree].iml b/[0559][Maximum Depth of N-ary Tree]/[0559][Maximum Depth of N-ary Tree].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0559][Maximum Depth of N-ary Tree]/[0559][Maximum Depth of N-ary Tree].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0559][Maximum Depth of N-ary Tree]/src/Node.java b/[0559][Maximum Depth of N-ary Tree]/src/Node.java new file mode 100644 index 0000000..bf5b87a --- /dev/null +++ b/[0559][Maximum Depth of N-ary Tree]/src/Node.java @@ -0,0 +1,25 @@ +import java.util.List; + +/** + * Author: 王俊超 + * Time: 2020-07-02 07:58 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Node { + public int val; + public List children; + + public Node() { + } + + public Node(int val) { + this.val = val; + } + + public Node(int val, List children) { + this.val = val; + this.children = children; + } +} diff --git a/[0559][Maximum Depth of N-ary Tree]/src/Solution.java b/[0559][Maximum Depth of N-ary Tree]/src/Solution.java new file mode 100644 index 0000000..d43fa08 --- /dev/null +++ b/[0559][Maximum Depth of N-ary Tree]/src/Solution.java @@ -0,0 +1,27 @@ +/** + * Author: 王俊超 + * Time: 2020-07-02 07:58 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int maxDepth(Node root) { + if (root == null) { + return 0; + } + + if (root.children == null || root.children.isEmpty()) { + return 1; + } + + int max = 0; + + for (Node child : root.children) { + max = Math.max(max, maxDepth(child)); + } + + return 1 + max; + } +} + diff --git a/[0559][Maximum Depth of N-ary Tree]/src/SolutionTest.java b/[0559][Maximum Depth of N-ary Tree]/src/SolutionTest.java new file mode 100644 index 0000000..4aebf27 --- /dev/null +++ b/[0559][Maximum Depth of N-ary Tree]/src/SolutionTest.java @@ -0,0 +1,31 @@ +import org.junit.Assert; + +import java.util.ArrayList; + +import static org.junit.Assert.*; + +/** + * Author: 王俊超 + * Time: 2020-07-02 08:00 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void maxDepth() { + Node root = new Node(1); + root.children = new ArrayList<>(); + root.children.add(new Node(3)); + root.children.add(new Node(2)); + root.children.add(new Node(4)); + root.children.get(0).children = new ArrayList<>(); + root.children.get(0).children.add(new Node(5)); + root.children.get(0).children.add(new Node(6)); + + Solution s =new Solution(); + + Assert.assertEquals(3, s.maxDepth(root)); + } +} \ No newline at end of file diff --git a/[0561][Array Partition I]/[0561][Array Partition I].iml b/[0561][Array Partition I]/[0561][Array Partition I].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0561][Array Partition I]/[0561][Array Partition I].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0561][Array Partition I]/src/Main.java b/[0561][Array Partition I]/src/Main.java new file mode 100644 index 0000000..9deca22 --- /dev/null +++ b/[0561][Array Partition I]/src/Main.java @@ -0,0 +1,15 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-04 08:49 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] arr = {1, 4, 3, 2}; + Assert.assertEquals(4, solution.arrayPairSum(arr)); + } +} diff --git a/[0561][Array Partition I]/src/Solution.java b/[0561][Array Partition I]/src/Solution.java new file mode 100644 index 0000000..7169b92 --- /dev/null +++ b/[0561][Array Partition I]/src/Solution.java @@ -0,0 +1,43 @@ +import java.util.Arrays; + +/** + * https://leetcode.com/problems/array-partition-i/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-04 08:46 + **/ +public class Solution { + /** + *
+     * Given an array of 2n integers, your task is to group these integers into n pairs of integer,
+     * say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n
+     * as large as possible.
+     *
+     * Example 1:
+     * Input: [1,4,3,2]
+     *
+     * Output: 4
+     * Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
+     * Note:
+     * n is a positive integer, which is in the range of [1, 10000].
+     * All the integers in the array will be in the range of [-10000, 10000].
+     *
+     * 解题思路
+     * 先将数据组排序,取偶数位置的数相加,即为结果
+     * 证明略
+     * 
+ * + * @param nums + * @return + */ + public int arrayPairSum(int[] nums) { + Arrays.sort(nums); + + int result = 0; + for (int i = 0; i < nums.length; i += 2) { + result += nums[i]; + } + + return result; + } +} diff --git a/[0563][Binary Tree Tilt]/[0563][Binary Tree Tilt].iml b/[0563][Binary Tree Tilt]/[0563][Binary Tree Tilt].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0563][Binary Tree Tilt]/[0563][Binary Tree Tilt].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0563][Binary Tree Tilt]/src/Solution.java b/[0563][Binary Tree Tilt]/src/Solution.java new file mode 100644 index 0000000..a3ae597 --- /dev/null +++ b/[0563][Binary Tree Tilt]/src/Solution.java @@ -0,0 +1,47 @@ +/** + * Author: 王俊超 + * Time: 2020-07-02 08:26 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 解题思路 + * 一个树的坡度等于=左子树的坡度+右子树的坡度+根节点的坡度 + * 子树同样适应 + * + * @param root + * @return + */ + public int findTilt(TreeNode root) { + return findTiltHelp(root)[0]; + } + + /** + * 第一个返回值表示root的坡度 + * 第二个返回值表示root的为根的树的节点和 + * + * @param root + * @return + */ + public int[] findTiltHelp(TreeNode root) { + // 空结点或者左右孩子为都空的结点 + if (root == null) { + return new int[]{0, 0}; + } else if (root.left == null && root.right == null) { + return new int[]{0, root.val}; + } + + + int[] left = findTiltHelp(root.left); + int[] right = findTiltHelp(root.right); + + int[] result = {0, 0}; + + result[0] = left[0] + right[0] + Math.abs(left[1] - right[1]); + result[1] = left[1] + right[1] + root.val; + + return result; + } +} diff --git a/[0563][Binary Tree Tilt]/src/SolutionTest.java b/[0563][Binary Tree Tilt]/src/SolutionTest.java new file mode 100644 index 0000000..358cd67 --- /dev/null +++ b/[0563][Binary Tree Tilt]/src/SolutionTest.java @@ -0,0 +1,22 @@ +import org.junit.Assert; + +import static org.junit.Assert.*; + +/** + * Author: 王俊超 + * Time: 2020-07-02 08:38 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findTilt() { + Solution s = new Solution(); + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + Assert.assertEquals(1, s.findTilt(root)); + } +} \ No newline at end of file diff --git a/[0563][Binary Tree Tilt]/src/TreeNode.java b/[0563][Binary Tree Tilt]/src/TreeNode.java new file mode 100644 index 0000000..8b88e24 --- /dev/null +++ b/[0563][Binary Tree Tilt]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Date: 2015-08-21 + * Time: 18:45 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} + diff --git a/[0566][Reshape the Matrix]/[0566][Reshape the Matrix].iml b/[0566][Reshape the Matrix]/[0566][Reshape the Matrix].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0566][Reshape the Matrix]/[0566][Reshape the Matrix].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0566][Reshape the Matrix]/src/Solution.java b/[0566][Reshape the Matrix]/src/Solution.java new file mode 100644 index 0000000..f4516d8 --- /dev/null +++ b/[0566][Reshape the Matrix]/src/Solution.java @@ -0,0 +1,29 @@ +/** + * Author: 王俊超 + * Time: 2020-07-02 08:43 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int[][] matrixReshape(int[][] nums, int r, int c) { + int row = nums.length; + int col = nums[0].length; + if (row * col != r * c) { + return nums; + } + + int[][] result = new int[r][c]; + for (int i = 0; i < r; i++) { + result[i] = new int[c]; + } + + int num = row * col; + + for (int i = 0; i < num; i++) { + result[i / c][i % c] = nums[i / col][i % col]; + } + + return result; + } +} diff --git a/[0566][Reshape the Matrix]/src/SolutionTest.java b/[0566][Reshape the Matrix]/src/SolutionTest.java new file mode 100644 index 0000000..d21e1f9 --- /dev/null +++ b/[0566][Reshape the Matrix]/src/SolutionTest.java @@ -0,0 +1,32 @@ +import org.junit.Assert; + +import static org.junit.Assert.*; + +/** + * Author: 王俊超 + * Time: 2020-07-02 08:46 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void matrixReshape() { + Solution s = new Solution(); + Object[][] data = { + {new int[][]{{1, 2}, {3, 4}}, 1, 4, new int[][]{{1, 2, 3, 4}}}, + {new int[][]{{1, 2}, {3, 4}}, 2, 4, new int[][]{{1, 2}, {3, 4}}}, + }; + + for (Object[] d : data) { + int[][] result = s.matrixReshape((int[][]) d[0], (Integer) d[1], (Integer) d[2]); + int[][] actual = (int[][]) d[3]; + Assert.assertEquals(result.length, actual.length); + + for (int i = 0; i < result.length; i++) { + Assert.assertArrayEquals(actual[i], result[i]); + } + } + } +} \ No newline at end of file diff --git a/[0572][Subtree of Another Tree]/[0572][Subtree of Another Tree].iml b/[0572][Subtree of Another Tree]/[0572][Subtree of Another Tree].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0572][Subtree of Another Tree]/[0572][Subtree of Another Tree].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0572][Subtree of Another Tree]/src/Solution.java b/[0572][Subtree of Another Tree]/src/Solution.java new file mode 100644 index 0000000..f14f241 --- /dev/null +++ b/[0572][Subtree of Another Tree]/src/Solution.java @@ -0,0 +1,56 @@ +import java.util.Deque; +import java.util.LinkedList; + +/** + * Author: 王俊超 + * Time: 2020-07-02 09:02 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public boolean isSubtree(TreeNode s, TreeNode t) { + + if (s == t || t == null) { + return true; + } + + if (s == null) { + return false; + } + + Deque queue = new LinkedList<>(); + queue.addFirst(s); + while (!queue.isEmpty()) { + TreeNode root = queue.removeFirst(); + if (root.right != null) { + queue.addFirst(root.right); + } + if (root.left != null) { + queue.addFirst(root.left); + } + + if(isSame(root, t)) { + return true; + } + + } + + return false; + } + + public boolean isSame(TreeNode s, TreeNode t) { + if (s == t) { + return true; + } + + if (s == null || t == null) { + return false; + } + + boolean leftSame = isSame(s.left, t.left); + boolean rightSame = isSame(s.right, t.right); + + return s.val == t.val && leftSame && rightSame; + } +} diff --git a/[0572][Subtree of Another Tree]/src/SolutionTest.java b/[0572][Subtree of Another Tree]/src/SolutionTest.java new file mode 100644 index 0000000..15b8f13 --- /dev/null +++ b/[0572][Subtree of Another Tree]/src/SolutionTest.java @@ -0,0 +1,46 @@ +import org.junit.Assert; + +import static org.junit.Assert.*; + +/** + * Author: 王俊超 + * Time: 2020-07-02 09:11 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void isSubtree() { + Solution s = new Solution(); + TreeNode root = new TreeNode(3); + root.left = new TreeNode(4); + root.right = new TreeNode(5); + root.left.left = new TreeNode(1); + root.left.right = new TreeNode(2); + + TreeNode t = new TreeNode(4); + t.left = new TreeNode(1); + t.right = new TreeNode(2); + + Assert.assertEquals(true, s.isSubtree(root, t)); + } + + @org.junit.Test + public void isSubtree2() { + Solution s = new Solution(); + TreeNode root = new TreeNode(3); + root.left = new TreeNode(4); + root.right = new TreeNode(5); + root.left.left = new TreeNode(1); + root.left.right = new TreeNode(2); + root.left.right.left = new TreeNode(0); + + TreeNode t = new TreeNode(4); + t.left = new TreeNode(1); + t.right = new TreeNode(2); + + Assert.assertEquals(false, s.isSubtree(root, t)); + } +} \ No newline at end of file diff --git a/[0572][Subtree of Another Tree]/src/TreeNode.java b/[0572][Subtree of Another Tree]/src/TreeNode.java new file mode 100644 index 0000000..ac7b907 --- /dev/null +++ b/[0572][Subtree of Another Tree]/src/TreeNode.java @@ -0,0 +1,22 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 11:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } + + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } +} diff --git a/[0575][Distribute Candies]/[0575][Distribute Candies].iml b/[0575][Distribute Candies]/[0575][Distribute Candies].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0575][Distribute Candies]/[0575][Distribute Candies].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0575][Distribute Candies]/src/Solution.java b/[0575][Distribute Candies]/src/Solution.java new file mode 100644 index 0000000..660aaac --- /dev/null +++ b/[0575][Distribute Candies]/src/Solution.java @@ -0,0 +1,32 @@ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Author: 王俊超 + * Time: 2020-07-03 10:03 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 找出共有多少种糖果,如果种类大于糖果数目的一半就取糖果数目的一半,否则就取糖果的种类数 + * + * @param candies + * @return + */ + public int distributeCandies(int[] candies) { + if (candies == null || candies.length % 2 != 0) { + throw new IllegalArgumentException("illegal candies: " + Arrays.toString(candies)); + } + + Set set = new HashSet<>(candies.length); + for (int c : candies) { + set.add(c); + } + + return Math.min(set.size(), candies.length / 2); + } + +} diff --git a/[0575][Distribute Candies]/src/SolutionTest.java b/[0575][Distribute Candies]/src/SolutionTest.java new file mode 100644 index 0000000..a066444 --- /dev/null +++ b/[0575][Distribute Candies]/src/SolutionTest.java @@ -0,0 +1,27 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-03 10:08 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void distributeCandies() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{1, 1, 2, 2, 3, 3}, 3}, + {new int[]{1, 1, 2, 3}, 2}, + {new int[]{1, 2, 3, 4}, 2}, + }; + + for (Object[] d : data) { + int result = s.distributeCandies((int[]) d[0]); + Assert.assertEquals(d[1], result); + } + + } +} \ No newline at end of file diff --git a/[0581][Shortest Unsorted Continuous Subarray]/[0581][Shortest Unsorted Continuous Subarray].iml b/[0581][Shortest Unsorted Continuous Subarray]/[0581][Shortest Unsorted Continuous Subarray].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0581][Shortest Unsorted Continuous Subarray]/[0581][Shortest Unsorted Continuous Subarray].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0581][Shortest Unsorted Continuous Subarray]/src/Solution.java b/[0581][Shortest Unsorted Continuous Subarray]/src/Solution.java new file mode 100644 index 0000000..bace39f --- /dev/null +++ b/[0581][Shortest Unsorted Continuous Subarray]/src/Solution.java @@ -0,0 +1,39 @@ +import java.util.Arrays; + +/** + * Author: 王俊超 + * Time: 2020-07-04 19:24 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int findUnsortedSubarray(int[] nums) { + if (nums == null || nums.length < 2) { + return 0; + } + + int[] sorted = Arrays.copyOf(nums, nums.length); + Arrays.sort(sorted); + + + int diffStart = 0; // 从开始找第一个位置变化的下标 + while (diffStart < nums.length && nums[diffStart] == sorted[diffStart]) { + diffStart++; + } + + if (diffStart >= nums.length) { + return 0; + } + + + int diffEnd = nums.length - 1; // 从最后找第一个位置变化的下标 + while (diffEnd >= 0 && nums[diffEnd] == sorted[diffEnd]) { + diffEnd--; + } + + + + return diffEnd - diffStart + 1; + } +} diff --git a/[0581][Shortest Unsorted Continuous Subarray]/src/SolutionTest.java b/[0581][Shortest Unsorted Continuous Subarray]/src/SolutionTest.java new file mode 100644 index 0000000..dcda38c --- /dev/null +++ b/[0581][Shortest Unsorted Continuous Subarray]/src/SolutionTest.java @@ -0,0 +1,26 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-04 19:32 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findUnsortedSubarray() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{2, 6, 4, 8, 10, 9, 15}, 5}, + {new int[]{1, 2, 3, 4, 5, 6, 7}, 0}, + {new int[]{7, 6, 5, 4, 3, 2, 1}, 7}, + }; + + for (Object[] d : data) { + Object result = s.findUnsortedSubarray((int[]) d[0]); + Assert.assertEquals(d[1], result); + } + } +} \ No newline at end of file diff --git "a/\343\200\220006\343\200\221\343\200\220ZigZagConversion\343\200\221/\343\200\220006\343\200\221\343\200\220ZigZagConversion\343\200\221.iml" b/[0589][N-ary Tree Preorder Traversal]/[0589][N-ary Tree Preorder Traversal].iml similarity index 100% rename from "\343\200\220006\343\200\221\343\200\220ZigZagConversion\343\200\221/\343\200\220006\343\200\221\343\200\220ZigZagConversion\343\200\221.iml" rename to [0589][N-ary Tree Preorder Traversal]/[0589][N-ary Tree Preorder Traversal].iml diff --git a/[0589][N-ary Tree Preorder Traversal]/src/Node.java b/[0589][N-ary Tree Preorder Traversal]/src/Node.java new file mode 100644 index 0000000..6df4c7f --- /dev/null +++ b/[0589][N-ary Tree Preorder Traversal]/src/Node.java @@ -0,0 +1,24 @@ +import java.util.List; + +/** + * Author: 王俊超 + * Time: 2020-07-03 10:20 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + this.val = _val; + } + + public Node(int val, List children) { + this.val = val; + this.children = children; + } +} diff --git a/[0589][N-ary Tree Preorder Traversal]/src/Solution.java b/[0589][N-ary Tree Preorder Traversal]/src/Solution.java new file mode 100644 index 0000000..f4cc00d --- /dev/null +++ b/[0589][N-ary Tree Preorder Traversal]/src/Solution.java @@ -0,0 +1,56 @@ +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: 王俊超 + * Time: 2020-07-03 10:20 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public List preorder(Node root) { + List result = new LinkedList<>(); +// preorderReserve(root, result); + preorderIterator(root, result); + return result; + } + + public void preorderIterator(Node root, List result) { + if (root == null) { + return; + } + + Deque deque = new LinkedList<>(); + deque.addFirst(root); + + while (!deque.isEmpty()) { + Node n = deque.removeFirst(); + result.add(n.val); + if (n.children != null) { + int size = n.children.size(); + for (int i = size - 1; i >= 0; i--) { + Node child = n.children.get(i); + if (child != null) { + deque.addFirst(child); + } + } + } + } + } + + public void preorderReserve(Node root, List result) { + + if (root == null) { + return; + } + + result.add(root.val); + if (root.children != null) { + for (Node n : root.children) { + preorderReserve(n, result); + } + } + } +} diff --git a/[0590][N-ary Tree postorder Traversal]/[0590][N-ary Tree postorder Traversal].iml b/[0590][N-ary Tree postorder Traversal]/[0590][N-ary Tree postorder Traversal].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0590][N-ary Tree postorder Traversal]/[0590][N-ary Tree postorder Traversal].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0590][N-ary Tree postorder Traversal]/src/Node.java b/[0590][N-ary Tree postorder Traversal]/src/Node.java new file mode 100644 index 0000000..a6c2e09 --- /dev/null +++ b/[0590][N-ary Tree postorder Traversal]/src/Node.java @@ -0,0 +1,24 @@ +import java.util.List; + +/** + * Author: 王俊超 + * Time: 2020-07-03 10:20 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int val) { + this.val = val; + } + + public Node(int val, List children) { + this.val = val; + this.children = children; + } +} diff --git a/[0590][N-ary Tree postorder Traversal]/src/Solution.java b/[0590][N-ary Tree postorder Traversal]/src/Solution.java new file mode 100644 index 0000000..0dcb602 --- /dev/null +++ b/[0590][N-ary Tree postorder Traversal]/src/Solution.java @@ -0,0 +1,63 @@ +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: 王俊超 + * Time: 2020-07-03 10:20 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public List postorder(Node root) { + List result = new LinkedList<>(); +// postorderReserve(root, result); + postorderIterator(root, result); + return result; + } + + public void postorderIterator(Node root, List result) { + if (root == null) { + return; + } + + Deque deque = new LinkedList<>(); + deque.addFirst(root); + Node curr; + Node prev = null; + while (!deque.isEmpty()) { + curr = deque.getFirst(); + if (curr.children == null || curr.children.isEmpty() // 没有子孩子 + ||(prev != null && prev == curr.children.get(curr.children.size() - 1))) { // 前一个遍历的元素是最后一个子孩子,说明子树已经遍历完了 + result.add(curr.val); + prev = curr; + deque.removeFirst(); + } else { + // 有孩子先处理孩子 + int size = curr.children.size(); + for (int i = size - 1; i >= 0; i--) { + Node child = curr.children.get(i); + if (child != null) { + deque.addFirst(child); + } + } + } + } + } + + public void postorderReserve(Node root, List result) { + + if (root == null) { + return; + } + + if (root.children != null) { + for (Node n : root.children) { + postorderReserve(n, result); + } + } + + result.add(root.val); + } +} diff --git a/[0590][N-ary Tree postorder Traversal]/src/SolutionTest.java b/[0590][N-ary Tree postorder Traversal]/src/SolutionTest.java new file mode 100644 index 0000000..36f1259 --- /dev/null +++ b/[0590][N-ary Tree postorder Traversal]/src/SolutionTest.java @@ -0,0 +1,35 @@ +import org.junit.Assert; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +/** + * Author: 王俊超 + * Time: 2020-07-03 10:47 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void postorder() { + Solution s = new Solution(); + + Node root = new Node(1); + root.children = new ArrayList<>(); + root.children.add(new Node(3)); + root.children.add(new Node(2)); + root.children.add(new Node(4)); + root.children.get(0).children = new ArrayList<>(); + root.children.get(0).children.add(new Node(5)); + root.children.get(0).children.add(new Node(6)); + + List result = Arrays.asList(5,6,3,2,4,1); + + Assert.assertEquals(result, s.postorder(root)); + } +} \ No newline at end of file diff --git a/[0594][Longest Harmonious Subsequence]/[0594][Longest Harmonious Subsequence].iml b/[0594][Longest Harmonious Subsequence]/[0594][Longest Harmonious Subsequence].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0594][Longest Harmonious Subsequence]/[0594][Longest Harmonious Subsequence].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0594][Longest Harmonious Subsequence]/src/Solution.java b/[0594][Longest Harmonious Subsequence]/src/Solution.java new file mode 100644 index 0000000..d3ec9aa --- /dev/null +++ b/[0594][Longest Harmonious Subsequence]/src/Solution.java @@ -0,0 +1,78 @@ +import java.util.Arrays; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + +/** + * Author: 王俊超 + * Time: 2020-07-04 15:09 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + + /** + * 求每个元素的个数,再找相邻元素之和最大的 + * 相邻指元素之差为1 + * + * @param nums + * @return + */ + public int findLHS(int[] nums) { + if (nums == null || nums.length < 2) { + return 0; + } + + int max = 0; + Arrays.sort(nums); + + int prevNum = Integer.MIN_VALUE; + int prevCnt = 0; + for (int i = 0; i < nums.length; ) { + int next = i + 1; + while (next < nums.length && nums[next] == nums[i]) { + next++; + } + if (prevNum + 1 == nums[i]) { + max = Math.max(max, prevCnt + next - i); + } + + prevNum = nums[i]; + prevCnt = next - i; + i = next; + + } + + return max; + } + + /** + * 求每个元素的个数,再找相邻元素之和最大的 + * 相邻指元素之差为1 + * + * @param nums + * @return + */ + public int findLHS2(int[] nums) { + if (nums == null || nums.length < 2) { + return 0; + } + + SortedMap map = new TreeMap<>(); + for (int n : nums) { + map.put(n, map.getOrDefault(n, 0) + 1); + } + + int max = 0; + Map.Entry prev = null; // 前一个遍历的元素 + for (Map.Entry entry : map.entrySet()) { + if (prev != null && prev.getKey() + 1 == entry.getKey()) { // 相邻元素 + max = Math.max(max, prev.getValue() + entry.getValue()); // 取较大的 + } + prev = entry; + } + + return max; + } +} diff --git a/[0594][Longest Harmonious Subsequence]/src/SolutionTest.java b/[0594][Longest Harmonious Subsequence]/src/SolutionTest.java new file mode 100644 index 0000000..f51d032 --- /dev/null +++ b/[0594][Longest Harmonious Subsequence]/src/SolutionTest.java @@ -0,0 +1,26 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-04 15:20 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findLHS() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{1, 3, 2, 2, 5, 2, 3, 7}, 5}, + {new int[]{-2, 0, 2, 2, 5, 5, 5, 5}, 0}, + {new int[]{1, 1, 1, 1}, 0}, + }; + + for (Object[] d : data) { + int result = s.findLHS((int[]) d[0]); + Assert.assertEquals(d[1], result); + } + } +} \ No newline at end of file diff --git a/[0598][Range Addition II]/[0598][Range Addition II].iml b/[0598][Range Addition II]/[0598][Range Addition II].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0598][Range Addition II]/[0598][Range Addition II].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0598][Range Addition II]/src/Solution.java b/[0598][Range Addition II]/src/Solution.java new file mode 100644 index 0000000..49747ce --- /dev/null +++ b/[0598][Range Addition II]/src/Solution.java @@ -0,0 +1,29 @@ +/** + * Author: 王俊超 + * Time: 2020-07-04 15:50 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 数组的第一元素一定是最大的,要找最大的元素个数,只要找ops中min(ops[0])*min(ops[1]) + * + * @param m + * @param n + * @param ops + * @return + */ + public int maxCount(int m, int n, int[][] ops) { + + + int row = m; + int col = n; + for (int[] op : ops) { + row = Math.min(op[0], row); + col = Math.min(op[1], col); + } + + return row * col; + } +} diff --git a/[0598][Range Addition II]/src/SolutionTest.java b/[0598][Range Addition II]/src/SolutionTest.java new file mode 100644 index 0000000..8550371 --- /dev/null +++ b/[0598][Range Addition II]/src/SolutionTest.java @@ -0,0 +1,26 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-04 16:04 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void maxCount() { + Solution s = new Solution(); + Object[][] data = { + {3, 3, new int[][]{{2, 2}, {3, 3}}, 4}, + {3, 3, new int[][]{{2, 3}, {3, 2}}, 4}, + {3, 3, new int[][]{}, 9}, + }; + + for (Object[] d : data) { + Object result = s.maxCount((int) d[0], (int)d[1], (int[][]) d[2]); + Assert.assertEquals(d[3], result); + } + } +} \ No newline at end of file diff --git a/[0599][Minimum Index Sum of Two Lists]/[0599][Minimum Index Sum of Two Lists].iml b/[0599][Minimum Index Sum of Two Lists]/[0599][Minimum Index Sum of Two Lists].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0599][Minimum Index Sum of Two Lists]/[0599][Minimum Index Sum of Two Lists].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0599][Minimum Index Sum of Two Lists]/src/Solution.java b/[0599][Minimum Index Sum of Two Lists]/src/Solution.java new file mode 100644 index 0000000..238a202 --- /dev/null +++ b/[0599][Minimum Index Sum of Two Lists]/src/Solution.java @@ -0,0 +1,39 @@ +import java.util.*; + +/** + * Author: 王俊超 + * Time: 2020-07-04 16:13 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public String[] findRestaurant(String[] list1, String[] list2) { + if (list1 == null || list2 == null){ + return null; + } + + Map map = new HashMap<>(); + for (int i = 0; i < list1.length; i++) { + map.put(list1[i], i); + } + List result = new ArrayList<>(list1.length); + + int min = Integer.MAX_VALUE; + + for (int i = 0; i < list2.length; i++) { + if (map.containsKey(list2[i])) { + if (map.get(list2[i]) + i < min) { + result.clear(); + min = map.get(list2[i]) + i; + result.add(list2[i]); + } else if (map.get(list2[i]) + i == min) { + result.add(list2[i]); + } + + } + } + + return result.toArray(new String[0]); + } +} diff --git a/[0599][Minimum Index Sum of Two Lists]/src/SolutionTest.java b/[0599][Minimum Index Sum of Two Lists]/src/SolutionTest.java new file mode 100644 index 0000000..671b81b --- /dev/null +++ b/[0599][Minimum Index Sum of Two Lists]/src/SolutionTest.java @@ -0,0 +1,34 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-04 16:23 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findRestaurant() { + Solution s = new Solution(); + Object[][] data = { + { + new String[]{"Shogun", "Tapioca Express", "Burger King", "KFC"}, + new String[]{"Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"}, + new String[]{"Shogun"}, + }, + { + new String[]{"Shogun","Tapioca Express","Burger King","KFC"}, + new String[]{"KFC","Shogun","Burger King"}, + new String[]{"Shogun"}, + } + + }; + + for (Object[] d : data) { + String[] result = s.findRestaurant((String[]) d[0], (String[]) d[1]); + Assert.assertArrayEquals((String[]) d[2], result); + } + } +} \ No newline at end of file diff --git a/[0605][Can Place Flowers]/[0605][Can Place Flowers].iml b/[0605][Can Place Flowers]/[0605][Can Place Flowers].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0605][Can Place Flowers]/[0605][Can Place Flowers].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0605][Can Place Flowers]/src/Solution.java b/[0605][Can Place Flowers]/src/Solution.java new file mode 100644 index 0000000..d6aed3c --- /dev/null +++ b/[0605][Can Place Flowers]/src/Solution.java @@ -0,0 +1,54 @@ +/** + * Author: 王俊超 + * Time: 2020-07-04 19:42 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + if (flowerbed == null || flowerbed.length < 1) { + return false; + } + + if (n < 1) { + return true; + } + + // 找第一个1的位置 + int firstOneIdx = 0; + while (firstOneIdx < flowerbed.length && flowerbed[firstOneIdx] == 0) { + firstOneIdx++; + } + + // [0,0,0] => 2 + // [0,0] => 1 + // [0] => 0 + int num = firstOneIdx / 2 + firstOneIdx % 2; + + if (firstOneIdx >= flowerbed.length) { + return num >= n; + } else { + // [0,0,0,1] => 1 + // [0,0,1] => 1 + // [0,1] => 0 + num -= firstOneIdx % 2; + } + + int prev = flowerbed[firstOneIdx]; + for (int i = firstOneIdx + 1; i < flowerbed.length; i++) { + if (prev == 0 && flowerbed[i] == 0) { + // i是最后一个,或者下一个位置也没有种花 + if (i + 1 >= flowerbed.length || flowerbed[i + 1] == 0) { + num++; + flowerbed[i] = 1; + } + } + + prev = flowerbed[i]; + } + + + return num >= n; + } +} diff --git a/[0605][Can Place Flowers]/src/SolutionTest.java b/[0605][Can Place Flowers]/src/SolutionTest.java new file mode 100644 index 0000000..b37b2f1 --- /dev/null +++ b/[0605][Can Place Flowers]/src/SolutionTest.java @@ -0,0 +1,31 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-04 19:52 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void canPlaceFlowers() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{1, 0, 0, 0, 1}, 1, true}, + {new int[]{1, 0, 0, 0, 1}, 2, false}, + {new int[]{1, 0, 1, 0, 1}, 1, false}, + {new int[]{1, 0, 1, 0, 0}, 2, false}, + {new int[]{0, 0, 0, 0, 0}, 3, true}, + {new int[]{1, 0, 0, 0, 0, 1}, 2, false}, + {new int[]{1, 0, 0, 0, 0, 1}, 2, false}, + {new int[]{ 0, 0, 1, 0, 1}, 1, true}, + }; + + for (Object[] d : data) { + Object result = s.canPlaceFlowers((int[]) d[0], (Integer) d[1]); + Assert.assertEquals(d[2], result); + } + } +} \ No newline at end of file diff --git a/[0606][Construct String from Binary Tree]/[0606][Construct String from Binary Tree].iml b/[0606][Construct String from Binary Tree]/[0606][Construct String from Binary Tree].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0606][Construct String from Binary Tree]/[0606][Construct String from Binary Tree].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0606][Construct String from Binary Tree]/src/Solution.java b/[0606][Construct String from Binary Tree]/src/Solution.java new file mode 100644 index 0000000..36c2245 --- /dev/null +++ b/[0606][Construct String from Binary Tree]/src/Solution.java @@ -0,0 +1,41 @@ +/** + * Author: 王俊超 + * Time: 2020-07-04 20:09 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public String tree2str(TreeNode t) { + StringBuilder builder = new StringBuilder(100); + tree2str(t, builder); + return builder.toString(); + } + + private void tree2str(TreeNode root, StringBuilder builder) { + if (root == null) { + return; + } + + builder.append(root.val); + + if (root.left == null && root.right == null) { + return; + } + + if (root.left != null && root.right == null) { + builder.append("("); + tree2str(root.left, builder); + builder.append(")"); + } + + if (root.right != null) { + builder.append("("); + tree2str(root.left, builder); + builder.append(")"); + builder.append("("); + tree2str(root.right, builder); + builder.append(")"); + } + } +} diff --git a/[0606][Construct String from Binary Tree]/src/SolutionTest.java b/[0606][Construct String from Binary Tree]/src/SolutionTest.java new file mode 100644 index 0000000..08f47cc --- /dev/null +++ b/[0606][Construct String from Binary Tree]/src/SolutionTest.java @@ -0,0 +1,33 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-04 20:12 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void tree2str() { + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.left = new TreeNode(4); + + Solution s = new Solution(); + Assert.assertEquals("1(2(4))(3)", s.tree2str(root)); + } + + @org.junit.Test + public void tree2str2() { + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.right = new TreeNode(4); + + Solution s = new Solution(); + Assert.assertEquals("1(2()(4))(3)", s.tree2str(root)); + } +} \ No newline at end of file diff --git a/[0606][Construct String from Binary Tree]/src/TreeNode.java b/[0606][Construct String from Binary Tree]/src/TreeNode.java new file mode 100644 index 0000000..8b88e24 --- /dev/null +++ b/[0606][Construct String from Binary Tree]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Date: 2015-08-21 + * Time: 18:45 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} + diff --git a/[0617][Merge Two Binary Trees]/[0617][Merge Two Binary Trees].iml b/[0617][Merge Two Binary Trees]/[0617][Merge Two Binary Trees].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0617][Merge Two Binary Trees]/[0617][Merge Two Binary Trees].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0617][Merge Two Binary Trees]/src/Main.java b/[0617][Merge Two Binary Trees]/src/Main.java new file mode 100644 index 0000000..f0f2e17 --- /dev/null +++ b/[0617][Merge Two Binary Trees]/src/Main.java @@ -0,0 +1,35 @@ +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-04 09:00 + **/ +public class Main { + @Test + public void test1() { + TreeNode t1 = new TreeNode(1); + t1.left = new TreeNode(3); + t1.left.left = new TreeNode(5); + t1.right = new TreeNode(2); + + TreeNode t2 = new TreeNode(2); + t2.left = new TreeNode(1); + t2.left.right = new TreeNode(4); + t2.right = new TreeNode(3); + t2.right.right = new TreeNode(7); + + Solution solution = new Solution(); + + TreeNode node = solution.mergeTrees(t1, t2); + + print(node); + } + + private void print(TreeNode node) { + if (node != null) { + System.out.print(node.val + ", "); + print(node.left); + print(node.right); + } + } +} diff --git a/[0617][Merge Two Binary Trees]/src/Solution.java b/[0617][Merge Two Binary Trees]/src/Solution.java new file mode 100644 index 0000000..3123ffe --- /dev/null +++ b/[0617][Merge Two Binary Trees]/src/Solution.java @@ -0,0 +1,53 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-04 08:57 + **/ +public class Solution { + /** + *
+     * Given two binary trees and imagine that when you put one of them to cover the other,
+     * some nodes of the two trees are overlapped while the others are not.
+     *
+     * You need to merge them into a new binary tree. The merge rule is that if two nodes overlap,
+     * then sum node values up as the new value of the merged node. Otherwise, the NOT null node
+     * will be used as the node of new tree.
+     *
+     * Example 1:
+     *
+     * Input:
+     *         Tree 1                     Tree 2
+     *           1                         2
+     *          / \                       / \
+     *         3   2                     1   3
+     *        /                           \   \
+     *       5                             4   7
+     * Output:
+     * Merged tree:
+     *      3
+     *     / \
+     *    4   5
+     *   / \   \
+     *  5   4   7
+     * 
+ * + * @param t1 + * @param t2 + * @return + */ + public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { + if (t1 == null) { + return t2; + } + + if (t2 == null) { + return t1; + } + + t1.val += t2.val; + + t1.left = mergeTrees(t1.left, t2.left); + t1.right = mergeTrees(t1.right, t2.right); + + return t1; + } +} diff --git a/[0617][Merge Two Binary Trees]/src/TreeNode.java b/[0617][Merge Two Binary Trees]/src/TreeNode.java new file mode 100644 index 0000000..8b88e24 --- /dev/null +++ b/[0617][Merge Two Binary Trees]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Date: 2015-08-21 + * Time: 18:45 + * Declaration: All Rights Reserved !!! + */ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} + diff --git a/[0628][Maximum Product of Three Numbers]/[0628][Maximum Product of Three Numbers].iml b/[0628][Maximum Product of Three Numbers]/[0628][Maximum Product of Three Numbers].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0628][Maximum Product of Three Numbers]/[0628][Maximum Product of Three Numbers].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0628][Maximum Product of Three Numbers]/src/Solution.java b/[0628][Maximum Product of Three Numbers]/src/Solution.java new file mode 100644 index 0000000..a39a8e8 --- /dev/null +++ b/[0628][Maximum Product of Three Numbers]/src/Solution.java @@ -0,0 +1,29 @@ +import java.util.Arrays; + +/** + * Author: 王俊超 + * Time: 2020-07-04 20:23 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int maximumProduct(int[] nums) { + if (nums == null || nums.length < 3) { + return 0; + } + + Arrays.sort(nums); + + int len = nums.length; + + int max = nums[len - 1] * nums[len - 2] * nums[len - 3]; + + if (nums[1] < 0) { // 前两个是负数 + max = Math.max(max, nums[0]*nums[1]*nums[len-1]); + } + + + return max; + } +} diff --git a/[0628][Maximum Product of Three Numbers]/src/SolutionTest.java b/[0628][Maximum Product of Three Numbers]/src/SolutionTest.java new file mode 100644 index 0000000..04697b4 --- /dev/null +++ b/[0628][Maximum Product of Three Numbers]/src/SolutionTest.java @@ -0,0 +1,24 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-04 20:45 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void maximumProduct() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{-4, -3, -2, -1, 60}, 720}, + }; + + for (Object[] d : data) { + int result = s.maximumProduct((int[]) d[0]); + Assert.assertEquals(d[1], result); + } + } +} \ No newline at end of file diff --git a/[0633][Sum of Square Numbers]/[0633][Sum of Square Numbers].iml b/[0633][Sum of Square Numbers]/[0633][Sum of Square Numbers].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0633][Sum of Square Numbers]/[0633][Sum of Square Numbers].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0633][Sum of Square Numbers]/src/Solution.java b/[0633][Sum of Square Numbers]/src/Solution.java new file mode 100644 index 0000000..816b16e --- /dev/null +++ b/[0633][Sum of Square Numbers]/src/Solution.java @@ -0,0 +1,36 @@ +/** + * Author: 王俊超 + * Time: 2020-07-05 16:55 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 解题思路: + * 1、假设b >=a >= 0 + * ==> sqrt(c/2) <= b <= sqrt(c) + * @param c + * @return + */ + public boolean judgeSquareSum(int c) { + + if (c < 0) { + return false; + } + + + int sqrt = (int) Math.sqrt(c); + int halfSqrt = (int) Math.sqrt(c / 2.0); + + for (int i = halfSqrt; i <= sqrt; i++) { + + int sqrt2 = (int) Math.sqrt(c - i * i); + if (sqrt2 * sqrt2 + i * i == c) { + return true; + } + } + + return false; + } +} diff --git a/[0633][Sum of Square Numbers]/src/SolutionTest.java b/[0633][Sum of Square Numbers]/src/SolutionTest.java new file mode 100644 index 0000000..a859ba2 --- /dev/null +++ b/[0633][Sum of Square Numbers]/src/SolutionTest.java @@ -0,0 +1,30 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-05 17:00 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void judgeSquareSum() { + Solution s = new Solution(); + Object[][] data = { + {0, true}, + {1, true}, + {2, true}, + {3, false}, + {4, true}, + {5, true}, + {1000, true}, + }; + + for (Object[] d : data) { + Object result = s.judgeSquareSum((int) d[0]); + Assert.assertEquals(d[1], result); + } + } +} \ No newline at end of file diff --git "a/\343\200\220007\343\200\221\343\200\220ReverseInteger\343\200\221/\343\200\220007\343\200\221\343\200\220ReverseInteger\343\200\221.iml" b/[0637][Average of Levels in Binary Tree]/[0637][Average of Levels in Binary Tree].iml similarity index 100% rename from "\343\200\220007\343\200\221\343\200\220ReverseInteger\343\200\221/\343\200\220007\343\200\221\343\200\220ReverseInteger\343\200\221.iml" rename to [0637][Average of Levels in Binary Tree]/[0637][Average of Levels in Binary Tree].iml diff --git a/[0637][Average of Levels in Binary Tree]/src/Solution.java b/[0637][Average of Levels in Binary Tree]/src/Solution.java new file mode 100644 index 0000000..9e113fb --- /dev/null +++ b/[0637][Average of Levels in Binary Tree]/src/Solution.java @@ -0,0 +1,48 @@ +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; + +/** + * Author: 王俊超 + * Time: 2020-07-04 16:32 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public List averageOfLevels(TreeNode root) { + List result = new ArrayList<>(); + + if (root == null) { + return result; + } + + Deque curr = new LinkedList<>(); + Deque next = new LinkedList<>(); + curr.addFirst(root); + + while (!curr.isEmpty()) { + + double count = curr.size(); + double sum = 0; + while (!curr.isEmpty()) { + TreeNode node = curr.removeFirst(); + sum += node.val; + + if (node.left != null) { + next.addLast(node.left); + } + if (node.right != null) { + next.addLast(node.right); + } + } + + result.add(sum / count); + curr = next; + next = new LinkedList<>(); + } + + return result; + } +} diff --git a/[0637][Average of Levels in Binary Tree]/src/TreeNode.java b/[0637][Average of Levels in Binary Tree]/src/TreeNode.java new file mode 100644 index 0000000..5554849 --- /dev/null +++ b/[0637][Average of Levels in Binary Tree]/src/TreeNode.java @@ -0,0 +1,13 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 18:52 + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0643][Maximum Average Subarray I]/[0643][Maximum Average Subarray I].iml b/[0643][Maximum Average Subarray I]/[0643][Maximum Average Subarray I].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0643][Maximum Average Subarray I]/[0643][Maximum Average Subarray I].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0643][Maximum Average Subarray I]/src/Solution.java b/[0643][Maximum Average Subarray I]/src/Solution.java new file mode 100644 index 0000000..d0a7f8c --- /dev/null +++ b/[0643][Maximum Average Subarray I]/src/Solution.java @@ -0,0 +1,28 @@ +/** + * Author: 王俊超 + * Time: 2020-07-05 16:23 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public double findMaxAverage(int[] nums, int k) { + if (nums == null || nums.length < 1 || k < 1) { + return 0; + } + + double sum = 0; + for (int i = 0; i < nums.length && i < k; i++) { // 求nums[0, k-1]的和 + sum += nums[i]; + } + + double max = sum; + for (int j = k; j < nums.length; j++) { // 求nums[j-k,j]中的大值 + sum = sum + nums[j] - nums[j - k]; + max = Math.max(max, sum); + + } + + return max / k; + } +} diff --git a/[0643][Maximum Average Subarray I]/src/SolutionTest.java b/[0643][Maximum Average Subarray I]/src/SolutionTest.java new file mode 100644 index 0000000..f698ef1 --- /dev/null +++ b/[0643][Maximum Average Subarray I]/src/SolutionTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-05 16:29 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findMaxAverage() { + Solution s = new Solution(); + Object[][] data = { +// {new int[]{1, 12, -5, -6, 50, 3}, 4, 12.75}, + {new int[]{7, 4, 5, 8, 8, 3, 9, 8, 7, 6}, 7, 7.0}, + }; + + for (Object[] d : data) { + Object result = s.findMaxAverage((int[]) d[0], (Integer) d[1]); + Assert.assertEquals(d[2], result); + } + } +} \ No newline at end of file diff --git a/[0645][Set Mismatch]/[0645][Set Mismatch].iml b/[0645][Set Mismatch]/[0645][Set Mismatch].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0645][Set Mismatch]/[0645][Set Mismatch].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0645][Set Mismatch]/src/Solution.java b/[0645][Set Mismatch]/src/Solution.java new file mode 100644 index 0000000..006c5f8 --- /dev/null +++ b/[0645][Set Mismatch]/src/Solution.java @@ -0,0 +1,43 @@ +import java.util.HashSet; +import java.util.Set; + +/** + * Author: 王俊超 + * Time: 2020-07-05 17:13 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 通过求和找丢失的数 + * m + x + y = total + * m + x + x = sum + * y - x = total -sum + * + * @param nums + * @return + */ + public int[] findErrorNums(int[] nums) { + if (nums == null || nums.length < 1) { + return null; + } + + Set map = new HashSet<>(); + int num = 1; + int sum = 0; + + for (int n : nums) { + if (map.contains(n)) { + num = n; + } else { + map.add(n); + } + sum += n; + } + + return new int[]{num, (1 + nums.length) * nums.length / 2 - sum + num}; + + } + +} diff --git a/[0645][Set Mismatch]/src/SolutionTest.java b/[0645][Set Mismatch]/src/SolutionTest.java new file mode 100644 index 0000000..93087a5 --- /dev/null +++ b/[0645][Set Mismatch]/src/SolutionTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-05 17:19 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findErrorNums() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{1, 2, 2, 4}, new int[]{2, 3}}, + {new int[]{1, 3, 2, 4, 4}, new int[]{4, 5}}, + }; + + for (Object[] d : data) { + int[] result = s.findErrorNums((int[]) d[0]); + Assert.assertArrayEquals((int[]) d[1], result); + } + } +} \ No newline at end of file diff --git a/[0653][Two Sum IV - Input is a BST]/[0653][Two Sum IV - Input is a BST].iml b/[0653][Two Sum IV - Input is a BST]/[0653][Two Sum IV - Input is a BST].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0653][Two Sum IV - Input is a BST]/[0653][Two Sum IV - Input is a BST].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0653][Two Sum IV - Input is a BST]/src/Solution.java b/[0653][Two Sum IV - Input is a BST]/src/Solution.java new file mode 100644 index 0000000..05f7a25 --- /dev/null +++ b/[0653][Two Sum IV - Input is a BST]/src/Solution.java @@ -0,0 +1,69 @@ +import java.util.HashSet; +import java.util.Set; + +/** + * Author: 王俊超 + * Time: 2020-07-05 18:20 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: + * 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; + * 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; + * 它的左、右子树也分别为二叉排序树。 + * + * @param root + * @param k + * @return + */ + + + public boolean findTarget(TreeNode root, int k) { + Set set = new HashSet<>(); + return findTargetHelp(root, k, set); + } + + private boolean findTargetHelp(TreeNode root, int k, Set set) { + if (root == null) { + return false; + } + if (set.contains(k - root.val)) { + return true; + } + + set.add(root.val); + + return findTargetHelp(root.left, k, set) || findTargetHelp(root.right, k, set); + } + + public boolean findTarget2(TreeNode root, int k) { + if (root == null) { + return false; + } + + Set set = new HashSet<>(); + visitTree(root, set); + + for (Integer n : set) { + if (n != k - n && set.contains(k - n)) { + return true; + } + } + + return false; + } + + public void visitTree(TreeNode root, Set set) { + if (root == null) { + return; + } + + set.add(root.val); + + visitTree(root.left, set); + visitTree(root.right, set); + } +} diff --git a/[0653][Two Sum IV - Input is a BST]/src/SolutionTest.java b/[0653][Two Sum IV - Input is a BST]/src/SolutionTest.java new file mode 100644 index 0000000..792632a --- /dev/null +++ b/[0653][Two Sum IV - Input is a BST]/src/SolutionTest.java @@ -0,0 +1,19 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-05 18:35 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findTarget() { + Solution s = new Solution(); + TreeNode root = new TreeNode(1); + + Assert.assertFalse(s.findTarget(root, 2)); + } +} \ No newline at end of file diff --git a/[0653][Two Sum IV - Input is a BST]/src/TreeNode.java b/[0653][Two Sum IV - Input is a BST]/src/TreeNode.java new file mode 100644 index 0000000..5554849 --- /dev/null +++ b/[0653][Two Sum IV - Input is a BST]/src/TreeNode.java @@ -0,0 +1,13 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 18:52 + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git "a/\343\200\220008\343\200\221\343\200\220StringToInteger (atoi)\343\200\221/\343\200\220008\343\200\221\343\200\220StringToInteger (atoi)\343\200\221.iml" b/[0657][Robot Return to Origin]/[0657][Robot Return to Origin].iml similarity index 100% rename from "\343\200\220008\343\200\221\343\200\220StringToInteger (atoi)\343\200\221/\343\200\220008\343\200\221\343\200\220StringToInteger (atoi)\343\200\221.iml" rename to [0657][Robot Return to Origin]/[0657][Robot Return to Origin].iml diff --git a/[0657][Robot Return to Origin]/src/Solution.java b/[0657][Robot Return to Origin]/src/Solution.java new file mode 100644 index 0000000..e02ca96 --- /dev/null +++ b/[0657][Robot Return to Origin]/src/Solution.java @@ -0,0 +1,34 @@ +/** + * Author: 王俊超 + * Time: 2020-07-04 20:51 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public boolean judgeCircle(String moves) { + if (moves == null || moves.length() < 1) { + return true; + } + + int[] pos = {0, 0}; + for (int i = 0; i < moves.length(); i++) { + switch (moves.charAt(i)) { + case 'U': + pos[1]++; + break; + case 'D': + pos[1]--; + break; + case 'L': + pos[0]--; + break; + case 'R': + pos[0]++; + break; + } + } + + return pos[0] == 0 && pos[1] == 0; + } +} diff --git a/[0661][Image Smoother]/[0661][Image Smoother].iml b/[0661][Image Smoother]/[0661][Image Smoother].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0661][Image Smoother]/[0661][Image Smoother].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0661][Image Smoother]/src/Solution.java b/[0661][Image Smoother]/src/Solution.java new file mode 100644 index 0000000..a92e9d8 --- /dev/null +++ b/[0661][Image Smoother]/src/Solution.java @@ -0,0 +1,32 @@ +/** + * Author: 王俊超 + * Time: 2020-07-06 08:11 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + + public int[][] imageSmoother(int[][] M) { + int[][] result = new int[M.length][]; + for (int i = 0; i < M.length; i++) { + result[i] = new int[M[i].length]; + } + + for (int i = 0; i < M.length; i++) { + for (int j = 0; j < M[0].length; j++) { + int count = 0; + int sum = 0; + for (int u = Math.max(0, i - 1); u <= i + 1 && u < M.length; u++) { + for (int v = Math.max(0, j - 1); v <= j + 1 && v < M[0].length; v++) { + count++; + sum += M[u][v]; + } + } + result[i][j] = sum / count; + } + } + + return result; + } +} diff --git a/[0661][Image Smoother]/src/SolutionTest.java b/[0661][Image Smoother]/src/SolutionTest.java new file mode 100644 index 0000000..311d241 --- /dev/null +++ b/[0661][Image Smoother]/src/SolutionTest.java @@ -0,0 +1,29 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-06 08:17 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void imageSmoother() { + Solution s = new Solution(); + Object[][] data = { + { + new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}, + new int[][]{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, + }, + }; + + for (Object[] d : data) { + int[][] result = s.imageSmoother((int[][]) d[0]); + for (int i = 0; i < result.length; i++) { + Assert.assertArrayEquals(((int[][]) d[1])[i], result[i]); + } + } + } +} \ No newline at end of file diff --git a/[0665][Non-decreasing Array]/[0665][Non-decreasing Array].iml b/[0665][Non-decreasing Array]/[0665][Non-decreasing Array].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0665][Non-decreasing Array]/[0665][Non-decreasing Array].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0665][Non-decreasing Array]/src/Solution.java b/[0665][Non-decreasing Array]/src/Solution.java new file mode 100644 index 0000000..db06448 --- /dev/null +++ b/[0665][Non-decreasing Array]/src/Solution.java @@ -0,0 +1,34 @@ +/** + * Author: 王俊超 + * Time: 2020-07-06 08:27 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + + /** + * 解题思路: + * 其实说的简单点,有2种情况: + * 升序序列中,突然有个数字小了,则nums[i]=nums[i-1] + * 升序序列中,突然有个数字大了,则nums[i-1]=nums[i] + * + * @param nums + * @return + */ + public boolean checkPossibility(int[] nums) { + int fix = 0; + for (int i = 1; i < nums.length && fix <= 1; i++) { + if (nums[i] >= nums[i - 1]) { + continue; + } + fix++; + if (i - 2 >= 0 && (nums[i] < nums[i - 2])) { // 突然有个数字小了 + nums[i] = nums[i - 1]; + } else {// 突然有个数字大了 + nums[i - 1] = nums[i]; + } + } + return fix <= 1; + } +} diff --git a/[0665][Non-decreasing Array]/src/SolutionTest.java b/[0665][Non-decreasing Array]/src/SolutionTest.java new file mode 100644 index 0000000..1667886 --- /dev/null +++ b/[0665][Non-decreasing Array]/src/SolutionTest.java @@ -0,0 +1,28 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-06 08:38 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void checkPossibility() { + Solution s = new Solution(); + Object[][] data = { +// {new int[]{1, 2, 3, 4, 6, 5, 7, 8, 9}, true}, +// {new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, true}, +// {new int[]{4, 2, 3}, true}, +// {new int[]{4, 2, 1}, false}, + {new int[]{-1, 4, 2, 3}, false}, + }; + + for (Object[] d : data) { + boolean result = s.checkPossibility((int[]) d[0]); + Assert.assertEquals(d[1], result); + } + } +} \ No newline at end of file diff --git "a/\343\200\220009\343\200\221\343\200\220PalindromeNumber\343\200\221/\343\200\220009\343\200\221\343\200\220PalindromeNumber\343\200\221.iml" b/[0669][Trim a Binary Search Tree]/[0669][Trim a Binary Search Tree].iml similarity index 100% rename from "\343\200\220009\343\200\221\343\200\220PalindromeNumber\343\200\221/\343\200\220009\343\200\221\343\200\220PalindromeNumber\343\200\221.iml" rename to [0669][Trim a Binary Search Tree]/[0669][Trim a Binary Search Tree].iml diff --git a/[0669][Trim a Binary Search Tree]/src/Solution.java b/[0669][Trim a Binary Search Tree]/src/Solution.java new file mode 100644 index 0000000..c86b80d --- /dev/null +++ b/[0669][Trim a Binary Search Tree]/src/Solution.java @@ -0,0 +1,33 @@ +/** + * Author: 王俊超 + * Time: 2020-07-06 08:58 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public TreeNode trimBST(TreeNode root, int L, int R) { + if (root == null) { + return null; + } + + if (root.val == L) { + root.left = null; + root.right = trimBST(root.right, L, R); + return root; + } else if (root.val == R) { + root.left = trimBST(root.left, L, R); + root.right = null; + return root; + } else if (root.val < L) { + return trimBST(root.right, L, R); + } else if (root.val > R) { + return trimBST(root.left, L, R); + } + + root.left = trimBST(root.left, L, R); + root.right = trimBST(root.right, L, R); + + return root; + } +} diff --git a/[0669][Trim a Binary Search Tree]/src/TreeNode.java b/[0669][Trim a Binary Search Tree]/src/TreeNode.java new file mode 100644 index 0000000..bff99a6 --- /dev/null +++ b/[0669][Trim a Binary Search Tree]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 11:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0671][Second Minimum Node In a Binary Tree]/[0671][Second Minimum Node In a Binary Tree].iml b/[0671][Second Minimum Node In a Binary Tree]/[0671][Second Minimum Node In a Binary Tree].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0671][Second Minimum Node In a Binary Tree]/[0671][Second Minimum Node In a Binary Tree].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0671][Second Minimum Node In a Binary Tree]/src/Solution.java b/[0671][Second Minimum Node In a Binary Tree]/src/Solution.java new file mode 100644 index 0000000..6562244 --- /dev/null +++ b/[0671][Second Minimum Node In a Binary Tree]/src/Solution.java @@ -0,0 +1,68 @@ +import java.util.SortedSet; +import java.util.TreeSet; + +/** + * Author: 王俊超 + * Time: 2020-07-07 08:58 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * @param root + * @return + */ + + public int findSecondMinimumValue(TreeNode root) { + if (root == null){ + return -1; + } + return help(root, root.val); + } + + private int help(TreeNode root, int min) { + if (root == null){ + return -1; + } + if (root.val > min) { + return root.val; + } + int left = help(root.left, min); + int right = help(root.right, min); + + if (left == -1) { + return right; + } + if (right == -1) { + return left; + } + + return Math.min(left, right); + } + + public int findSecondMinimumValue2(TreeNode root) { + SortedSet result = new TreeSet<>(); + findSecondMinimumValue(root, result); + + if (result.size() < 2) { + return -1; + } + + result.remove(result.first()); + return result.first(); + } + + /** + * @param root + * @param result 是一个从小到大的size=2的有序数组 + */ + private void findSecondMinimumValue(TreeNode root, SortedSet result) { + if (root == null) { + return; + } + result.add(root.val); + findSecondMinimumValue(root.left, result); + findSecondMinimumValue(root.right, result); + } +} diff --git a/[0671][Second Minimum Node In a Binary Tree]/src/SolutionTest.java b/[0671][Second Minimum Node In a Binary Tree]/src/SolutionTest.java new file mode 100644 index 0000000..26dc827 --- /dev/null +++ b/[0671][Second Minimum Node In a Binary Tree]/src/SolutionTest.java @@ -0,0 +1,24 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-07 09:13 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findSecondMinimumValue() { + Solution s = new Solution(); + + TreeNode root = new TreeNode(2); + root.left = new TreeNode(2); + root.right = new TreeNode(5); + root.right.left = new TreeNode(5); + root.right.right = new TreeNode(7); + + Assert.assertEquals(5, s.findSecondMinimumValue(root)); + } +} \ No newline at end of file diff --git a/[0671][Second Minimum Node In a Binary Tree]/src/TreeNode.java b/[0671][Second Minimum Node In a Binary Tree]/src/TreeNode.java new file mode 100644 index 0000000..bff99a6 --- /dev/null +++ b/[0671][Second Minimum Node In a Binary Tree]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 11:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0674][Longest Continuous Increasing Subsequence]/[0674][Longest Continuous Increasing Subsequence].iml b/[0674][Longest Continuous Increasing Subsequence]/[0674][Longest Continuous Increasing Subsequence].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0674][Longest Continuous Increasing Subsequence]/[0674][Longest Continuous Increasing Subsequence].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0674][Longest Continuous Increasing Subsequence]/src/Solution.java b/[0674][Longest Continuous Increasing Subsequence]/src/Solution.java new file mode 100644 index 0000000..5a15c9f --- /dev/null +++ b/[0674][Longest Continuous Increasing Subsequence]/src/Solution.java @@ -0,0 +1,30 @@ +/** + * Author: 王俊超 + * Time: 2020-07-07 10:03 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + + public int findLengthOfLCIS(int[] nums) { + if (nums == null) { + return 0; + } else if (nums.length < 2) { + return nums.length; + } + + int prev = 0; + int max = 0; + for (int i = 1; i < nums.length; i++) { + while (i < nums.length && nums[i - 1] < nums[i]) { + i++; + } + + max = Math.max(max, i - prev); + prev = i; + } + + return max; + } +} diff --git a/[0674][Longest Continuous Increasing Subsequence]/src/SolutionTest.java b/[0674][Longest Continuous Increasing Subsequence]/src/SolutionTest.java new file mode 100644 index 0000000..351e6f5 --- /dev/null +++ b/[0674][Longest Continuous Increasing Subsequence]/src/SolutionTest.java @@ -0,0 +1,27 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-07 10:07 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void findLengthOfLCIS() { + Solution s = new Solution(); + Object[][] data = { + {new int[]{1, 3, 5, 4, 7}, 3}, + {new int[]{2, 2, 2, 2, 2}, 1}, + {new int[]{1, 2, 3, 4, 5}, 5}, + {new int[]{2, 2, 3, 4, 5}, 4}, + }; + + for (Object[] d : data) { + int result = s.findLengthOfLCIS((int[]) d[0]); + Assert.assertEquals(d[1], result); + } + } +} \ No newline at end of file diff --git "a/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221.iml" b/[0680][Valid Palindrome II]/[0680][Valid Palindrome II].iml similarity index 100% rename from "\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221.iml" rename to [0680][Valid Palindrome II]/[0680][Valid Palindrome II].iml diff --git a/[0680][Valid Palindrome II]/src/Solution.java b/[0680][Valid Palindrome II]/src/Solution.java new file mode 100644 index 0000000..9ae5eb2 --- /dev/null +++ b/[0680][Valid Palindrome II]/src/Solution.java @@ -0,0 +1,35 @@ +/** + * Author: 王俊超 + * Time: 2020-07-07 10:12 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public boolean validPalindrome(String s) { + int start = 0; + int end = s.length() - 1; + while (start < end) { + // 有一个不相等,可以抛弃start或者end字符,抛弃一个字符后,后面的都要是回文 + if (s.charAt(start) != s.charAt(end)) { + return validPalindrome(s, start + 1, end) || validPalindrome(s, start, end - 1); + } + start++; + end--; + } + + return true; + } + + private boolean validPalindrome(String s, int start, int end) { + while (start < end) { + if (s.charAt(start) != s.charAt(end)) { + return false; + } + start++; + end--; + } + + return true; + } +} diff --git a/[0682][Baseball Game]/[0682][Baseball Game].iml b/[0682][Baseball Game]/[0682][Baseball Game].iml new file mode 100644 index 0000000..c70cbf1 --- /dev/null +++ b/[0682][Baseball Game]/[0682][Baseball Game].iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0682][Baseball Game]/src/Solution.java b/[0682][Baseball Game]/src/Solution.java new file mode 100644 index 0000000..4af7f26 --- /dev/null +++ b/[0682][Baseball Game]/src/Solution.java @@ -0,0 +1,43 @@ +import java.util.LinkedList; +import java.util.List; + +/** + * Author: 王俊超 + * Time: 2020-07-07 12:46 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + public int calPoints(String[] ops) { + + if (ops == null || ops.length < 1) { + return 0; + } + List round = new LinkedList<>(); + + for (String o : ops) { + int size = round.size(); + switch (o) { + case "+": + round.add(round.get(size - 1) + round.get(size - 2)); + break; + case "D": + round.add(2 * round.get(size - 1)); + break; + case "C": + round.remove(size - 1); + break; + default: + round.add(Integer.parseInt(o)); + } + } + + int sum = 0; + for(Integer n : round) { + sum += n; + } + + return sum; + } +} diff --git a/[0682][Baseball Game]/src/SolutionTest.java b/[0682][Baseball Game]/src/SolutionTest.java new file mode 100644 index 0000000..1cf9c9d --- /dev/null +++ b/[0682][Baseball Game]/src/SolutionTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; + +/** + * Author: 王俊超 + * Time: 2020-07-07 12:53 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class SolutionTest { + + @org.junit.Test + public void calPoints() { + Solution s = new Solution(); + Object[][] data = { + {new String[]{"5", "2", "C", "D", "+"}, 30}, + {new String[]{"5", "-2", "4", "C", "D", "9", "+", "+"}, 27}, + }; + + for (Object[] d : data) { + int result = s.calPoints((String[]) d[0]); + Assert.assertEquals(d[1], result); + } + } +} \ No newline at end of file diff --git "a/\343\200\220011\343\200\221\343\200\220ContainerWithMost Water\343\200\221/\343\200\220011\343\200\221\343\200\220ContainerWithMost Water\343\200\221.iml" b/[0783][Minimum Distance Between BST Nodes]/[0783][Minimum Distance Between BST Nodes].iml similarity index 100% rename from "\343\200\220011\343\200\221\343\200\220ContainerWithMost Water\343\200\221/\343\200\220011\343\200\221\343\200\220ContainerWithMost Water\343\200\221.iml" rename to [0783][Minimum Distance Between BST Nodes]/[0783][Minimum Distance Between BST Nodes].iml diff --git a/[0783][Minimum Distance Between BST Nodes]/src/Solution.java b/[0783][Minimum Distance Between BST Nodes]/src/Solution.java new file mode 100644 index 0000000..0230f1b --- /dev/null +++ b/[0783][Minimum Distance Between BST Nodes]/src/Solution.java @@ -0,0 +1,50 @@ +import java.util.*; + +/** + * Author: 王俊超 + * Time: 2020-06-29 10:09 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class Solution { + /** + * 解题思路 + * root提个二叉搜索树 + * 二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: + * 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; + * 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; + * 它的左、右子树也分别为二叉排序树。 + * + * @param root + * @return + */ + public int minDiffInBST(TreeNode root) { + if (root == null) { + return 0; + } + Deque s = new LinkedList<>(); + int min = Integer.MAX_VALUE; + int prev = 0; + boolean first = true; + while (root != null || !s.isEmpty()) { + while (root != null) { + s.push(root);//先访问再入栈 + root = root.left; + } + root = s.pop(); + + if (first) { + first = false; + } else { + min = Math.min(min, root.val - prev); + } + + prev = root.val; + root = root.right;//如果是null,出栈并处理右子树 + } + + return min; + } + +} diff --git a/[0783][Minimum Distance Between BST Nodes]/src/TreeNode.java b/[0783][Minimum Distance Between BST Nodes]/src/TreeNode.java new file mode 100644 index 0000000..bff99a6 --- /dev/null +++ b/[0783][Minimum Distance Between BST Nodes]/src/TreeNode.java @@ -0,0 +1,16 @@ +/** + * Author: 王俊超 + * Time: 2020-06-29 11:06 + * CSDN: http://blog.csdn.net/derrantcm + * Github: https://github.com/Wang-Jun-Chao + * Declaration: All Rights Reserved !!! + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[0969][Pancake Sorting]/[0969][Pancake Sorting].iml b/[0969][Pancake Sorting]/[0969][Pancake Sorting].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0969][Pancake Sorting]/[0969][Pancake Sorting].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0969][Pancake Sorting]/src/Main.java b/[0969][Pancake Sorting]/src/Main.java new file mode 100644 index 0000000..2778b3c --- /dev/null +++ b/[0969][Pancake Sorting]/src/Main.java @@ -0,0 +1,17 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 18:37 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + + Assert.assertEquals(Arrays.asList(4, 2, 4, 3), solution.pancakeSort(new int[]{3, 2, 4, 1})); + } +} diff --git a/[0969][Pancake Sorting]/src/Solution.java b/[0969][Pancake Sorting]/src/Solution.java new file mode 100644 index 0000000..4aafc53 --- /dev/null +++ b/[0969][Pancake Sorting]/src/Solution.java @@ -0,0 +1,89 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * https://leetcode.com/problems/pancake-sorting/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 18:29 + **/ +public class Solution { + /** + *
+     * Given an array A, we can perform a pancake flip: We choose some positive integer
+     * k <= A.length, then reverse the order of the first k elements of A.  We want to
+     * perform zero or more pancake flips (doing them one after another in succession)
+     * to sort the array A.
+     *
+     * Return the k-values corresponding to a sequence of pancake flips that sort A.
+     * Any valid answer that sorts the array within 10 * A.length flips will be judged
+     * as correct.
+     *
+     *
+     *
+     * Example 1:
+     *
+     * Input: [3,2,4,1]
+     * Output: [4,2,4,3]
+     * Explanation:
+     * We perform 4 pancake flips, with k values 4, 2, 4, and 3.
+     * Starting state: A = [3, 2, 4, 1]
+     * After 1st flip (k=4): A = [1, 4, 2, 3]
+     * After 2nd flip (k=2): A = [4, 1, 2, 3]
+     * After 3rd flip (k=4): A = [3, 2, 1, 4]
+     * After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted.
+     * Example 2:
+     *
+     * Input: [1,2,3]
+     * Output: []
+     * Explanation: The input is already sorted, so there is no need to flip anything.
+     * Note that other answers, such as [3, 3], would also be accepted.
+     *
+     * 思路:
+     * (1)找到当前序列的最大值;
+     * (2)翻到序列的首位置;
+     * (3)翻到当前序列最后的位置;
+     * 完成把当前最大值放到最后的操作,即完成选择排序的选择最大值到最后的操作。
+     * 缩减未排序的序列,即可完成排序;
+     * 
+ * + * @param nums nums元素的值是[1, 2, ..., nums.length]的一个排列 + * @return + */ + public List pancakeSort(int[] nums) { + List result = new ArrayList<>(); + + if (nums != null && nums.length > 1) { + for (int i = nums.length - 1; i >= 0; i--) { + int pos = 0; + while (pos <= i) { + if (nums[pos] == i + 1) { + break; + } + pos++; + } + + // pos == i说明i位置的元素已经排好了 + if (pos < i) { + reverse(nums, 0, pos); + reverse(nums, 0, i); + result.add(pos + 1); + result.add(i + 1); + } + + } + } + + return result; + } + + private void reverse(int[] arr, int x, int y) { + while (x < y) { + int temp = arr[x]; + arr[x] = arr[y]; + arr[y] = temp; + x++; + y--; + } + } +} diff --git a/[0979][Distribute Coins in Binary Tree]/[0979][Distribute Coins in Binary Tree].iml b/[0979][Distribute Coins in Binary Tree]/[0979][Distribute Coins in Binary Tree].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[0979][Distribute Coins in Binary Tree]/[0979][Distribute Coins in Binary Tree].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[0979][Distribute Coins in Binary Tree]/src/Main.java b/[0979][Distribute Coins in Binary Tree]/src/Main.java new file mode 100644 index 0000000..c9963cb --- /dev/null +++ b/[0979][Distribute Coins in Binary Tree]/src/Main.java @@ -0,0 +1,18 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 21:10 + **/ +public class Main { + @Test + public void test1() { + TreeNode root = new TreeNode(3); + root.left = new TreeNode(0); + root.right = new TreeNode(0); + + Solution solution = new Solution(); + Assert.assertEquals(2, solution.distributeCoins(root)); + } +} diff --git a/[0979][Distribute Coins in Binary Tree]/src/Solution.java b/[0979][Distribute Coins in Binary Tree]/src/Solution.java new file mode 100644 index 0000000..fac903d --- /dev/null +++ b/[0979][Distribute Coins in Binary Tree]/src/Solution.java @@ -0,0 +1,62 @@ +/** + * https://leetcode.com/problems/distribute-coins-in-binary-tree/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 18:52 + **/ +public class Solution { + + private int moves = 0; + + /** + *
+     * 解题思路:这个题目有点意思,我的方法是“借”的思想。对于任意一个叶子节点,如果val是0,
+     * 那么表示要向其父节点取一个coin,那么parent.val -= 1, moves += 1;如果是叶子节点
+     * 的val大于1,那么表示要给父节点val-1个coin,同时moves += (val-1)。当然这两种情况
+     * 可以用通用的表达式:move += abs(node.val - 1), parent.val += (node.val - 1)。
+     * 按照后序遍历的方式即可算出总的move次数。
+     *
+     * https://www.cnblogs.com/seyjs/p/10369614.html
+     * 
+ * + * @param root + * @return + */ + public int distributeCoins(TreeNode root) { + if (root == null) { + return 0; + } + + moves = 0; + distributeCoins(root, null); + return moves; + } + + /** + * 自底向上,对每一个节点,只能从父结点借,或者向父节点上交coin + * + * @param node + * @param parent + */ + private void distributeCoins(TreeNode node, TreeNode parent) { + + if (node == null) { + return; + } + + if (node.left != null) { + distributeCoins(node.left, node); + } + + if (node.right != null) { + distributeCoins(node.right, node); + } + + // 不论向父节点借还是上交都要移动Math.abs(node.val - 1)次 + moves += Math.abs(node.val - 1); + if (parent != null) { + // 标记父结点 + parent.val += node.val - 1; + } + } +} diff --git a/[0979][Distribute Coins in Binary Tree]/src/TreeNode.java b/[0979][Distribute Coins in Binary Tree]/src/TreeNode.java new file mode 100644 index 0000000..5554849 --- /dev/null +++ b/[0979][Distribute Coins in Binary Tree]/src/TreeNode.java @@ -0,0 +1,13 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-09 18:52 + **/ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/[1089][Duplicate Zeros]/[1089][Duplicate Zeros].iml b/[1089][Duplicate Zeros]/[1089][Duplicate Zeros].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[1089][Duplicate Zeros]/[1089][Duplicate Zeros].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[1089][Duplicate Zeros]/src/Main.java b/[1089][Duplicate Zeros]/src/Main.java new file mode 100644 index 0000000..43d9011 --- /dev/null +++ b/[1089][Duplicate Zeros]/src/Main.java @@ -0,0 +1,16 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-12 08:53 + **/ +public class Main { + @Test + public void test1() { + Solution solution = new Solution(); + int[] arr = {1, 0, 2, 3, 0, 4, 5, 0}; + solution.duplicateZeros(arr); + Assert.assertArrayEquals(new int[]{1, 0, 0, 2, 3, 0, 0, 4}, arr); + } +} diff --git a/[1089][Duplicate Zeros]/src/Solution.java b/[1089][Duplicate Zeros]/src/Solution.java new file mode 100644 index 0000000..701084f --- /dev/null +++ b/[1089][Duplicate Zeros]/src/Solution.java @@ -0,0 +1,21 @@ +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-12 08:44 + **/ +public class Solution { + public void duplicateZeros(int[] arr) { + for (int i = 0; i < arr.length - 1; i++) { + if (arr[i] == 0) { + move(arr, i + 1); + arr[i + 1] = 0; + i++; + } + } + } + + private void move(int[] arr, int i) { + if (arr.length - 1 - i >= 0) { + System.arraycopy(arr, i, arr, i + 1, arr.length - 1 - i); + } + } +} diff --git a/[1108][Defanging an IP Address]/[1108][Defanging an IP Address].iml b/[1108][Defanging an IP Address]/[1108][Defanging an IP Address].iml new file mode 100644 index 0000000..c8cb479 --- /dev/null +++ b/[1108][Defanging an IP Address]/[1108][Defanging an IP Address].iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/[1108][Defanging an IP Address]/src/Main.java b/[1108][Defanging an IP Address]/src/Main.java new file mode 100644 index 0000000..5e2aba0 --- /dev/null +++ b/[1108][Defanging an IP Address]/src/Main.java @@ -0,0 +1,22 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * @author: wangjunchao(王俊超) + * @time: 2019-07-12 08:37 + **/ +public class Main { + @Test + public void test1() { + String address = "1.1.1.1"; + Solution solution = new Solution(); + Assert.assertEquals("1[.]1[.]1[.]1", solution.defangIPaddr(address)); + } + + @Test + public void test2() { + String address = "255.100.50.0"; + Solution solution = new Solution(); + Assert.assertEquals("255[.]100[.]50[.]0", solution.defangIPaddr(address)); + } +} diff --git a/[1108][Defanging an IP Address]/src/Solution.java b/[1108][Defanging an IP Address]/src/Solution.java new file mode 100644 index 0000000..8667b05 --- /dev/null +++ b/[1108][Defanging an IP Address]/src/Solution.java @@ -0,0 +1,50 @@ +/** + * https://leetcode.com/problems/defanging-an-ip-address/submissions/ + * + * @author: wangjunchao(王俊超) + * @time: 2019-07-12 08:31 + **/ +public class Solution { + /** + *
+     * Given a valid (IPv4) IP address, return a defanged version of that IP address.
+     *
+     * A defanged IP address replaces every period "." with "[.]".
+     *
+     *
+     *
+     * Example 1:
+     *
+     * Input: address = "1.1.1.1"
+     * Output: "1[.]1[.]1[.]1"
+     * Example 2:
+     *
+     * Input: address = "255.100.50.0"
+     * Output: "255[.]100[.]50[.]0"
+     * 
+ * + * @param address + * @return + */ + public String defangIPaddr(String address) { + if (address == null || address.length() < 1) { + return address; + } + + StringBuilder builder = new StringBuilder(address.length() * 2); + + for (int i = 0; i < address.length(); i++) { + char ch = address.charAt(i); + if (Character.isDigit(ch)) { + builder.append(ch); + } else if (ch == '.') { + builder.append("[.]"); + } else { + throw new IllegalArgumentException(address + " contains invalid char"); + } + } + + + return builder.toString(); + } +} diff --git a/leetcode.iml b/leetcode.iml new file mode 100644 index 0000000..24c525d --- /dev/null +++ b/leetcode.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git "a/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Main.class" "b/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Main.class" deleted file mode 100644 index 7297ec1..0000000 Binary files "a/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Solution$Node.class" "b/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Solution$Node.class" deleted file mode 100644 index 5a6d57e..0000000 Binary files "a/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Solution$Node.class" and /dev/null differ diff --git "a/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Solution.class" "b/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Solution.class" deleted file mode 100644 index ffb7ec3..0000000 Binary files "a/out/production/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/Main.class" "b/out/production/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/Main.class" deleted file mode 100644 index 273267b..0000000 Binary files "a/out/production/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/Solution.class" "b/out/production/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/Solution.class" deleted file mode 100644 index 9ec8c08..0000000 Binary files "a/out/production/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220005\343\200\221\343\200\220LongestValidParentheses\343\200\221/Main.class" "b/out/production/\343\200\220005\343\200\221\343\200\220LongestValidParentheses\343\200\221/Main.class" deleted file mode 100644 index b69cb49..0000000 Binary files "a/out/production/\343\200\220005\343\200\221\343\200\220LongestValidParentheses\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220005\343\200\221\343\200\220LongestValidParentheses\343\200\221/Solution.class" "b/out/production/\343\200\220005\343\200\221\343\200\220LongestValidParentheses\343\200\221/Solution.class" deleted file mode 100644 index 8c0a665..0000000 Binary files "a/out/production/\343\200\220005\343\200\221\343\200\220LongestValidParentheses\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/Main.class" "b/out/production/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/Main.class" deleted file mode 100644 index 6e32f13..0000000 Binary files "a/out/production/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/Solution.class" "b/out/production/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/Solution.class" deleted file mode 100644 index 765ec12..0000000 Binary files "a/out/production/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220013\343\200\221\343\200\2203Sum\343\200\221/Main.class" "b/out/production/\343\200\220013\343\200\221\343\200\2203Sum\343\200\221/Main.class" deleted file mode 100644 index 2151554..0000000 Binary files "a/out/production/\343\200\220013\343\200\221\343\200\2203Sum\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220013\343\200\221\343\200\2203Sum\343\200\221/Solution.class" "b/out/production/\343\200\220013\343\200\221\343\200\2203Sum\343\200\221/Solution.class" deleted file mode 100644 index bd9bfe8..0000000 Binary files "a/out/production/\343\200\220013\343\200\221\343\200\2203Sum\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/Main.class" "b/out/production/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/Main.class" deleted file mode 100644 index 9ed186c..0000000 Binary files "a/out/production/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/Solution.class" "b/out/production/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/Solution.class" deleted file mode 100644 index 47a92fb..0000000 Binary files "a/out/production/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/Main.class" "b/out/production/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/Main.class" deleted file mode 100644 index d83a00e..0000000 Binary files "a/out/production/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/Solution.class" "b/out/production/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/Solution.class" deleted file mode 100644 index 902bade..0000000 Binary files "a/out/production/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/ListNode.class" "b/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/ListNode.class" deleted file mode 100644 index 8fb9287..0000000 Binary files "a/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/ListNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/Main.class" "b/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/Main.class" deleted file mode 100644 index 78a7b95..0000000 Binary files "a/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/Solution.class" "b/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/Solution.class" deleted file mode 100644 index 7262aec..0000000 Binary files "a/out/production/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/Main.class" "b/out/production/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/Main.class" deleted file mode 100644 index 9552b18..0000000 Binary files "a/out/production/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/Solution.class" "b/out/production/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/Solution.class" deleted file mode 100644 index a65cee5..0000000 Binary files "a/out/production/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/Main.class" "b/out/production/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/Main.class" deleted file mode 100644 index 4c8c1e5..0000000 Binary files "a/out/production/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/Solution.class" "b/out/production/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/Solution.class" deleted file mode 100644 index 3dc1153..0000000 Binary files "a/out/production/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/Main.class" "b/out/production/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/Main.class" deleted file mode 100644 index 0d76e63..0000000 Binary files "a/out/production/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/Solution.class" "b/out/production/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/Solution.class" deleted file mode 100644 index 08433ae..0000000 Binary files "a/out/production/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/Main.class" "b/out/production/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/Main.class" deleted file mode 100644 index 2142fe4..0000000 Binary files "a/out/production/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/Solution.class" "b/out/production/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/Solution.class" deleted file mode 100644 index b1ec3da..0000000 Binary files "a/out/production/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/Main.class" "b/out/production/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/Main.class" deleted file mode 100644 index b92e07d..0000000 Binary files "a/out/production/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/Solution.class" "b/out/production/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/Solution.class" deleted file mode 100644 index 53d6fb9..0000000 Binary files "a/out/production/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/Main.class" "b/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/Main.class" deleted file mode 100644 index 637d7b4..0000000 Binary files "a/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/Solution.class" "b/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/Solution.class" deleted file mode 100644 index 2ba8bdb..0000000 Binary files "a/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/TreeNode.class" "b/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/TreeNode.class" deleted file mode 100644 index 7c3216c..0000000 Binary files "a/out/production/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/TreeNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/Main.class" "b/out/production/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/Main.class" deleted file mode 100644 index 356fece..0000000 Binary files "a/out/production/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/Solution.class" "b/out/production/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/Solution.class" deleted file mode 100644 index 8c40ac8..0000000 Binary files "a/out/production/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/Main.class" "b/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/Main.class" deleted file mode 100644 index 5ec4a23..0000000 Binary files "a/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/Solution.class" "b/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/Solution.class" deleted file mode 100644 index ea40b63..0000000 Binary files "a/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/TreeNode.class" "b/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/TreeNode.class" deleted file mode 100644 index 7c3216c..0000000 Binary files "a/out/production/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/TreeNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/Main.class" "b/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/Main.class" deleted file mode 100644 index 4a80a98..0000000 Binary files "a/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/Solution.class" "b/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/Solution.class" deleted file mode 100644 index 46ff8be..0000000 Binary files "a/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/TreeNode.class" "b/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/TreeNode.class" deleted file mode 100644 index 7c3216c..0000000 Binary files "a/out/production/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/TreeNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/ListNode.class" "b/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/ListNode.class" deleted file mode 100644 index 8fb9287..0000000 Binary files "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/ListNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/Main.class" "b/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/Main.class" deleted file mode 100644 index 25c7044..0000000 Binary files "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/Solution.class" "b/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/Solution.class" deleted file mode 100644 index 71a9ed4..0000000 Binary files "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/TreeNode.class" "b/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/TreeNode.class" deleted file mode 100644 index 7c3216c..0000000 Binary files "a/out/production/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/TreeNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/Main.class" "b/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/Main.class" deleted file mode 100644 index 515657a..0000000 Binary files "a/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/Solution.class" "b/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/Solution.class" deleted file mode 100644 index 5c03eb9..0000000 Binary files "a/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/TreeLinkNode.class" "b/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/TreeLinkNode.class" deleted file mode 100644 index 2a3ad57..0000000 Binary files "a/out/production/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/TreeLinkNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/Main.class" "b/out/production/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/Main.class" deleted file mode 100644 index 07ca3df..0000000 Binary files "a/out/production/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/Solution.class" "b/out/production/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/Solution.class" deleted file mode 100644 index 9f4e9e3..0000000 Binary files "a/out/production/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Main.class" "b/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Main.class" deleted file mode 100644 index 8f33c4d..0000000 Binary files "a/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Solution$Coordinate.class" "b/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Solution$Coordinate.class" deleted file mode 100644 index 672f58a..0000000 Binary files "a/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Solution$Coordinate.class" and /dev/null differ diff --git "a/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Solution.class" "b/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Solution.class" deleted file mode 100644 index 712759b..0000000 Binary files "a/out/production/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/Main.class" "b/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/Main.class" deleted file mode 100644 index 7957a8c..0000000 Binary files "a/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/RandomListNode.class" "b/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/RandomListNode.class" deleted file mode 100644 index 6618a10..0000000 Binary files "a/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/RandomListNode.class" and /dev/null differ diff --git "a/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/Solution.class" "b/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/Solution.class" deleted file mode 100644 index 374f06f..0000000 Binary files "a/out/production/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/Main.class" "b/out/production/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/Main.class" deleted file mode 100644 index fc8c37f..0000000 Binary files "a/out/production/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/Solution.class" "b/out/production/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/Solution.class" deleted file mode 100644 index e1ff981..0000000 Binary files "a/out/production/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/Main.class" "b/out/production/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/Main.class" deleted file mode 100644 index def9594..0000000 Binary files "a/out/production/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/Solution.class" "b/out/production/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/Solution.class" deleted file mode 100644 index 273690e..0000000 Binary files "a/out/production/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/Main.class" "b/out/production/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/Main.class" deleted file mode 100644 index 762d19d..0000000 Binary files "a/out/production/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/Solution.class" "b/out/production/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/Solution.class" deleted file mode 100644 index 9e3985a..0000000 Binary files "a/out/production/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220152\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/Main.class" "b/out/production/\343\200\220152\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/Main.class" deleted file mode 100644 index 6b254cf..0000000 Binary files "a/out/production/\343\200\220152\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220152\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/Solution.class" "b/out/production/\343\200\220152\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/Solution.class" deleted file mode 100644 index 1ea61e8..0000000 Binary files "a/out/production/\343\200\220152\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/Main.class" "b/out/production/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/Main.class" deleted file mode 100644 index 9a9db62..0000000 Binary files "a/out/production/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/Solution.class" "b/out/production/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/Solution.class" deleted file mode 100644 index 35187e6..0000000 Binary files "a/out/production/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/Main.class" "b/out/production/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/Main.class" deleted file mode 100644 index aed0d7a..0000000 Binary files "a/out/production/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/Solution.class" "b/out/production/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/Solution.class" deleted file mode 100644 index d45b962..0000000 Binary files "a/out/production/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/Main.class" "b/out/production/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/Main.class" deleted file mode 100644 index 06c370f..0000000 Binary files "a/out/production/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/Solution.class" "b/out/production/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/Solution.class" deleted file mode 100644 index 8a3606a..0000000 Binary files "a/out/production/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/Main.class" "b/out/production/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/Main.class" deleted file mode 100644 index 35cfcfc..0000000 Binary files "a/out/production/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/Solution.class" "b/out/production/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/Solution.class" deleted file mode 100644 index 48f5a57..0000000 Binary files "a/out/production/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/Solution.class" "b/out/production/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/Solution.class" deleted file mode 100644 index 0c65e79..0000000 Binary files "a/out/production/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/Main.class" "b/out/production/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/Main.class" deleted file mode 100644 index 48501d5..0000000 Binary files "a/out/production/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/Solution.class" "b/out/production/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/Solution.class" deleted file mode 100644 index e66f2f9..0000000 Binary files "a/out/production/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/Main.class" "b/out/production/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/Main.class" deleted file mode 100644 index b031920..0000000 Binary files "a/out/production/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/Solution.class" "b/out/production/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/Solution.class" deleted file mode 100644 index 12ad096..0000000 Binary files "a/out/production/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/Main.class" "b/out/production/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/Main.class" deleted file mode 100644 index 9dfa3ed..0000000 Binary files "a/out/production/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/Solution.class" "b/out/production/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/Solution.class" deleted file mode 100644 index 51fa24b..0000000 Binary files "a/out/production/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/Solution.class" and /dev/null differ diff --git "a/out/production/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/Main.class" "b/out/production/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/Main.class" deleted file mode 100644 index df917bf..0000000 Binary files "a/out/production/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/Main.class" and /dev/null differ diff --git "a/out/production/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/Solution.class" "b/out/production/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/Solution.class" deleted file mode 100644 index 1cdde86..0000000 Binary files "a/out/production/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/Solution.class" and /dev/null differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..f4d3123 --- /dev/null +++ b/pom.xml @@ -0,0 +1,12 @@ + + + 4.0.0 + + wjc.leetcode + leetcode + 1.0-SNAPSHOT + + + \ No newline at end of file diff --git "a/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/src/Main.java" "b/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/src/Main.java" deleted file mode 100644 index 6c41f33..0000000 --- "a/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/src/Main.java" +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Author: - * Date: 2015-06-18 - * Time: 09:17 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - int[] result = new Solution().twoSum(new int[]{0, 4, 3, 0}, 0); - - System.out.println("[" + result[0] + " ," + result[1] + "]"); - } -} diff --git "a/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/src/Solution.java" "b/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/src/Solution.java" deleted file mode 100644 index 5fc48cd..0000000 --- "a/\343\200\220001\343\200\221\343\200\220TwoSum\343\200\221/src/Solution.java" +++ /dev/null @@ -1,92 +0,0 @@ -import java.util.Arrays; - -/** - * Author: - * Date: 2015-06-17 - * Time: 20:27 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - private static class Node implements Comparable { - int val; - int idx; - - public Node() { - } - - public Node(int val, int idx) { - this.val = val; - this.idx = idx; - } - - @Override - public int compareTo(Node o) { - if (o == null) { - return -1; - } - return this.val - o.val; - } - } - - - /** - *
-     * Given an array of integers, find two numbers such that they add up to a specific target number.
-     * The function twoSum should return indices of the two numbers such that they add up to the target,
-     * where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
-     * are not zero-based.
-     * You may assume that each input would have exactly one solution.
-     *
-     * Input: numbers={2, 7, 11, 15}, target=9
-     * Output: index1=1, index2=2
-     *
-     * Ŀ
-     * һ飬ҳӵָĿ֡
-     * ҪtwoSumҪܹӵĿֵindex1ҪСindex2
-     * עһ㣬㷵صĽindex1index2ǻ0ʼġԼÿһ϶ֻһ
-     *
-     * ˼·
-     * һ飬Ըʹָ룬ʼʱֱָˣ±ӦֵǷ
-     * ĿֵھʹӸҳ¼±꣬÷ؽءھұߵ±ƣ
-     * һƥ䣬Сھߵ±ƶһƥ䣬ֱеݶ
-     * 
- * - * @param nums - * @param target - * @return - */ - - public int[] twoSum(int[] nums, int target) { - int[] result = {0, 0}; - - Node[] tmp = new Node[nums.length]; - for (int i = 0; i < nums.length; i++) { - tmp[i] = new Node(nums[i], i); - } - - Arrays.sort(tmp); - - int lo = 0; - int hi = nums.length - 1; - - - while (lo < hi) { - if (tmp[lo].val + tmp[hi].val == target) { - - if (tmp[lo].idx > tmp[hi].idx) { - result[0] = tmp[hi].idx + 1; - result[1] = tmp[lo].idx + 1; - } else { - result[0] = tmp[lo].idx + 1; - result[1] = tmp[hi].idx + 1; - } - break; - } else if (tmp[lo].val + tmp[hi].val > target) { - hi--; - } else { - lo++; - } - } - return result; - } -} diff --git "a/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/src/Solution.java" "b/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/src/Solution.java" deleted file mode 100644 index 1bb9d80..0000000 --- "a/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/src/Solution.java" +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:04 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * You are given two linked lists representing two non-negative numbers.
-     * 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.
-     * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
-     * Output: 7 -> 0 -> 8
-     *
-     * Ŀ
-     * ǸÿһڵһλǷ洢ģ
-     * һʾλһʾλӺͣʽء
-     *
-     * ˼·
-     * ӵһʼӣٳ10̣ΪһλӵĽλ
-     * ͬʱ¼ΪλĽһֱֱеĽ㶼ꡣ
-     * 
- * - * @param l1 һ - * @param l2 ڶ - * @return - */ - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - - if (l1 == null) { - return l2; - } - - if (l2 == null) { - return l1; - } - - ListNode p1 = l1; - ListNode p2 = l2; - ListNode root = new ListNode(0); // ͷ - ListNode r = root; - root.next = l1; - - int carry = 0; // ʼλ - int sum; - while (p1 != null && p2 != null) { - sum = p1.val + p2.val + carry; - p1.val = sum % 10; // λĽ - carry = sum / 10; // νλ - - r.next = p1; - r = p1; // ָһӵĽ - p1 = p1.next; - p2 = p2.next; - - } - - if (p1 == null) { - r.next = p2; - } else { - r.next = p1; - } - - // һӻнλ - if (carry == 1) { - // ʼʱr.nextǵһҪӵĽ - while (r.next != null) { - sum = r.next.val + carry; - r.next.val = sum % 10; - carry = sum / 10; - r = r.next; - } - - // ˻нλҪһµĽ - if (carry == 1) { - r.next = new ListNode(1); - } - } - - return root.next; - } -} diff --git "a/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221.iml" "b/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221.iml" deleted file mode 100644 index b769534..0000000 --- "a/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221/\343\200\220002\343\200\221\343\200\220AddTwoNumbers\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220003\343\200\221\343\200\220LongestSubstringWithoutRepeatingCharacters\343\200\221/src/Solution.java" "b/\343\200\220003\343\200\221\343\200\220LongestSubstringWithoutRepeatingCharacters\343\200\221/src/Solution.java" deleted file mode 100644 index be83bb1..0000000 --- "a/\343\200\220003\343\200\221\343\200\220LongestSubstringWithoutRepeatingCharacters\343\200\221/src/Solution.java" +++ /dev/null @@ -1,91 +0,0 @@ -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Author: - * Date: 2015-06-17 - * Time: 20:46 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a string, find the length of the longest substring without repeating characters.
-     * For example, the longest substring without repeating letters for "abcabcbb" is "abc",
-     * which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
-     *
-     * Ŀ⣺
-     * һַַеظӴ
-     *
-     * ˼·
-     * start¼Ŀʼλ
-     * ַǰַӿʼλstartʼѾֹʱӴʼλ+1mapеhashֵΪǰλá
-     * 
- * - * @param s - * @return - */ - // ԴеUTF-8ַ - public int lengthOfLongestSubstring(String s) { - // ַ벻Ϸ - if (s == null) { - return 0; - } - - // ǰĿʼλ - int start = 0; - // - int result = 0; - // ʱǣ¼һηʵַλ - Map map = new HashMap<>(s.length()); - - for (int i = 0; i < s.length(); i++) { - char ch = s.charAt(i); - // ַѾֹ(ڱǿλ)±start - if (map.containsKey(ch) && map.get(ch) >= start) { - start = map.get(ch) + 1; - } - // ûгֹķظӴij - else { - result = Math.max(result, i - start + 1); - } - - // ·ʼ¼ - map.put(ch, i); - } - return result; - } - - // ֻASCIIַ - public int lengthOfLongestSubstring2(String s) { - // ַ벻Ϸ - if (s == null) { - return 0; - } - - // ַǷֹҼ¼ǵһηʵԪصλ - int[] appear = new int[256]; - // ʼΪ-1 - Arrays.fill(appear, -1); - // ǰĿʼλ - int start = 0; - // - int result = 0; - - for (int i = 0; i < s.length(); i++) { - // ַѾֹ(ڱǿλ)±start - if (appear[s.charAt(i)] >= start) { - start = i + 1; - } - // ûгֹķظӴij - else { - result = Math.max(result, i - start + 1); - } - // ǵiַѾʹǵiλã - appear[s.charAt(i)] = i; - } - - return result; - } -} diff --git "a/\343\200\220004\343\200\221\343\200\220MedianofTwoSortedArrays\343\200\221/src/Solution.java" "b/\343\200\220004\343\200\221\343\200\220MedianofTwoSortedArrays\343\200\221/src/Solution.java" deleted file mode 100644 index 2e8b9b2..0000000 --- "a/\343\200\220004\343\200\221\343\200\220MedianofTwoSortedArrays\343\200\221/src/Solution.java" +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Author: - * Date: 2015-06-17 - * Time: 20:54 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * 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)).
-     *
-     * Ŀ⣺
-     * 飬λʱ临ӶΪO(log(m+n))
-     *
-     * ˼·
-     * ݹ
-     * 
- * - * @param nums1 - * @param nums2 - * @return - */ - public double findMedianSortedArrays(int[] nums1, int[] nums2) { - - if (nums1 == null) { - nums1 = new int[0]; - } - - if (nums2 == null) { - nums2 = new int[0]; - } - - int len1 = nums1.length; - int len2 = nums2.length; - - if (len1 < len2) { - // ȷһȵڶ鳤ȴ - return findMedianSortedArrays(nums2, nums1); - } - - // С鳤Ϊ0ͷǰһλ - if (len2 == 0) { - return (nums1[(len1 - 1) / 2] + nums1[len1 / 2]) / 2.0; - } - - - int lo = 0; - int hi = len2 * 2; - int mid1; - int mid2; - double l1; - double l2; - double r1; - double r2; - - while (lo <= hi) { - mid2 = (lo + hi) / 2; - mid1 = len1 + len2 - mid2; - - l1 = (mid1 == 0) ? Integer.MIN_VALUE : nums1[(mid1 - 1) / 2]; - l2 = (mid2 == 0) ? Integer.MIN_VALUE : nums2[(mid2 - 1) / 2]; - - r1 = (mid1 == len1 * 2) ? Integer.MAX_VALUE : nums1[mid1 / 2]; - r2 = (mid2 == len2 * 2) ? Integer.MAX_VALUE : nums2[mid2 / 2]; - - if (l1 > r2) { - lo = mid2 + 1; - } else if (l2 > r1) { - hi = mid2 - 1; - } else { - return (Math.max(l1, l2) + Math.min(r1, r2)) / 2; - } - } - - return -1; - } -} diff --git "a/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/src/Solution.java" "b/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/src/Solution.java" deleted file mode 100644 index 7034ef0..0000000 --- "a/\343\200\220005\343\200\221\343\200\220LongestPalindromicSubstringTotal \343\200\221/src/Solution.java" +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Author: - * Date: 2015-06-17 - * Time: 21:24 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a string S, find the longest palindromic substring in S.
-     * You may assume that the maximum length of S is 1000, and there
-     * exists one unique longest palindromic substring.
-     *
-     * Ŀ⣺
-     * һַSҳĻӴԼַ󳤶1000
-     * ҴΨһӴ
-     *
-     * ˼·
-     * ̬滮
-     * dp[ i ][ j ]ֵΪtrueʾַs± i  j ַɵӴǻĴôƳ
-     * dp[ i ][ j ] = dp[ i + 1][ j - 1] && s[ i ] == s[ j ]
-     * һҪi+1, j -1п i + 1 = j -1, i +1 = (j - 1) -1
-     * Ҫ׼ϵĹʽ
-     *
-     * a. i + 1 = j -1ijΪ1ʱdp[ i ][ i ] = true;
-     * b. i +1 = (j - 1) -1ijΪ2ʱdp[ i ][ i + 1] = s[ i ] == s[ i + 1]
-     *
-     * ϷͿдˡҪעǶ̬滮ҪO(n^2)Ŀռ䡣
-     * 
- * - * @param s - * @return - */ - public String longestPalindrome(String s) { - - if (s == null || s.length() < 2) { - return s; - } - - int maxLength = 0; - String longest = null; - - int length = s.length(); - boolean[][] table = new boolean[length][length]; - - // ַǻ - for (int i = 0; i < length; i++) { - table[i][i] = true; - longest = s.substring(i, i + 1); - maxLength = 1; - } - - // жַǷǻ - for (int i = 0; i < length - 1; i++) { - if (s.charAt(i) == s.charAt(i + 1)) { - table[i][i + 1] = true; - longest = s.substring(i, i + 2); - maxLength = 2; - } - } - - - // 󳤶ȴ2ӴǷǻĴ - for (int len = 3; len <= length; len++) { - for (int i = 0, j; (j = i + len - 1) <= length - 1; i++) { - if (s.charAt(i) == s.charAt(j)) { - table[i][j] = table[i + 1][j - 1]; - if (table[i][j] && maxLength < len) { - longest = s.substring(i, j + 1); - maxLength = len; - } - } else { - table[i][j] = false; - } - } - } - - return longest; - } - - -} diff --git "a/\343\200\220006\343\200\221\343\200\220ZigZagConversion\343\200\221/src/Solution.java" "b/\343\200\220006\343\200\221\343\200\220ZigZagConversion\343\200\221/src/Solution.java" deleted file mode 100644 index 3de4a90..0000000 --- "a/\343\200\220006\343\200\221\343\200\220ZigZagConversion\343\200\221/src/Solution.java" +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:08 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     *     ԭ
-     * 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
-     * APLSIIG
-     * Y I R
-     * And then read line by line: PAHNAPLSIIGYIR
-     * Write the code that will take a string and make this conversion given a number of rows:
-     * string convert(string text, int nRows);
-     * convert(PAYPALISHIRING,3) should return PAHNAPLSIIGYIR.
-     * Ŀ
-     * һַַָZ
-     *
-     * ˼·
-     * ַһһά飬ټÿַһάеλã
-     * ٶһάеַнղؽ
-     * 
- * - * @param s - * @param nRows - * @return - */ - public String convert(String s, int nRows) { - - if (s == null || s.length() <= nRows || nRows == 1) { - return s; - } - - int index = s.length(); - int rowLength = 0; // еijȣַ - - int slash = nRows - 2; // һб߳ȥβռõ - - while (index > 0) { - // εһ - index -= nRows; - rowLength++; - - // бŵ - for (int i = 0; i < slash && index > 0; i++) { - rowLength++; - index--; - } - } - - char[] result = new char[nRows * rowLength]; // 飬һڱ滻з - for (int i = 0; i < result.length; i++) { // ʼΪո - result[i] = ' '; - } - - int curColumn = 0; // ǰ - index = 0; - while (index < s.length()) { - // - for (int i = 0; i < nRows && index < s.length(); i++) { - result[rowLength * i + curColumn] = s.charAt(index); - index++; - } - curColumn++; - // б - for (int i = nRows - 2; i > 0 && index < s.length(); i--) { - result[rowLength * i + curColumn] = s.charAt(index); - curColumn++; - index++; - } - } - - // ַнղ - index = 0; - while (index < s.length() && result[index] != ' ') { // ҵһǿոַλ - index++; - } - int next = index + 1; - while (index < s.length()) { - while (next < result.length && result[next] == ' ') { // ҲǿոԪ - next++; - } - result[index] = result[next]; - index++; - next++; - } - return new String(result, 0, index); - } -} diff --git "a/\343\200\220008\343\200\221\343\200\220StringToInteger (atoi)\343\200\221/src/Solution.java" "b/\343\200\220008\343\200\221\343\200\220StringToInteger (atoi)\343\200\221/src/Solution.java" deleted file mode 100644 index 6010b26..0000000 --- "a/\343\200\220008\343\200\221\343\200\220StringToInteger (atoi)\343\200\221/src/Solution.java" +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:13 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * 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.
-     *
-     * Ŀ
-     * ʵһatoiַת
-     * Ҫ㣺е
-     *
-     * ˼·
-     * ǰַ+-ûУֲ֣ܱʾС
-     * ͷضӦССֵ
-     * 
- * - * @param str - * @return - */ - public int atoi(String str) { - - if (str == null || str.length() == 0) { -// throw new NumberFormatException("Invalid input string: " + str); - return 0; - } - - // ַԿոʼ - int start = 0; //ӿʼҵһǿո - boolean positive = true; // ǷΪĬΪtrue - - if (str.charAt(start) == ' ') { - while (str.charAt(start) == ' ') { - start++; - if (start >= str.length()) { // ȫǿո -// throw new NumberFormatException("Invalid input string: " + str); - return 0; - } - } - } - - if (str.charAt(start) == '-') { // һǿհַ- - positive = false; - start++; - } else if (str.charAt(start) == '+') {// һǿհַ+ - start++; - } else if (str.charAt(start) >= '0' && str.charAt(start) <= '9') { // һǿհַ - return cal(str, start, true); - } else { // ׳쳣 -// throw new NumberFormatException("Invalid input string: " + str); - return 0; - } - - - if (start >= str.length()) { // һǿհַ+-Ҳһַ -// throw new NumberFormatException("Invalid input string: " + str); - return 0; - } - - if (str.charAt(start) > '9' || str.charAt(start) < '0') { // +-ӵIJ -// throw new NumberFormatException("Invalid input string: " + str); - return 0; - } else { - return cal(str, start, positive); - } - } - - private int cal(String str, int start, boolean positive) { - - long result = 0; - while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') { - result = result * 10 + (str.charAt(start) - '0'); - - if (positive) { // - if (result > Integer.MAX_VALUE) { -// throw new NumberFormatException("Invalid input string: " + str); - return Integer.MAX_VALUE; - } - - } else { - if (-result < Integer.MIN_VALUE) { -// throw new NumberFormatException("Invalid input string: " + str); - return Integer.MIN_VALUE; - } - } - - start++; - } - - if (positive) { - return (int) result; - } else { - return (int) -result; - } - } -} diff --git "a/\343\200\220009\343\200\221\343\200\220PalindromeNumber\343\200\221/src/Solution.java" "b/\343\200\220009\343\200\221\343\200\220PalindromeNumber\343\200\221/src/Solution.java" deleted file mode 100644 index 318a64d..0000000 --- "a/\343\200\220009\343\200\221\343\200\220PalindromeNumber\343\200\221/src/Solution.java" +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:52 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Determine whether an integer is a palindrome. Do this without extra space.
-     *
-     * Ŀ
-     * жһǷǻطҪʹöĿռ䡣
-     *
-     * ˼·
-     * Ϊ˲ʹöĿռ䣬οĽЩⷨisPalindromeûʹö
-     * ȴʹ˷ãһĵĿռ ûдﵽĿҪǼٵʵ֣
-     * ԱȻһĿռʵ֡
-     *  ȣǻ֣ζֽת123321任˵ǻ֡
-     * 
- * - * @param x - * @return - */ - public boolean isPalindrome(int x) { - - // ǻط - if (x < 0) { - return false; - } - - // תֵΪ˲ʹlong - long reverse = 0; - int tmp = x; - - // תֵ - while (tmp != 0) { - reverse = reverse * 10 + tmp % 10; - tmp /= 10; - } - - // жǷǻ - return x == reverse; - } -} diff --git "a/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/src/Solution.java" "b/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/src/Solution.java" deleted file mode 100644 index b462e2f..0000000 --- "a/\343\200\220010\343\200\221\343\200\220RegularExpressionMatching\343\200\221/src/Solution.java" +++ /dev/null @@ -1,120 +0,0 @@ -import java.util.Arrays; - -/** - * Author: - * Date: 2015-06-24 - * Time: 20:42 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * 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
-     *
-     * Ŀ⣺
-     * ʵһʽƥ㷨.ƥһַ*ƥ0߶ǰַ
-     *
-     * Կ˼·
-     * ע
-     *
-     * 
- * - * @param s - * @param p - * @return - */ - public boolean isMatch(String s, String p) { - boolean[] match = new boolean[s.length() + 1]; - Arrays.fill(match, false); - match[s.length()] = true; - for (int i = p.length() - 1; i >= 0; i--) { - if (p.charAt(i) == '*') { - for (int j = s.length() - 1; j >= 0; j--) { - match[j] = match[j] || match[j + 1] - && (p.charAt(i - 1) == '.' || s.charAt(j) == p.charAt(i - 1)); - } - i--; - } else { - for (int j = 0; j < s.length(); j++) { - match[j] = match[j + 1] - && (p.charAt(i) == '.' || p.charAt(i) == s.charAt(j)); - } - - match[s.length()] = false; - } - } - return match[0]; - } - - // ĴʱȽϳ - public boolean isMatch2(String s, String p) { - // 붼Ϊnull - if (s == null && p == null) { - return true; - } - // һΪnull - else if (s == null || p == null) { - return false; - } - - return isMatch(s, 0, p, 0); - } - - /** - * ʽƥ - * - * @param s ƥ䴮 - * @param sIdx ǰƥλ - * @param p ģʽ - * @param pIdx ģʽƥλ - * @return ƥ - */ - public boolean isMatch(String s, int sIdx, String p, int pIdx) { - // ͬʱԵĩβ - if (s.length() == sIdx && p.length() == pIdx) { - return true; - } - // ƥ䴮ûеĩβģʽѾĩβ - else if (s.length() != sIdx && p.length() == pIdx) { - return false; - } - // - else { - // ǰƥһַ* - if (pIdx < p.length() - 1 && p.charAt(pIdx + 1) == '*') { - // ƥ䴮δҵǰַƥ䣨ַȻ.ţ - if (sIdx < s.length() && (s.charAt(sIdx) == p.charAt(pIdx) || p.charAt(pIdx) == '.')) { - return isMatch(s, sIdx + 1, p, pIdx + 2) // ƥ䴮ǰƶһַֻƥһΣ - || isMatch(s, sIdx + 1, p, pIdx) // ƥ䴮ǰƶһַһƥͬģģʽ - || isMatch(s, sIdx, p, pIdx + 2); // ƥģʽ - } else { - // * - return isMatch(s, sIdx, p, pIdx + 2); - } - } - - // ƥһַ - if (sIdx < s.length() && (s.charAt(sIdx) == p.charAt(pIdx) || p.charAt(pIdx) == '.')) { - return isMatch(s, sIdx + 1, p, pIdx + 1); - } - } - - return false; - } - -} diff --git "a/\343\200\220011\343\200\221\343\200\220ContainerWithMost Water\343\200\221/src/Solution.java" "b/\343\200\220011\343\200\221\343\200\220ContainerWithMost Water\343\200\221/src/Solution.java" deleted file mode 100644 index 7a40cf8..0000000 --- "a/\343\200\220011\343\200\221\343\200\220ContainerWithMost Water\343\200\221/src/Solution.java" +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Author: - * Date: 2015-06-30 - * Time: 07:25 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * 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.
-     *
-     * Ŀ⣺
-     * ȻԼXṹɵˮ
-     *
-     * ˼·
-     * ʹ̰㷨
-     *      1.ȼҵȡݻΪ i, j (ٶi aj) 
-     *          ô   ak > aj min(ai, aj, ak) =min(ai, aj) 
-     *          i, kɵݻC' = min(ai, aj) * (k - i) > C
-     *          CֵìܣԵ֤jĺ߲бߵߣ
-     *
-     *          :ͬiҲбߵߣ˵ʲôأ
-     *          Ŀǰõĺѡ Ϊ x, yߣx< y)ôܹõ
-     *          ݻµ߱Ȼ[x, y]ڲ ax' >= ax , ay' >= ay;
-     *
-     *      3.Ǵͷм俿£ͬʱºѡֵʱȴ
-     *      x, yнСı߿ʼ
-     * 
- * - * @param height - * @return - */ - public int maxArea(int[] height) { - - // У - if (height == null || height.length < 2) { - return 0; - } - - - // ¼Ľ - int result = 0; - - // ߵ - int left = 0; - // ұߵ - int right = height.length - 1; - - while (left < right) { - // 㵱ǰֵ - result = Math.max(result, Math.min(height[left], height[right]) * (right - left)); - // ұ߸ - if (height[left] < height[right]) { - int k = left; - // [left, right - 1]Уңҵһ߶ȱheight[left]ߵλ - while (k < right && height[k] <= height[left]) { - k++; - } - - // [left, right - 1]У¼һԭheight[left]ߵλ - left = k; - } - // ߵ߸ - else { - int k = right; - // [left + 1, right]Уңҵһ߶ȱheight[right]ߵλ - while (k > left && height[k] <= height[right]) { - k--; - } - - // [left, right - 1]У¼һԭheight[right]ߵλ - right = k; - } - } - - return result; - } -} diff --git "a/\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221/\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221.iml" "b/\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221/\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221/\343\200\220012\343\200\221\343\200\220IntegerToRoman\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/src/Main.java" "b/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/src/Main.java" deleted file mode 100644 index 78bbc1a..0000000 --- "a/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/src/Main.java" +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Author: 王俊超 - * Date: 2015-03-01 - * Time: 16:35 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - - System.out.println(solution.romanToInt("I")); - System.out.println(solution.romanToInt("II")); - System.out.println(solution.romanToInt("III")); - System.out.println(solution.romanToInt("IV")); - System.out.println(solution.romanToInt("V")); - System.out.println(solution.romanToInt("VI")); - - System.out.println(solution.romanToInt("XCVIII")); - System.out.println(solution.romanToInt("XCIX")); - - System.out.println(solution.romanToInt("CM")); - System.out.println(solution.romanToInt("CMXCIX")); - - System.out.println(solution.romanToInt("MDCLXVI")); - System.out.println(solution.romanToInt("MCMLXXVI")); - System.out.println(solution.romanToInt("MMMCMXCIX")); - } -} diff --git "a/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/src/Solution.java" "b/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/src/Solution.java" deleted file mode 100644 index c6fca2b..0000000 --- "a/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/src/Solution.java" +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Author: 王俊超 - * Date: 2015-03-01 - * Time: 16:09 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * 原题
-     * Given a roman numeral, convert it to an integer.
-     * Input is guaranteed to be within the range from 1 to 3999.
-     *
-     * 题目大意
-     * 给定一个罗马数字,将其转换成对应的整数。
-     * 输入的数字在1-3999之间。
-     *
-     * 解题思路
-     * 根据罗马数字与整数数字对应关系进行加法操作,如果前一个数字比后一个大就相减,否则进行相加。
-     * 
- * - * @param s - * @return - */ - public int romanToInt(String s) { - - int result = 0; - int prev = 0; // 记录前一个数字的值 - - for (int i = s.length() - 1; i > -1; i--) { - switch (s.charAt(i)) { - case 'I': // 1 - if (1 < prev) { - result -= 1; - } else { - result += 1; - - } - prev = 1; - break; - - case 'V': // 5 - - if (5 < prev) { - result -= 5; - } else { - result += 5; - } - - prev = 5; - - break; - case 'X': // 10 - if (10 < prev) { - result -= 10; - } else { - result += 10; - } - - prev = 10; - break; - case 'L': // 50 - if (50 < prev) { - result -= 50; - } else { - result += 50; - } - - prev = 50; - break; - case 'C': // 100 - if (100 < prev) { - result -= 100; - } else { - result += 100; - } - - prev = 100; - break; - case 'D': // 500 - if (500 < prev) { - result -= 500; - } else { - result += 500; - } - - prev = 500; - break; - case 'M': // 1000 - result += 1000; - prev = 1000; - break; - } - } - - return result; - } -} diff --git "a/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221.iml" "b/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221/\343\200\220013\343\200\221\343\200\220RomarToInteger\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221/src/Solution.java" "b/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221/src/Solution.java" deleted file mode 100644 index e5f1606..0000000 --- "a/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221/src/Solution.java" +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:19 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Write a function to find the longest common prefix string amongst an array of strings.
-     *
-     * Ŀ
-     * дһҳһִеĹǰ׺
-     *
-     * ˼·
-     * һҳСַȻַַҳ̵ǰ׺
-     * 
- * - * @param strs - * @return - */ - public String longestCommonPrefix(String[] strs) { - if (strs == null) { - return null; - } - - if (strs.length == 0) { - return ""; - } - - int min = Integer.MAX_VALUE; // ¼̵ַij - - // Ҷַij - for (String str : strs) { - - if (str == null) { - return null; - } - - if (min > str.length()) { - min = str.length(); - } - } - - int i; // ¼ǰ׺ַ - boolean flag; - for (i = 0; i < min; i++) { - flag = true; - for (int j = 1; j < strs.length; j++) { - if (strs[0].charAt(i) != strs[j].charAt(i)) { - flag = false; - break; - } - } - - if (!flag) { - break; - } - } - - return strs[0].substring(0, i); - } -} diff --git "a/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221.iml" "b/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221/\343\200\220014\343\200\221\343\200\220LongestCommonPrefix\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/src/Main.java" "b/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/src/Main.java" deleted file mode 100644 index 0ee6251..0000000 --- "a/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/src/Main.java" +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Author: - * Date: 2015-06-20 - * Time: 22:56 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - System.out.println(solution.threeSum(new int[]{0, 0, 0, 0})); -// System.out.println(solution.threeSum(new int[]{1, -1, -1, 0})); - System.out.println(solution.threeSum(new int[]{-2,0,1,1,2})); - } -} diff --git "a/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/src/Solution.java" "b/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/src/Solution.java" deleted file mode 100644 index f769078..0000000 --- "a/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/src/Solution.java" +++ /dev/null @@ -1,119 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-06-20 - * Time: 21:46 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * 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:
-     * Elements in a triplet (a,b,c) must be in non-descending order. (ie, a  b  c)
-     * 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)
-     *
-     * Ŀ⣺
-     * һnԪص飬ǷabcԪأʹõa+b+c=0ҳзԪ
-     *
-     * ע⣺
-     *   - ԪеԪرǷǵݼ
-     *   - ܰظԪ
-     *
-     * ˼·
-     *  2sum Ļ3sum⣬3sumĿtargetÿδѡһk
-     * ʣµĿtarget-k2sum⡣ҪעиСtrickǴѡ
-     * iʱֻҪֵдӵi+1һΧ2sum⡣
-     *
-     * ѡһ͵ڶΪA[],ܹnԪA1A2....AnȻѡA1ʱ
-     * [A2~An]Ŀλtarget-A12sum⣬Ҫ֤ǵѡA2ʱֻҪ
-     * [A3~An]мĿλtarget-A22sum⣬[A1,A3~An]У֤£
-     * [A1,A3~An]Ŀλtarget-A22sumУA1 + m = target-A2mΪA3~An
-     * ijA2 + m = target-A1պǡ[A3~An],Ŀλtarget-A12sum⡱
-     * һ⡣൱ڶ3sumA1+A2+m = targetظˡΪ˱ظ㣬
-     * [A1A3~An]У԰A1ȥĿtarget-A22sum⡣
-     *
-     * ڱҪӽ⣬ֻҪ浱ǰԼǰĿľ룬µĽӽ½⡣
-     * 㷨ӶΪOn^2;
-     * 
- * - * @param nums - * @return - */ - public List> threeSum(int[] nums) { - List> result = new LinkedList<>(); - - if (nums != null && nums.length > 2) { - // ȶ - Arrays.sort(nums); - // iʾȡiΪ - for (int i = 0; i < nums.length - 2; ) { - // ڶܵʼλ - int j = i + 1; - // ǽλ - int k = nums.length - 1; - - while (j < k) { - // ҵĽ - if (nums[j] + nums[k] == -nums[i]) { - // ӵ - List list = new ArrayList<>(3); - list.add(nums[i]); - list.add(nums[j]); - list.add(nums[k]); - result.add(list); - - // ƶһλãһ - k--; - j++; - - // ҵһ֮ǰͬ± - while (j < k && nums[j] == nums[j - 1]) { - j++; - } - // ҵһ֮ǰͬ± - while (j < k && nums[k] == nums[k + 1]) { - k--; - } - } - // ʹ0 - else if (nums[j] + nums[k] > -nums[i]) { - k--; - // ҵһ֮ǰͬ± - while (j < k && nums[k] == nums[k + 1]) { - k--; - } - } - // С0 - else { - j++; - // ҵһ֮ǰͬ± - while (j < k && nums[j] == nums[j - 1]) { - j++; - } - } - } - - // ָһҪ - i++; - // ҵһ֮ǰͬ± - while (i < nums.length - 2 && nums[i] == nums[i - 1]) { - i++; - } - } - } - - return result; - } -} diff --git "a/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221.iml" "b/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221/\343\200\220015\343\200\221\343\200\2203Sum\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/src/Main.java" "b/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/src/Main.java" deleted file mode 100644 index ecb9b20..0000000 --- "a/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/src/Main.java" +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Author: - * Date: 2015-06-21 - * Time: 09:58 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - System.out.println(solution.threeSumClosest(new int[]{0, 1 , 2}, 3)); - } -} diff --git "a/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/src/Solution.java" "b/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/src/Solution.java" deleted file mode 100644 index af7e413..0000000 --- "a/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/src/Solution.java" +++ /dev/null @@ -1,91 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Author: - * Date: 2015-06-21 - * Time: 09:29 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given an array S of n integers, find three integers in S such that the sum is
-     * closest to a given number, target. Return the sum of the three integers. You
-     * may assume that each input would have exactly one solution.
-     *
-     * For example,
-     * given array S = {-1 2 1 -4}, and target = 1.
-     * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
-     *
-     * Ŀ⣺
-     * nSҵSеӶʹ֮ӽ
-     * ܺ͡Լÿ뽫һȷеĽ
-     *
-     * ˼·
-     * 3sum
-     * 
- * - * @param nums - * @param target - * @return - */ - public int threeSumClosest(int[] nums, int target) { - - // ¼СIJֵ - long minDiff = Long.MAX_VALUE; - // ¼СֵӦͺ - long result = 0; - // ÿõIJֵ - long diff; - // ÿõĺ - long sum; - - // ȶ - Arrays.sort(nums); - - - // iʾȡiΪ - for (int i = 0; i < nums.length - 2; i++) { - // ڶܵʼλ - int j = i + 1; - // ǽλ - int k = nums.length - 1; - - while (j < k) { - // ǰĺ - sum = nums[j] + nums[k] + nums[i]; - // ǰĿ֮IJֵ - diff = Math.abs(target - sum); - - // ֵΪ0ֱӷ - if (diff == 0) { - return (int) sum; - } - - // ǰIJֵ֮ǰ¼IJֵС - if (diff < minDiff) { - // СIJֵ - minDiff = diff; - // СֵӦĺ - result = sum; - - // ϵһԪشʱЧ - } - - - // ʹtarget - if (sum > target) { - k--; - } - // Сtarget - else { - j++; - } - } - } - - return (int) result; - } -} diff --git "a/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221.iml" "b/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221/\343\200\220016\343\200\221\343\200\2203SumClosest\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/src/Solution.java" "b/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/src/Solution.java" deleted file mode 100644 index 1f26d6f..0000000 --- "a/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/src/Solution.java" +++ /dev/null @@ -1,95 +0,0 @@ -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-08-21 - * Time: 16:23 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - - private String[] map = { - "abc", - "def", - "ghi", - "jkl", - "mno", - "pqrs", - "tuv", - "wxyz", - }; - private List result; // 洢ս - private char[] chars; // ȥ01ַĽ - private char[] curResult; // 洢м - private int end = 0; // ַеĵһδʹõλ - private int handle = 0; // ǰǵڼַ - - /** - *
-     * ԭ
-     * Given a digit string, return all possible letter combinations that the number could represent.
-     * A mapping of digit to letters (just like on the telephone buttons) is given below.
-     *
-     * Input:Digit string "23"
-     * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
-     *
-     * Note: Although the above answer is in lexicographical order, your answer
-     * could be in any order you want.
-     *
-     * Ŀ
-     * һִַϣֵַӳͼʾ
-     * ע⣺ Ľַ˳еģκ˳򷵻ؽ
-     *
-     * ˼·
-     * һ鱣ֵֺӳϵִ룬ҵӦַϽ
-     * 
- * - * @param digits - * @return - */ - public List letterCombinations(String digits) { - result = new LinkedList<>(); - - if (digits != null && digits.length() > 0) { - - chars = digits.toCharArray(); - - // ַдȥ01 - // ҵһ01λ - while (end < digits.length() && chars[end] != '0' && chars[end] != '1') { - end++; - } - - handle = end + 1; - while (handle < chars.length) { - if (chars[handle] != '0' && chars[handle] != '1') { - chars[end] = chars[handle]; - end++; - } - handle++; - } - - curResult = new char[end]; - // whileendΪЧַij - handle = 0; // ָһЧַλ - - letterCombinations(); - } - return result; - } - - private void letterCombinations() { - if (handle >= end) { - result.add(new String(curResult)); - } else { - int num = chars[handle] - '2'; - for (int i = 0; i < map[num].length(); i++) { - curResult[handle] = map[num].charAt(i); - handle++; - letterCombinations(); - handle--; - } - } - } -} diff --git "a/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221.iml" "b/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221/\343\200\220017\343\200\221\343\200\220LetterCombinationsOfAPhonNumber \343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221/src/Solution.java" "b/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221/src/Solution.java" deleted file mode 100644 index f983189..0000000 --- "a/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221/src/Solution.java" +++ /dev/null @@ -1,95 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-08-21 - * Time: 16:28 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given an array S of n integers, are there elements a, b, c, and d in S
-     * such that a + b + c + d = target? Find all unique quadruplets in the array
-     * which gives the sum of target.
-     * Note:
-     * Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a  b  c  d)
-     * The solution set must not contain duplicate quadruplets.
-     *
-     * For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
-     *
-     * A solution set is:
-     * (-1,  0, 0, 1)
-     * (-2, -1, 1, 2)
-     * (-2,  0, 0, 2)
-     *
-     * Ŀ
-     * һ飬ҳa + b + c + d = targetΨһ⡣
-     *
-     * ˼·
-     * ȷadadͬʱظʹáȻȷbcͬҲ
-     * ͬʱظʹáҳĽ⣬ͬʱԱ֤ⲻظ
-     * 
- * - * @param num - * @param target - * @return - */ - public List> fourSum(int[] num, int target) { - List> result = new LinkedList<>(); - if (num == null || num.length < 4) { - return result; - } - - Arrays.sort(num); // - - for (int i = 0; i < num.length - 3; i++) { // һ - if (i > 0 && num[i] == num[i - 1]) { // һʹòظ - continue; - } - - for (int j = num.length - 1; j > i + 2; j--) { // ĸ - if (j < num.length - 1 && num[j] == num[j + 1]) { // ĸʹòظ - continue; - } - - int start = i + 1; // ڶ - int end = j - 1; // - int n = target - num[i] - num[j]; - - while (start < end) { - if (num[start] + num[end] == n) { - List four = new ArrayList<>(4); - four.add(num[i]); - four.add(num[start]); - four.add(num[end]); - four.add(num[j]); - - result.add(four); - - do { - start++; - } while (start < end && num[start] == num[start - 1]); // ֤ٴʹõڶظ - - do { - end--; - } while (start < end && num[end] == num[end + 1]); // ֤ٴʹõظ - } else if (num[start] + num[end] < n) { - do { - start++; - } while (start < end && num[start] == num[start - 1]); // ֤ٴʹõڶظ - } else { - do { - end--; - } while (start < end && num[end] == num[end + 1]); // ֤ٴʹõظ - } - } - } - } - return result; - } -} diff --git "a/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221.iml" "b/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221/\343\200\220018\343\200\221\343\200\2204Sum\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/src/Solution.java" "b/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/src/Solution.java" deleted file mode 100644 index 7c004d0..0000000 --- "a/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/src/Solution.java" +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:30 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given a linked list, remove the nth node from the end of list and return its head.
-     * For example,
-     *
-     * 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.
-     *
-     * Note:
-     * Given n will always be valid.
-     * Try to do this in one pass.
-     *
-     * Ŀ
-     * ɾĵڣθ㣬ע⣺ģζǺϷһαɲ
-     *
-     * ˼·
-     * һָҵNڵ㣬Ȼһָָͷ㣬Ȼָһߣ
-     * ֱǰһֱָĩβһָǵN+1㣬ɾNͿˡ
-     * 
- * - * @param head - * @param n - * @return - */ - public ListNode removeNthFromEnd(ListNode head, int n) { - ListNode pa = head; - ListNode pb = head; - - // ҵn - for (int i = 0; i < n && pa != null; i++) { - pa = pa.next; - } - - - if (pa == null) { - head = head.next; - return head; - } - - // pbpan-1 - // pa.nextΪnullpbڵn+1λ - while (pa.next != null) { - pa = pa.next; - pb = pb.next; - } - - pb.next = pb.next.next; - return head; - } -} diff --git "a/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221.iml" "b/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221/\343\200\220019\343\200\221\343\200\220RemoveNthNodeFromEndOfList\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221/src/Solution.java" "b/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221/src/Solution.java" deleted file mode 100644 index 67bac1f..0000000 --- "a/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221/src/Solution.java" +++ /dev/null @@ -1,97 +0,0 @@ -import java.util.Deque; -import java.util.LinkedList; - -/** - * Author: - * Date: 2015-08-21 - * Time: 16:32 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * 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.
-     *
-     * Ŀ
-     * һֻ(, ), {, }, [ ͡]ַ֤ǷЧġ
-     * űԣҪȷ˳
-     *
-     * ˼·
-     * һջŴдžջžջԪؿǷһţ
-     * ɾ͵Ҵһţƥֱӷؽ
-     * 
- * - * @param s - * @return - */ - public boolean isValid(String s) { - Deque stack = new LinkedList<>(); - int index = 0; - Character top; - while (index < s.length()) { - Character c = s.charAt(index); - switch (c) { - case '(': - case '[': - case '{': - stack.addFirst(c); - break; - case ')': - - if (stack.isEmpty()) { - return false; - } - - top = stack.getFirst(); - if (top == '(') { - stack.removeFirst(); - } else if (top == '[' || top == '{') { - return false; - } else { - stack.addFirst(c); - } - break; - case ']': - - if (stack.isEmpty()) { - return false; - } - - top = stack.getFirst(); - if (top == '[') { - stack.removeFirst(); - } else if (top == '(' || top == '{') { - return false; - } else { - stack.addFirst(c); - } - break; - case '}': - - if (stack.isEmpty()) { - return false; - } - - top = stack.getFirst(); - if (top == '{') { - stack.removeFirst(); - } else if (top == '[' || top == '(') { - return false; - } else { - stack.addFirst(c); - } - break; - default: - return false; - } - - index++; - } - - return stack.isEmpty(); - } -} diff --git "a/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221.iml" "b/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221/\343\200\220020\343\200\221\343\200\220ValidParentheses\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/src/Solution.java" "b/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/src/Solution.java" deleted file mode 100644 index 15b4d85..0000000 --- "a/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/src/Solution.java" +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:35 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * 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.
-     *
-     * Ŀ
-     * ϲһµбµĽԭȵɣ
-     * ҲDzܺϲܰ´Ľ㡣
-     *
-     * ˼·
-     * ʹͷrootиһͷ㣬ʹָͷ㣬
-     * СĽֵĽժӵrootĩβͬʱժͷƶһ㣬
-     * һֱԭһΪգٽʣµĽӵrootĩβ
-     * 󷵻rootһ㣬Ϊµͷ
-     * 
- * - * @param l1 - * @param l2 - * @return - */ - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - - ListNode head = new ListNode(0); // һͷ㣬Ҫɾ - ListNode tail = head; - - while (l1 != null && l2 != null) { - if (l1.val <= l2.val) { - tail.next = l1; - l1 = l1.next; - } else { - tail.next = l2; - l2 = l2.next; - } - - tail = tail.next; // ƶµβ - } - - tail.next = (l1 != null ? l1 : l2); - - return head.next; // headһڵǵһݽ - } -} diff --git "a/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221.iml" "b/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221/\343\200\220021\343\200\221\343\200\220MergeTwoSortedLists\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/src/Solution.java" "b/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/src/Solution.java" deleted file mode 100644 index ce980c4..0000000 --- "a/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/src/Solution.java" +++ /dev/null @@ -1,72 +0,0 @@ -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-06-22 - * Time: 11:13 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * 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:
-     * "((()))", "(()())", "(())()", "()(())", "()()()"
-     *
-     * Ŀ⣺
-     * nţȷ
-     *
-     * ˼·
-     * õݹ
-     * 
- * - * @param n - * @return - */ - public List generateParenthesis(int n) { - // Ķ - List result = new ArrayList<>(); - // 0 - if (n > 0) { - // ʹ - char[] parentheses = new char[2 * n]; - // - solve(n, n, parentheses, result); - } - return result; - } - - /** - * @param left ʣõ - * @param right ʣõ - * @param parentheses һΪֹʹõ - * @param result Žļ - */ - public void solve(int left, int right, char[] parentheses, List result) { - - // ʣµС0ÿʣµС - if (left < 0 || right < 0 || right < left) { - // ʲô - } - // Ŷʹ - else if (left == 0 && right == 0) { - result.add(new String(parentheses)); - } - // ʹ - else { - // ǰʹõλ - int idx = parentheses.length - left - right; - // ʹ - parentheses[idx] = '('; - // ݹ - solve(left - 1, right, parentheses, result); - // ʹ - parentheses[idx] = ')'; - solve(left, right - 1, parentheses, result); - } - } -} diff --git "a/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221.iml" "b/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221/\343\200\220022\343\200\221\343\200\220GenerateParentheses\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/src/Solution.java" "b/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/src/Solution.java" deleted file mode 100644 index 243ebc1..0000000 --- "a/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/src/Solution.java" +++ /dev/null @@ -1,214 +0,0 @@ -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -/** - * Author: - * Date: 2015-06-30 - * Time: 19:21 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Merge k sorted linked lists and return it as one sorted list.
-     * Analyze and describe its complexity.
-     *
-     * Ŀ⣺
-     * ϲkźõĵĵ
-     *
-     * ˼·
-     * ʹһСвȽkĵһѣȡеСأΪСԪأ
-     * ԪصһѣȡСģβֱΪ
-     * 
- * - * @param lists - * @return - */ - public ListNode mergeKLists(ListNode[] lists) { - - // ΪջûԪ - if (lists == null || lists.length < 1) { - return null; - } - - // ֻһԪ - if (lists.length == 1) { - return lists[0]; - } - - // һСѣʹһڲΪȽ - MinHeap minHeap = new MinHeap(new Comparator() { - @Override - public int compare(ListNode o1, ListNode o2) { - if (o1 == null) { - return -1; - } - - if (o2 == null) { - return 1; - } - - return o1.val - o2.val; - } - }); - - - // ĵһ - for (ListNode node : lists) { - if (node != null) { - minHeap.add(node); - } - } - - // ͷ㣬ʹ - ListNode head = new ListNode(0); - // ǰĽ - ListNode curr = head; - - while (!minHeap.isEmpty()) { - ListNode node = minHeap.deleteTop(); - - // һ㲻Ϊվͽһ - if (node.next != null) { - minHeap.add(node.next); - } - - curr.next = node; - curr = node; - } - - return head.next; - } - - /** - * С - * - * @param - */ - private static class MinHeap { - // Ԫشŵļ - private List items; - - private Comparator comp; - - /** - * һ׵ʼС32 - */ - public MinHeap(Comparator comp) { - this(32, comp); - } - - /** - * һָʼСĶ - * - * @param size ʼС - */ - public MinHeap(int size, Comparator comp) { - items = new ArrayList<>(size); - this.comp = comp; - } - - /** - * ϵ - * - * @param index Ԫصʼλ - */ - public void siftUp(int index) { - T intent = items.get(index); // ȡʼԪض - - while (index > 0) { // ǸԪ - int parentIndex = (index - 1) / 2; // ҸԪضλ - T parent = items.get(parentIndex); // ȡԪض - if (comp.compare(intent, parent) < 0) { //ƵӽڵȸڵС - items.set(index, parent); // ڵ· - index = parentIndex; // ¼ڵ·ŵλ - } else { // ӽڵ㲻ȸڵС˵·ѾСź˳ˣҪ - break; - } - } - - // indexʱ¼ǵһ·ŵĸڵλãҲ - // ԽʼĵԪֵindexλü - items.set(index, intent); - } - - /** - * µ - * - * @param index ƵԪصʼλ - */ - public void siftDown(int index) { - T intent = items.get(index); // ȡʼԪض - int leftIndex = 2 * index + 1; // // ȡʼԪضӽԪλ - - while (leftIndex < items.size()) { // ӽ - T minChild = items.get(leftIndex); // ȡӽԪض󣬲ҼٶΪӽС - int minIndex = leftIndex; // ӽڵСڵԪصλãٶʼʱΪӽλ - - int rightIndex = leftIndex + 1; // ȡӽλ - if (rightIndex < items.size()) { // ӽ - T rightChild = items.get(rightIndex); // ȡӽԪض - if (comp.compare(rightChild, minChild) < 0) { // ҳӽڵеСӽ - minChild = rightChild; - minIndex = rightIndex; - } - } - - // СӽڵȸڵСҪµ - if (comp.compare(minChild, intent) < 0) { - items.set(index, minChild); // ӽڵ - index = minIndex; // ¼ƽڵλ - leftIndex = index * 2 + 1; // ҵƽڵӽڵλ - } else { // Сӽڵ㲻ȸڵС˵·ѾСź˳ˣҪ - break; - } - } - - // indexʱ¼ǵһƵӽڵλãҲ - // ԽʼĵԪֵindexλü - items.set(index, intent); - } - - /** - * һԪ - * - * @param item ȴӵԪ - */ - public void add(T item) { - items.add(item); // Ԫӵ - siftUp(items.size() - 1); // ѭƣع - } - - /** - * ɾѶԪ - * - * @return ѶԪ - */ - public T deleteTop() { - if (items.isEmpty()) { // ѾΪգͱ쳣 - throw new RuntimeException("The heap is empty."); - } - - T maxItem = items.get(0); // ȡѶԪ - T lastItem = items.remove(items.size() - 1); // ɾһԪ - if (items.isEmpty()) { // ɾԪغΪյ˵ɾԪҲǶѶԪ - return lastItem; - } - - items.set(0, lastItem); // ɾԪطѶ - siftDown(0); // µ - return maxItem; // ضѶԪ - } - - /** - * ж϶ǷΪ - * - * @return trueǿգfalse - */ - public boolean isEmpty() { - return items.isEmpty(); - } - } - -} diff --git "a/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221.iml" "b/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221/\343\200\220023\343\200\221\343\200\220MergeKSortedLists\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/src/Solution.java" "b/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/src/Solution.java" deleted file mode 100644 index 1f5afe5..0000000 --- "a/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/src/Solution.java" +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:37 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given a linked list, swap every two adjacent nodes and return its head.
-     * For example,
-     * Given 1->2->3->4, you should return the list as 2->1->4->3.
-     * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
-     *
-     * Ŀ
-     * һɶԽڵĽ㡣㷨Ӧռ䣬ܸĽֵֻܽ㡣
-     *
-     * ˼·
-     * ʹһͷrootҪнÿλýн
-     * ҰѽĽӵrootϣֱеĽ㶼ꡣ
-     * 
- * - * @param head - * @return - */ - public ListNode swapPairs(ListNode head) { - ListNode node = new ListNode(0); // ͷ - node.next = head; - - // pָµβ - ListNode p = node; - ListNode tmp; - - // ÿв - while (p.next != null && p.next.next != null) { - // ¼һҪдλ - tmp = p.next.next; - // 㽻 - p.next.next = tmp.next; - tmp.next = p.next; - p.next = tmp; - // ָ򷵻µβ - p = tmp.next; - } - - head = node.next; - node.next = null; - - return head; - } -} diff --git "a/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221.iml" "b/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221/\343\200\220024\343\200\221\343\200\220SwapNodesInPairs\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221.iml" "b/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221/\343\200\220025\343\200\221\343\200\220ReverseNodesInK-Group\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221/src/Solution.java" "b/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221/src/Solution.java" deleted file mode 100644 index d2a1fa2..0000000 --- "a/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221/src/Solution.java" +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:40 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * 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 doesnt matter what you leave beyond the new length.
-     *
-     * Ŀ
-     * һ飬еظԪȥֻͬһҷµԪظ
-     * Ҫһµڳʱڽ
-     *
-     * ˼·
-     * ӵڶԪؿʼΪǰԪأǰԪǰһԪͬɾԪأ
-     * ͬͽƶȷλãԪ˸
-     * 
- * - * @param A - * @return - */ - public int removeDuplicates(int[] A) { - - if (A.length == 0) { - return 0; - } - - int index = 0;//[0,index]ֻ¼гֵİСΨһһѾź - int next = 1; - - // 㷨˼룺index֮ıA[index]ҵƶA[index+1] - // indexƶһλãnextƶһλãұA[index] - - while (next < A.length) { - while (next < A.length && A[index] == A[next]) { // Ҳ - next++; - } - - if (next < A.length) { - index++; - A[index] = A[next]; - next++; - } - } - return index + 1; - } -} diff --git "a/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221.iml" "b/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221/\343\200\220026\343\200\221\343\200\220RemoveDuplicatesfromSortedArray\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221/src/Solution.java" "b/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221/src/Solution.java" deleted file mode 100644 index e7ae1e6..0000000 --- "a/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221/src/Solution.java" +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:43 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given an array and a value, remove all instances of that value in place and return the new length.
-     *  The order of elements can be changed. It doesnt matter what you leave beyond the new length.
-     *
-     * Ŀ
-     * һһֵɾֵȵԪأҷµijȡ
-     *
-     * ˼·
-     * ֵΪelemԪصλãjұֵΪelemԪصλãȻjλõֵƶiλá
-     * 
- * - * @param A - * @param elem - * @return - */ - public int removeElement(int[] A, int elem) { - int exchange = 0; // ¼ĴҲͳelemԪֵȵĸ - - // 㷨˼룺iֵΪelemԪصλãjұֵΪelemԪصλã - // ȡȺóΪ1Խ - for (int i = 0, j = A.length - 1; i <= j; i++) { - if (A[i] == elem) { // ҵҪԪ - exchange++; - - while (j > i && A[j] == elem) { // 濪ʼǰҵһelemԪ - exchange++; // ֵΪelemԪ˵Ҫǽ̿ʡȥ - j--; - } - - // 1ΪelemԪصλãjλõԪطŵiλ - // 2ûҵelemԪصλãiԪֵeʱj=i - // jеֵiûйϵ - A[i] = A[j]; - j--; // jѾʹԻҪǰƶһµλ - } - } - - return A.length - exchange; - } -} diff --git "a/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221.iml" "b/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221/\343\200\220027\343\200\221\343\200\220RemoveElement\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221/\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221.iml" "b/\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221/\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221/\343\200\220028\343\200\221\343\200\220Implement-strStr()\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221.iml" "b/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221/\343\200\220029\343\200\221\343\200\220DivideTwoIntegers\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221/src/Solution.java" "b/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221/src/Solution.java" deleted file mode 100644 index b6d432d..0000000 --- "a/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221/src/Solution.java" +++ /dev/null @@ -1,33 +0,0 @@ -import java.util.List; - -/** - * Author: - * Date: 2015-07-01 - * Time: 08:23 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * You are given a string, s, and a list of words, words,
-     * that are all of the same length. Find all starting indices
-     * of substring(s) in s that is a concatenation of each word
-     * in words exactly once and without any intervening characters.
-     *
-     * For example, given:
-     * s: "barfoothefoobarman"
-     * words: ["foo", "bar"]
-     * You should return the indices: [0,9].
-     * (order does not matter).
-     * 
- * - * @param s - * @param words - * @return - */ - public List findSubstring(String s, String[] words) { - - - return null; - } -} diff --git "a/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221.iml" "b/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221/\343\200\220030\343\200\221\343\200\220SubstringWithConcatenationOfAllWords\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/src/Solution.java" "b/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/src/Solution.java" deleted file mode 100644 index 2e4f5d1..0000000 --- "a/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/src/Solution.java" +++ /dev/null @@ -1,54 +0,0 @@ -import java.util.Deque; -import java.util.LinkedList; -import java.util.Stack; - -/** - * Author: - * Date: 2015-06-25 - * Time: 09:12 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a string containing just the characters '(' and ')',
-     * find the length of the longest valid (well-formed) parentheses substring.
-     *
-     * For "(()", the longest valid parentheses substring is "()", which has length = 2.
-     * Another example is ")()())", where the longest valid parentheses substring is "()()",
-     * which has length = 4.
-     *
-     * Ŀ⣺
-     * һַֻСźţĺϷСŵĿ
-     *
-     * ˼·
-     * ʹջʵ
-     * 
- * - * @param s - * @return - */ - public int longestValidParentheses(String s) { - // ڼ¼ƥźŵλ - Stack st = new Stack<>(); - int max = 0; - for (int i = 0; i < s.length(); i++) { - - // ǵǰַţҼ¼ջǿգǰһַ - if (s.charAt(i) == ')' && !st.isEmpty() && s.charAt(st.peek()) == '(') { - // ųջ - st.pop(); - // ֵ - // ʱ(ƥ)ѾջջҪôΪգҪô뵱ǰ)) - // Ҫô뵱ǰ)ڶ( - max = Math.max(max, i - ((st.isEmpty()) ? -1 : st.peek())); - } - // ͽַջ - else { - st.push(i); - } - } - - return max; - } -} diff --git "a/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221.iml" "b/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221/\343\200\220032\343\200\221\343\200\220LongestValidParentheses\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221/src/Solution.java" "b/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221/src/Solution.java" deleted file mode 100644 index e8921ba..0000000 --- "a/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221/src/Solution.java" +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Author: - * Date: 2015-06-21 - * Time: 14:48 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Suppose a sorted array is rotated at some pivot unknown to you beforehand.
-     * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
-     * You are given a target value to search. If found in the array return its
-     * index, otherwise return -1.
-     *
-     * You may assume no duplicate exists in the array.
-     *
-     * Ŀ⣺
-     * һһδ֪ĵת0 1 2 4 5 6 7ܳΪ4 5 6 7 0 1 2
-     * һĿֵѰھͷӦ±꣬򷵻-1
-     * вظֵ
-     *
-     * ˼·
-     * תСֵλminIndexLeetCode153 minIndexΪ˵ڷָ
-     * 飬ǰһеĵһԪضںһÿһԪأжtargetһ
-     * ʹö㷨ңminIndex=0˵ȫ򣬶жңزҽ
-     * 
- * - * @param nums - * @param target - * @return - */ - public int search(int[] nums, int target) { - - if (nums != null && nums.length > 0) { - - // СԪضӦ± - int minIndex = searchMinIndex(nums, 0, nums.length - 1); - - // ȫ - if (minIndex == 0) { - return binarySearch(nums, 0, nums.length - 1, target); - } - // ֲ, 4 5 6 7 8 9 0 1 2 3 - else { - // úͺһһԪȣضӦ± - if (nums[nums.length - 1] == target) { - return nums.length - 1; - } - // targetںһ - else if (nums[nums.length - 1] > target) { - return binarySearch(nums, minIndex, nums.length - 1, target); - } - // targetǰһ - else { - return binarySearch(nums, 0, minIndex - 1, target); - } - } - } - - return -1; - } - - /** - * - * - * @param nums - * @param start ʼλ - * @param end λ - * @param target Ŀ - * @return ƥԪص± - */ - public int binarySearch(int[] nums, int start, int end, int target) { - - int mid; - while (start <= end) { - mid = start + ((end - start) >> 1); - - if (nums[mid] == target) { - return mid; - } else if (nums[mid] > target) { - end = mid - 1; - } else { - start = mid + 1; - } - } - - return -1; - } - - /** - * СԪص± - * - * @param nums - * @param start ʼλ - * @param end λ - * @return СԪص± - */ - public int searchMinIndex(int[] nums, int start, int end) { - - int mid; - while (start < end) { - mid = start + ((end - start) >> 1); - // һǰСҵ - if (nums[mid] > nums[mid + 1]) { - return mid + 1; - } - // ˵мֵڵһ - else if (nums[mid] > nums[start]) { - start = mid; - } - // ˵мֵڵڶ - else { - end = mid; - } - } - - // ˵ - return 0; - } -} diff --git "a/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221.iml" "b/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221/\343\200\220033\343\200\221\343\200\220SearchInRotatedSortedArray\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221/\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221.iml" "b/\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221/\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221/\343\200\220034\343\200\221\343\200\220SearchForARange\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221/\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221.iml" "b/\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221/\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221/\343\200\220035\343\200\221\343\200\220SearchInsertPosition\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/src/Solution.java" "b/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/src/Solution.java" deleted file mode 100644 index d0147d6..0000000 --- "a/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/src/Solution.java" +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 16:59 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
-     * The Sudoku board could be partially filled, where empty cells are filled
-     * with the character '.'.
-     *
-     * A partially filled sudoku which is valid.
-     * Note:
-     * A valid Sudoku board (partially filled) is not necessarily solvable.
-     * Only the filled cells need to be validated.
-     *
-     * Ŀ
-     * ֤һǷϷ̵֤ӶӦҳ档
-     * Dzģյλʹõ档
-     * ע⣺Ϸ̲һҪĿɽģֻҪҪͿԡ
-     *
-     * ˼·
-     * ȶнм飬ٶнм飬飳*ķ
-     * 
- * - * @param board - * @return - */ - public boolean isValidSudoku(char[][] board) { - // .ASCIIֵ460ASCIIֵ48/ASCIIֵ47 - int number = board[0].length; - int[] record = new int[10 + 2]; //.9ֵݵλ[2, 10] - boolean isValid; - reset(record); - - // нм - for (int i = 0; i < number; i++) { - for (int j = 0; j < number; j++) { - record[board[i][j] - '.']++; - } - - if (!check(record)) { // Ǽʧ - return false; - } else { // ɹ - reset(record); - } - } - - // нм - for (int i = 0; i < number; i++) { - for (int j = 0; j < number; j++) { - record[board[j][i] - '.']++; - } - - if (!check(record)) { // Ǽʧ - return false; - } else { // ɹ - reset(record); - } - } - - // 3*3 - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - - for (int k = i * 3; k < (i + 1) * 3; k++) { - for (int l = j * 3; l < (j + 1) * 3; l++) { - record[board[k][l] - '.']++; - } - } - - if (!check(record)) { // Ǽʧ - return false; - } else { // ɹ - reset(record); - } - } - } - return true; - } - - private void reset(int[] a) { - for (int i = 0; i < a.length; i++) { - a[i] = 0; - } - - - } - - /** - * һУһУ3*3ķǷϷ1-9еָ1ͲϷ - * - * @param a ֤ - * @return ؽ - */ - private boolean check(int[] a) { - for (int i = 2; i < a.length; i++) { - if (a[i] > 1) { - return false; - } - } - return true; - } -} diff --git "a/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221.iml" "b/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221/\343\200\220036\343\200\221\343\200\220Valid Sudoku\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221/\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221.iml" "b/\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221/\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221/\343\200\220038\343\200\221\343\200\220CountAndSay\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221/src/Solution.java" "b/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221/src/Solution.java" deleted file mode 100644 index 317ceda..0000000 --- "a/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221/src/Solution.java" +++ /dev/null @@ -1,66 +0,0 @@ -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-08-21 - * Time: 16:50 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - private List> result; - - /** - *
-     * ԭ
-     * Given a collection of numbers, return all possible permutations.
-     * For example,
-     * [1,2,3] have the following permutations:
-     * [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
-     *
-     * Ŀ
-     * һ飬С
-     *
-     * ˼·
-     * ʹ÷η⡣
-     * 
- * - * @param num - * @return - */ - public List> permute(int[] num) { - - result = new LinkedList<>(); - if (num != null) { - permute(0, num); - } - - return result; - } - - private void permute(int i, int[] num) { - - if (i == num.length) { - List l = new ArrayList<>(); - for (int n : num) { - l.add(n); - } - - result.add(l); - } else { - - for (int j = i; j < num.length; j++) { - swap(num, j, i); - permute(i + 1, num); - swap(num, j, i); - } - } - } - - private void swap(int[] A, int x, int y) { - int tmp = A[x]; - A[x] = A[y]; - A[y] = tmp; - } -} diff --git "a/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221.iml" "b/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221/\343\200\220046\343\200\221\343\200\220Permutations\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221/\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221.iml" "b/\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221/\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221/\343\200\220050\343\200\221\343\200\220Pow(x,n)\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220052\346\234\252\343\200\221\343\200\220N-QueensII \343\200\221/\343\200\220052\343\200\221\343\200\220N-QueensII \343\200\221.iml" "b/\343\200\220052\346\234\252\343\200\221\343\200\220N-QueensII \343\200\221/\343\200\220052\343\200\221\343\200\220N-QueensII \343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220052\346\234\252\343\200\221\343\200\220N-QueensII \343\200\221/\343\200\220052\343\200\221\343\200\220N-QueensII \343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221/src/Solution.java" "b/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221/src/Solution.java" deleted file mode 100644 index 9c2d79b..0000000 --- "a/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221/src/Solution.java" +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Author: - * Date: 2015-06-22 - * Time: 12:05 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Find the contiguous subarray within an array (containing at least one number)
-     * which has the largest 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.
-     *
-     * Ŀ⣺
-     * ĺ
-     * ˼·
-     * ̬滮⣬֪ǰkԪصкΪmaxSubѾ¼ˣԼһʱsum
-     * ˵k+1Ԫأƣk+1Ԫ֮ǰĺС0ģ
-     * ôk+1ԪشӶȥûй׵ģԿ԰sum 0
-     *
- * @param nums - * @return - */ - public int maxSubArray(int[] nums) { - // У - if (nums == null || nums.length < 1) { - throw new IllegalArgumentException(); - } - - int max = Integer.MIN_VALUE; - int curSum = 0; - - for (int i : nums) { - // ǰС0ͽǰֵcurSum - if (curSum <= 0){ - curSum = i; - } - // ۼ - else { - curSum += i; - } - - // ϴֵ - if (max < curSum) { - max = curSum; - } - } - - return max; - } -} diff --git "a/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221.iml" "b/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221/\343\200\220053\343\200\221\343\200\220MaximumSubarray\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221/\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221.iml" "b/\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221/\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221/\343\200\220054\343\200\221\343\200\220SpiralMatrix\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220055\346\234\252\343\200\221\343\200\220JumpGame\343\200\221/src/Solution.java" "b/\343\200\220055\346\234\252\343\200\221\343\200\220JumpGame\343\200\221/src/Solution.java" deleted file mode 100644 index d3e5313..0000000 --- "a/\343\200\220055\346\234\252\343\200\221\343\200\220JumpGame\343\200\221/src/Solution.java" +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Author: - * Date: 2015-06-19 - * Time: 19:29 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given an array of non-negative integers, you are initially positioned at the
-     * first index of the array.
-     *
-     * Each element in the array represents your maximum jump length at that position.
-     *
-     * Determine if you are able to reach the last index.
-     *
-     * For example:
-     * A = [2,3,1,1,4], return true.
-     * A = [3,2,1,0,4], return false.
-     *
-     * Ŀ⣺
-     * ķǸ飬λĵһλáеÿԪضԾǸλá
-     * Ƿܵһ
-     *
-     * 
- * - * @param nums - * @return - */ - public boolean canJump(int[] nums) { - return false; - } -} diff --git "a/\343\200\220055\346\234\252\343\200\221\343\200\220JumpGame\343\200\221/\343\200\220055\343\200\221\343\200\220JumpGame\343\200\221.iml" "b/\343\200\220055\346\234\252\343\200\221\343\200\220JumpGame\343\200\221/\343\200\220055\343\200\221\343\200\220JumpGame\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220055\346\234\252\343\200\221\343\200\220JumpGame\343\200\221/\343\200\220055\343\200\221\343\200\220JumpGame\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/src/Solution.java" "b/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/src/Solution.java" deleted file mode 100644 index 312eac5..0000000 --- "a/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/src/Solution.java" +++ /dev/null @@ -1,60 +0,0 @@ -import java.util.*; - -/** - * Author: - * Date: 2015-06-23 - * Time: 19:39 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * 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].
-     *
-     * Ŀ⣬
-     * һ伯ϣϲص
-     *
-     * ˼·
-     * ȶ򣬰ʼһһкϲ
-     * 
- * - * @param intervals - * @return - */ - public List merge(List intervals) { - List result = new LinkedList<>(); - - if (intervals == null || intervals.size() < 1) { - return result; - } - - // ȶʹһڲ - Collections.sort(intervals, new Comparator() { - @Override - public int compare(Interval o1, Interval o2) { - return o1.start - o2.start; - } - }); - - // 󣬺һԪأΪnextstartһDzСǰһΪprevstartģ - // ӵ䣬next.startprev.end˵ǷֿģҪ - // һµ䣬˵next.start[prev.start, prev.end]ڣֻҪ - // next.endǷǴprev.endھҪϲ䣨 - Interval prev = null; - for (Interval item : intervals) { - - if (prev == null || prev.end < item.start) { - result.add(item); - prev = item; - } else if (prev.end < item.end) { - prev.end = item.end; - } - } - - return result; - } -} diff --git "a/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221.iml" "b/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221/\343\200\220056\343\200\221\343\200\220MergeIntervals\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/src/Solution.java" "b/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/src/Solution.java" deleted file mode 100644 index d158b09..0000000 --- "a/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/src/Solution.java" +++ /dev/null @@ -1,76 +0,0 @@ -import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ; - -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-06-24 - * Time: 19:33 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a set of non-overlapping intervals, insert a new interval into the intervals
-     * (merge if necessary).
-     *
-     * 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].
-     *
-     * 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].
-     *
-     * Ŀ⣺
-     * һϵзǸǵ䣬һµ䣬бҪʱϲ
-     * 俪ʼʼʱкϲ
-     *
-     * ˼·
-     * ԭȲСͲص²䣬
-     * Сԭ䣬Ȳ䣬Ӵ
-     * 
- * - * @param intervals - * @param newInterval - * @return - */ - public List insert(List intervals, Interval newInterval) { - - // ļ - List result = new LinkedList<>(); - - // 뼯ǿ - if (intervals != null) { - // Ԫ - for (Interval item : intervals) { - // newInterval == null ʾѾ - // ȲС - if (newInterval == null || item.end < newInterval.start) { - result.add(item); - } - // ȲУͬʱ - else if (item.start > newInterval.end) { - result.add(newInterval); - result.add(item); - newInterval = null; - } - // ص² - else { - newInterval.start = Math.min(newInterval.start, item.start); - newInterval.end = Math.max(newInterval.end, item.end); - } - } - } - - // ǿ˵仹δ - if (newInterval != null) { - result.add(newInterval); - } - - return result; - } -} diff --git "a/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221.iml" "b/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221/\343\200\220057\343\200\221\343\200\220InsertInterval\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221/\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221.iml" "b/\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221/\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221/\343\200\220058\343\200\221\343\200\220LengthOfLastWord\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221/\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221.iml" "b/\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221/\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221/\343\200\220059\343\200\221\343\200\220SpiralMatrixII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/src/Solution.java" "b/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/src/Solution.java" deleted file mode 100644 index 5f75aba..0000000 --- "a/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/src/Solution.java" +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Author: - * Date: 2015-07-21 - * Time: 18:46 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - public ListNode rotateRight(ListNode head, int n) { - - if (head == null || n < 1) { - return head; - } - - ListNode root = new ListNode(0); - root.next = head; - ListNode p = root; - ListNode q = root; - - int count = 0; - for (int i = 0; i <= n; i++) { - p = p.next; - count++; - if (p == null) { - count--; // гͷݸ - n = n % count; // ʵҪλõλ - // Ϊ¿ʼλ׼ - i = 0; - p = head; - } - } - - // ҵһҪĽǰ - // qΪһҪĽǰ - while (p != null) { - p = p.next; - q = q.next; - - } - - p = q; - q = root; - if (p != null && p.next != null) { // ҪλƵĽ - ListNode node; - while (p.next != null) { - // ժ - node = p.next; - p.next = node.next; - // Ͻ - node.next = q.next; - q.next = node; - q = node; // һƶĽڵ - } - } - - return root.next; - } -} diff --git "a/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221.iml" "b/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221/\343\200\220061\343\200\221\343\200\220RotateList\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221/src/Solution.java" "b/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221/src/Solution.java" deleted file mode 100644 index d379e68..0000000 --- "a/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221/src/Solution.java" +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:30 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * A robot is located at the top-left corner of a m x n grid
-     * (marked Start in the diagram below).
-     * The robot can only move either down or right at any point in time.
-     * The robot is trying to reach the bottom-right corner of the grid
-     * (marked Finish in the diagram below).
-     * How many possible unique paths are there?
-     *
-     * Above is a 3 x 7 grid. How many possible unique paths are there?
-     * Note: m and n will be at most 100.
-     *
-     * Ŀ
-     * һһm*nķϽǡ
-     * ֻһһ񣬻Ҫ½ǵķ
-     * һжΨһ·
-     * ע⣺ͣ󲻳100
-     *
-     * ˼·
-     * ͵Ķ̬滮⣬ʹö̬滮ķ⡣
-     * һ*nA
-     * AеԪС
-     * 1x=0y=0ʱA[x][y] = 1
-     * 2x>=1y>=1ʱA[\x][\y] = A[x-1][y]+A[\x][y-1]
-     * 3ĽA[m-1][n-1]
-     * 
- * - * @param m - * @param n - * @return - */ - public int uniquePaths(int m, int n) { - int[][] result = new int[m][n]; - - // һеĽ - for (int i = 0; i < m; i++) { - result[i][0] = 1; - } - - // һеĽ - for (int i = 1; i < n; i++) { - result[0][i] = 1; - } - - // λõĽ - for (int i = 1; i < m; i++) { - for (int j = 1; j < n; j++) { - result[i][j] = result[i - 1][j] + result[i][j - 1]; - } - } - - // Ľ - return result[m - 1][n - 1]; - } -} diff --git "a/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221.iml" "b/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221/\343\200\220062\343\200\221\343\200\220UniquePaths\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221/\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221.iml" "b/\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221/\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221/\343\200\220063\343\200\221\343\200\220UniquePathsII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221.iml" "b/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221/\343\200\220064\343\200\221\343\200\220MinimumPathSum\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221/src/Solution.java" "b/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221/src/Solution.java" deleted file mode 100644 index baef319..0000000 --- "a/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221/src/Solution.java" +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:32 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given a non-negative number represented as an array of digits, plus one to the number.
-     * The digits are stored such that the most significant digit is at the head of the list.
-     *
-     * Ŀ
-     * һʾһмһ
-     * ÿһλ洢һλϡ±ӴСʾλӵλλ
-     *
-     * ˼·
-     * ֱ⣬һλ־carryֵΪ1ʾ1λʼtmp = a[x] + carry
-     * a[x] = tmp%10carry = tmp/10carryΪ0һλٽвֱеλcarray
-     * Ϊ0˳carrayΪ0˵Ҫչһλ
-     * 
- * - * @param digits - * @return - */ - public int[] plusOne(int[] digits) { - - int carry = 1; // λ־һλĽλ־ - int tmp; - for (int i = digits.length - 1; i >= 0; i--) { - tmp = digits[i]; - digits[i] = (tmp + carry) % 10; // 㵱ǰλֵ - carry = (tmp + carry) / 10; // µĽλ - - if (carry == 0) { // ûнλ˾Ϳ˳ - break; - } - } - - if (carry == 1) { // һλ - int[] result = new int[digits.length + 1]; - System.arraycopy(digits, 0, result, 1, digits.length); - result[0] = carry; - return result; - } else { - return digits; - } - } -} diff --git "a/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221.iml" "b/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221/\343\200\220066\343\200\221\343\200\220PlusOne\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221/\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221.iml" "b/\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221/\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221/\343\200\220067\343\200\221\343\200\220AddBinary\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221/src/Solution.java" "b/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221/src/Solution.java" deleted file mode 100644 index 0ac8cfa..0000000 --- "a/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221/src/Solution.java" +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Author: - * Date: 2015-07-25 - * Time: 09:10 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - public int climbStairs(int n) { - - int result = 0; - - // ֻһ - if (n == 1) { - result = 1; - } - // ֻ - else if (n == 2) { - result = 2; - } - // ¥ݽ2 - else if (n > 2) { - // еĽⷨ - int[] ways = new int[n]; - - ways[0] = 1; - ways[1] = 2; - - for (int i = 2; i < ways.length; i++) { - ways[i] = ways[i - 1] + ways[i - 2]; - } - - result = ways[ways.length - 1]; - } - - return result; - } -} diff --git "a/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221.iml" "b/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221/\343\200\220070\343\200\221\343\200\220ClimbingStairs\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221/src/Solution.java" "b/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221/src/Solution.java" deleted file mode 100644 index 1d25618..0000000 --- "a/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221/src/Solution.java" +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Author: - * Date: 2015-07-25 - * Time: 09:27 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - public void setZeroes(int[][] matrix) { - // һбõı־ - boolean rowFlag = false; - // һбõı־ - boolean colFlag = false; - - for (int i = 0; i < matrix.length; i++) { - for (int j = 0; j < matrix[0].length; j++) { - if (matrix[i][j] == 0) { - // ǵһҪ - if (i == 0) { - rowFlag = true; - } - - // ǵһҪ - if (j == 0){ - colFlag = true; - } - - // ڱҪΪ0к - matrix[0][j] = 0; - matrix[i][0] = 0; - } - } - } - - // ԵڶеڶпʼԪ0 - for (int i = 1; i < matrix.length; i++) { - for (int j = 1; j < matrix[0].length; j++) { - if (matrix[i][0] == 0 || matrix[0][j] == 0) { - matrix[i][j] = 0; - } - } - } - - // õһΪ0 - if (rowFlag) { - for (int j = 0; j < matrix[0].length; j++) { - matrix[0][j] = 0; - } - } - - // õһΪ0 - if (colFlag) { - for (int i = 0; i < matrix.length; i++) { - matrix[i][0] = 0; - } - } - - } -} diff --git "a/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221.iml" "b/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221/\343\200\220073\343\200\221\343\200\220SetMatrixZeroes\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221/src/Solution.java" "b/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221/src/Solution.java" deleted file mode 100644 index 65e7be7..0000000 --- "a/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221/src/Solution.java" +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:36 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
-     * Integers in each row are sorted from left to right.
-     * The first integer of each row is greater than the last integer of the previous row.
-     * For example,
-     * Consider the following matrix:Given target = 3, return true.
-     *
-     * [
-     *  [1,   3,  5,  7],
-     *  [10, 11, 16, 20],
-     *  [23, 30, 34, 50]
-     * ]
-     *
-     * Ŀ
-     * һάʵһ㷨ھʵֿkھk
-     * ʣÿһÿһжźģÿһеĵһһеһ
-     *
-     * ˼·
-     * ⷨһö鿴㷨ҵڵУö㷨ڵСҵͷtrue򷵻false
-     * 
- * - * @param matrix - * @param target - * @return - */ - public boolean searchMatrix(int[][] matrix, int target) { - - if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { - return false; - } - - int row = matrix.length; - int column = matrix[0].length; - int low = 0; - int high = row - 1; - int mid = 0; - - // ҽڵ - while (low <= high) { - mid = low + (high - low) / 2; - - if (target < matrix[mid][column - 1]) { - high = mid - 1; - } else if (target > matrix[mid][column - 1]) { - low = mid + 1; - } else { - return true; - } - } - - // ڵλ - int targetRow = mid; - if (matrix[mid][column - 1] < target) { - targetRow++; - } - - // Ŀг޽ - if (targetRow >= row) { - return false; - } - - low = 0; - high = column - 1; - // ڵУҵtrueûзfalse - while (low <= high) { - mid = low + (high - low) / 2; - - if (target < matrix[targetRow][mid]) { - high = mid - 1; - } else if (target > matrix[targetRow][mid]) { - low = mid + 1; - } else { - return true; - } - } - - return false; - } -} diff --git "a/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221.iml" "b/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221/\343\200\220074\343\200\221\343\200\220SearchA2DMatrix\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221/src/Solution.java" "b/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221/src/Solution.java" deleted file mode 100644 index 639fd06..0000000 --- "a/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221/src/Solution.java" +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:37 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given an array with n objects colored red, white or blue, sort them so that objects
-     * of the same color are adjacent, with the colors in the order red, white and blue.
-     * Here, we will use the integers 0, 1, and 2 to represent the color red, white,
-     * and blue respectively.
-     * Note:
-     * You are not suppose to use the librarys sort function for this problem.
-     *
-     * Ŀ
-     * һ飬Ǻɫɫɫɫ򣬺죬ף
-     * ʹ012ֱ죬ף
-     * ע⣺ʹÿ⺯
-     *
-     * ˼·
-     * ɨ裬¼1ĸĺ͡ɨԵó1Ŀt2Ŀ(sum-t)/2
-     * Եó0ĿӸ012Ŀٶֵ
-     * 
- * - * @param A - */ - public void sortColors(int[] A) { - - if (A == null) { - return; - } - - int count = 0; // ͳ1ĸ - int sum = 0; // ͳĺ - - for (int i : A) { - if (i == 1) { - count++; - } - - sum += i; - } - - sum = (sum - count) / 2; // 2Ŀ - - count = A.length - count - sum; // 1ʼֵλ - - sum = A.length - sum; // 2ʼֵλ - - for (int i = 0; i < count; i++) { - A[i] = 0; - } - - for (int i = count; i < sum; i++) { - A[i] = 1; - } - - for (int i = sum; i < A.length; i++) { - A[i] = 2; - } - } -} diff --git "a/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221.iml" "b/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221/\343\200\220075\343\200\221\343\200\220SortColors\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221/src/Solution.java" "b/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221/src/Solution.java" deleted file mode 100644 index 0e2f1db..0000000 --- "a/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221/src/Solution.java" +++ /dev/null @@ -1,79 +0,0 @@ -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-08-21 - * Time: 19:39 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - private List> result; - private List l; - - /** - *
-     * ԭ
-     * Given two integers n and k, return all possible combinations of k numbers out of 1  n.
-     * For example,
-     * If n = 4 and k = 2, a solution is:
-     *
-     * [
-     *  [2,4],
-     *  [3,4],
-     *  [2,3],
-     *  [1,2],
-     *  [1,3],
-     *  [1,4],
-     * ]
-     *
-     * Ŀ
-     * nk1-nkϡ
-     *
-     * ˼·
-     * õݹη⣬롣
-     * 
- * - * @param n - * @param k - * @return - */ - public List> combine(int n, int k) { - result = new LinkedList<>(); - - if (n > 0 && k > 0 && n >= k) { - l = new LinkedList<>(); - combine(1, n, k); - } - - return result; - } - - /** - * - * - * @param start ѡʼλ - * @param end ѡĽλ - * @param num [start, end]ѡĿ - */ - private void combine(int start, int end, int num) { - - if (num == 0) { - List tmp = new ArrayList<>(); - for (Integer i : l) { - tmp.add(i); - } - - result.add(tmp); - return; - } - - int endFirst = end - num + 1; // һѡֵ - for (int i = start; i <= endFirst; i++) { - l.add(i); - combine(i + 1, end, num - 1); - l.remove(new Integer(i)); - } - } -} diff --git "a/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221.iml" "b/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221/\343\200\220077\343\200\221\343\200\220Combinations\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221/src/Solution.java" "b/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221/src/Solution.java" deleted file mode 100644 index a270ee0..0000000 --- "a/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221/src/Solution.java" +++ /dev/null @@ -1,123 +0,0 @@ -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-08-21 - * Time: 19:41 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - private List> result; - private List l; - private int[] set; - private int num; // setлҪѡԪظ - - /** - *
-     * ԭ
-     * Given a set of distinct integers, nums, return all possible subsets.
-     * Note:
-     * Elements in a subset must be in non-descending order.
-     * The solution set must not contain duplicate subsets.
-     * For example,
-     * If nums = [1,2,3], a solution is:
-     *
-     * [
-     *  [3],
-     *  [1],
-     *  [2],
-     *  [1,2,3],
-     *  [1,3],
-     *  [2,3],
-     *  [1,2],
-     *  []
-     * ]
-     *
-     * Ŀ
-     * һֵͬ飬Ӽ
-     *
-     * ˼·
-     * ȶеԪؽȻõݹη⡣
-     * 
- * - * @param S - * @return - */ - public List> subsets(int[] S) { - result = new LinkedList<>(); - - if (S != null) { - l = new ArrayList<>(); - - // S - quickSort(S, 0, S.length - 1); - - set = S; - for (int i = 0; i <= S.length; i++) { - num = i; - subset(0); - } - } - - // գӿ - set = null; - l = null; - - return result; - } - - /** - * ԪظnumӼ - * - * @param start ʣҪѡnumԪУһС± - */ - public void subset(int start) { - if (num == 0) { - List tmp = new ArrayList<>(); - for (Integer i : l) { - tmp.add(i); - } - - result.add(tmp); - return; - } - - int endFirst = set.length - num; // ʣҪѡnumԪУһ± - for (int i = start; i <= endFirst; i++) { - l.add(set[i]); - num--; - subset(i + 1); - num++; - l.remove(new Integer(set[i])); - } - } - - private void quickSort(int[] arr, int lo, int hi) { - if (lo < hi) { - int mid = getMid(arr, lo, hi); - quickSort(arr, lo, mid - 1); - quickSort(arr, mid + 1, hi); - } - } - - private int getMid(int[] arr, int lo, int hi) { - int tmp = arr[lo]; - while (lo < hi) { - while (lo < hi && arr[hi] > tmp) { - hi--; - } - arr[lo] = arr[hi]; - - while (lo < hi && arr[lo] < tmp) { - lo++; - } - - arr[hi] = arr[lo]; - } - - arr[lo] = tmp; - return lo; - } -} diff --git "a/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221.iml" "b/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221/\343\200\220078\343\200\221\343\200\220Subsets\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/src/Main.java" "b/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/src/Main.java" deleted file mode 100644 index 2491d90..0000000 --- "a/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/src/Main.java" +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Author: - * Date: 2015-06-20 - * Time: 08:02 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - System.out.println(solution.exist(new char[][]{ - "abc".toCharArray(),"aed".toCharArray(),"afg".toCharArray() - }, "abcdefg")); - } -} diff --git "a/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/src/Solution.java" "b/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/src/Solution.java" deleted file mode 100644 index e510517..0000000 --- "a/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/src/Solution.java" +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Author: - * Date: 2015-06-20 - * Time: 07:19 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a 2D board and a word, find if the word exists in the grid.
-     *
-     * The word can be constructed from letters of sequentially adjacent cell,
-     * where "adjacent" cells are those horizontally or vertically neighboring.
-     * The same letter cell may not be used more than once.
-     *
-     * For example,
-     * Given board =
-     * [
-     *      ["ABCE"],
-     *      ["SFCS"],
-     *      ["ADEE"]
-     * ]
-     * word = "ABCCED", -> returns true,
-     * word = "SEE", -> returns true,
-     * word = "ABCB", -> returns false.
-     *
-     * Ŀ⣺
-     * һboardַ󣬿Դһ㿪ʼҵķʽߣÿֻһΣ
-     * һ·߹ַڸַôtrue
-     *
-     * ˼·
-     * ÿһΪ㣬ʹûݷ
-     * 
- * - * @param board - * @param word - * @return - */ - public boolean exist(char[][] board, String word) { - // עǼٶIJǺϷ - - // ʱǾ󣬳ʼֵĬϻΪfalse - boolean[][] visited = new boolean[board.length][board[0].length]; - - // ÿһλΪҵһ·ֹͣ - for (int i = 0; i < board.length; i++) { - for (int j = 0; j < board[0].length; j++) { - if (search(board, visited, i, j, word, new int[]{0})) { - return true; - } - } - } - - return false; - } - - /** - * @param board ַ - * @param visited ʱǾ - * @param row ʵк - * @param col ʵк - * @param word ƥַ - * @param idx ƥλãȡǸºֵԱ - * @return - */ - private boolean search(char[][] board, boolean[][] visited, int row, int col, String word, int[] idx) { - // λõִijȣ˵Ѿҵҵƥ - if (idx[0] == word.length()) { - return true; - } - - boolean hasPath = false; - // ǰλúϷ - if (check(board, visited, row, col, word, idx[0])) { - // λñʹ - visited[row][col] = true; - idx[0]++; - // ϣң£ĸ - hasPath = search(board, visited, row - 1, col, word, idx ) // - || search(board, visited, row, col + 1, word, idx) // - || search(board, visited, row + 1, col, word, idx) // - || search(board, visited, row, col - 1, word, idx); // - - - // ûҵ·ͻ - if (!hasPath) { - visited[row][col] = false; - idx[0]--; - } - } - - return hasPath; - } - - /** - * жʵλǷϷ - * - * @param board ַ - * @param visited ʱǾ - * @param row ʵк - * @param col ʵк - * @param word ƥַ - * @param idx ƥλ - * @return - */ - - public boolean check(char[][] board, boolean[][] visited, int row, int col, String word, int idx) { - return row >= 0 && row < board.length // кźϷ - && col >= 0 && col < board[0].length // кźϷ - && !visited[row][col] // ûбʹ - && board[row][col] == word.charAt(idx); // ַ - } -} diff --git "a/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221.iml" "b/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221/\343\200\220079\343\200\221\343\200\220WordSearch\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/src/Main.java" "b/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/src/Main.java" deleted file mode 100644 index e6ee29f..0000000 --- "a/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/src/Main.java" +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Author: - * Date: 2015-06-21 - * Time: 16:38 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - System.out.println(solution.search(new int[]{1, 1, 3, 1}, 3)); -// System.out.println(solution.findMinIndex(new int[]{1, 1, 3, 1})); - } -} diff --git "a/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/src/Solution.java" "b/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/src/Solution.java" deleted file mode 100644 index 3a86418..0000000 --- "a/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/src/Solution.java" +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Author: - * Date: 2015-06-21 - * Time: 14:46 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Follow up for "Search in Rotated Sorted Array":
-     * What if duplicates are allowed?
-     * Would this affect the run-time complexity? How and why?
-     * Write a function to determine if a given target is in the array
-     *
-     * Ŀ⣺
-     * "תֵ"ĺеֵظ
-     * дһȷһֵǷ
-     * 
- * @param nums - * @param target - * @return - */ - public boolean search(int[] nums, int target) { - if (nums != null && nums.length > 0) { - // СԪضӦ± - int minIndex = findMinIndex(nums); - - // ȫ - if (minIndex == 0) { - return binarySearch(nums, 0, nums.length - 1, target); - } - // ֲ, 4 5 6 7 8 9 0 1 2 3 - else { - // úͺһһԪȣضӦ± - if (nums[nums.length - 1] == target) { - return true; - } - // targetںһ - else if (nums[nums.length - 1] > target) { - return binarySearch(nums, minIndex, nums.length - 1, target); - } - // targetǰһ - else { - return binarySearch(nums, 0, minIndex - 1, target); - } - } - } - - return false; - } - - /** - * - * - * @param nums - * @param start ʼλ - * @param end λ - * @param target Ŀ - * @return trueҵfalseûҵ - */ - public boolean binarySearch(int[] nums, int start, int end, int target) { - - int mid; - while (start <= end) { - mid = start + ((end - start) >> 1); - - if (nums[mid] == target) { - return true; - } else if (nums[mid] > target) { - end = mid - 1; - } else { - start = mid + 1; - } - } - - return false; - } - - - public int findMinIndex(int[] nums) { - // У - if (nums == null || nums.length < 1) { - throw new IllegalArgumentException(); - } - - int lo = 0; - int hi = nums.length - 1; - int mid = 0; - - // ųȫ - while (nums[lo] >= nums[hi]) { - // ֻԪأغһ - if (hi - lo == 1) { - mid = hi; - break; - } - - mid = lo + ((hi - lo) >> 1); - - if (nums[mid] == nums[lo] && nums[mid] == nums[hi]) { - // ֻܲ˳ܲlo++hi--ķʽ - // Ϊloǰһһ - // hiҲǺһĵһ - return sequenceSearchMinIndex(nums, lo, hi); - } - - // midǰһ - if (nums[mid] >= nums[lo]) { - lo = mid; - } - // midںһ - else if (nums[mid] <= nums[hi]) { - hi = mid; - } - } - - return mid; - } - - /** - * ˳еСֵ±꣬nums鰴ijת - * - * @param nums - * @param start ʼλ - * @param end λ - * @return Сֵ± - */ - public int sequenceSearchMinIndex(int[] nums, int start, int end) { - for (int i = start; i < end; i++) { - if (nums[i] > nums[i + 1]) { - return i + 1; - } - } - return start; - } -} diff --git "a/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221.iml" "b/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221/\343\200\220081\343\200\221\343\200\220SearchInRotatedSortedArraII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/src/Solution.java" "b/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/src/Solution.java" deleted file mode 100644 index 9a0c9a6..0000000 --- "a/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/src/Solution.java" +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:43 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given a sorted linked list, delete all nodes that have duplicate numbers,
-     * leaving only distinct numbers from the original list.
-     * For example,
-     * Given 1->2->3->3->4->4->5, return 1->2->5.
-     * Given 1->1->1->2->3, return 2->3.
-     *
-     * Ŀ
-     * һźĵɾظԪءֻֻһֵԪء
-     *
-     * ˼·
-     * һrootrootӵԭͷͷ͸ָ룬صԪؽɾ
-     * 
- * - * @param head - * @return - */ - public ListNode deleteDuplicates(ListNode head) { - - ListNode root = new ListNode(0); // ͷ - root.next = head; - ListNode p = head; - ListNode q = root; // ¼һûظԪأʼָͷ - - int delta = 0; // Ԫظ - - while (p != null && p.next != null) { - if (p.val == p.next.val) { // ͬ - delta++; - p = p.next; // ƶһ - } else { // 㲻ͬ - if (delta == 0) { // ֵΪp.valĽûظ - q.next = p; // ӵûиԪ - q = p; // ָһδظԪ - p = p.next; // ƶһ - } else { // ֵΪp.valĽظ - p = p.next; // ƶһԪ - q.next = p.next; // ȥظԪ - delta = 0; // ԪظΪ0 - } - } - } - - if (delta != 0) { // һԪǸľȥ - q.next = null; - } else { // ûظͿӵβ - q.next = p; - } - - return root.next; - } -} diff --git "a/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221.iml" "b/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221/\343\200\220082\343\200\221\343\200\220RemoveDuplicatesFromSortedListII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/src/Solution.java" "b/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/src/Solution.java" deleted file mode 100644 index abd32b4..0000000 --- "a/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/src/Solution.java" +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:45 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * 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.
-     *
-     * Ŀ
-     * һɾظԪأֻͬһ
-     *
-     * ˼·
-     * ʹһָָͷһ뵱ǰĽɾֱһͬģָָ
-     * µĽ㣬ظֱеĽ㶼ꡣ
-     * 
- * - * @param head - * @return - */ - public ListNode deleteDuplicates(ListNode head) { - ListNode point; - ListNode tail = head; // ָ½βʼʱֻһԪأͷ - - if (head != null) { - point = head.next; // ָһͷ - while (point != null) { // һδĩβ - - if (tail.val != point.val) { // βڵ㲻ͬͽͬĽڵӵtailһλ - tail.next = point; - tail = tail.next; // ָβ - } - - point = point.next; - } - - tail.next = null; // βָ - } - - return head; - } -} diff --git "a/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221.iml" "b/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221/\343\200\220083\343\200\221\343\200\220RemoveDuplicatesFromSortedList\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/src/ListNode.java" "b/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/src/ListNode.java" deleted file mode 100644 index b0946e7..0000000 --- "a/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/src/ListNode.java" +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 17:18 - * Declaration: All Rights Reserved !!! - */ -public class ListNode { - int val; - ListNode next; - ListNode(int x) { val = x; } -} diff --git "a/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/src/Solution.java" "b/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/src/Solution.java" deleted file mode 100644 index 1ba57eb..0000000 --- "a/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/src/Solution.java" +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 17:18 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given a linked list and a value x, partition it such that all nodes less
-     * than x come before nodes greater than or equal to x.
-     * You should preserve the original relative order of the nodes in each of
-     * the two partitions.
-     *
-     * For example,
-     * Given 1->4->3->2->5->2 and x = 3,
-     * return 1->2->2->4->3->5.
-     *
-     * Ŀ
-     * һһֵxֳСڵxIJֺʹxIJ֡ͬʱԭ˳
-     *
-     * ˼·
-     * abԭеÿ㣬СڵxĽaĩβǴھͷb
-     * ĩβbͷӵaĩβ
-     * 
- * - * @param head - * @param x - * @return - */ - public ListNode partition(ListNode head, int x) { - - ListNode le = new ListNode(0); // Сx - ListNode ge = new ListNode(0); // ڵx - ListNode t1 = le; - ListNode t2 = ge; - ListNode p = head; - - while (p != null) { - if (p.val < x) { - t1.next = p; - t1 = p; - } else { - t2.next = p; - t2 = p; - } - p = p.next; - } - - t2.next = null; - - // ˵Сڵ - if (t1 != le) { - t1.next = ge.next; - head = le.next; - } else { - head = ge.next; - } - return head; - } -} diff --git "a/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221.iml" "b/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221/\343\200\220086\343\200\221\343\200\220PartitionList\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221/src/Solution.java" "b/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221/src/Solution.java" deleted file mode 100644 index 1a4970c..0000000 --- "a/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221/src/Solution.java" +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 17:20 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * 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.
-     *
-     * Ŀ
-     * 飬кϲϲҲģϲnums1С
-     * nums1㹻Ŀռnums2
-     *
-     * ˼·
-     * еһλÿʼкϲнϴƶλãǸ
-     * λֵǰƶһλãٽͬIJֱеԪشꡣ
-     * 
- * - * @param A - * @param m - * @param B - * @param n - */ - public void merge(int A[], int m, int B[], int n) { - int pa = m - 1; - int pb = n - 1; - int index = m + n - 1; - - while (pa >= 0 && pb >= 0) { - if (A[pa] >= B[pb]) { - A[index--] = A[pa--]; - } else { - A[index--] = B[pb--]; - } - } - - while (pb >= 0) { // ˵paһΪ0 - A[index--] = B[pb--]; - } - - // pa >= 0˵[0, pa]ûнжϣΪ[0, pa]AУԲҪƶ - } -} diff --git "a/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221.iml" "b/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221/\343\200\220088\343\200\221\343\200\220MergeSortedArray\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/src/Main.java" "b/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/src/Main.java" deleted file mode 100644 index ba43581..0000000 --- "a/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/src/Main.java" +++ /dev/null @@ -1,18 +0,0 @@ -import java.util.List; - -/** - * Author: - * Date: 2015-06-22 - * Time: 13:27 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - List result = solution.grayCode(2); - - for (Integer i: result) { - System.out.printf("%s\n", Integer.toBinaryString(i)); - } - } -} diff --git "a/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/src/Solution.java" "b/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/src/Solution.java" deleted file mode 100644 index 4a53251..0000000 --- "a/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/src/Solution.java" +++ /dev/null @@ -1,62 +0,0 @@ -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-06-22 - * Time: 13:16 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * The gray code is a binary numeral system where two successive values differ in only one bit.
-     * Given a non-negative integer n representing the total number of bits in the code, print the
-     * sequence of gray code. A gray code sequence must begin with 0.
-     *
-     * For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
-     * 00 - 0
-     * 01 - 1
-     * 11 - 3
-     * 10 - 2
-     *
-     * Note:
-     *   - For a given n, a gray code sequence is not uniquely defined.
-     *   - For example, [0,2,3,1] is also a valid gray code sequence according to the above
-     *          definition.
-     *   - For now, the judge is able to judge based on one instance of gray code sequence.
-     *          Sorry about that.
-     *
-     * Ŀ⣺
-     * nΪnĸ
-     * ˼·
-     * ݹ
-     *  ַڸǷʵõݹ¹죺
-     *  1λ
-     *  (n+1)λеǰ2nֵnλ֣˳дǰ׺0
-     *  (n+1)λеĺ2nֵnλ֣дǰ׺1
-     * 
- * - * @param n - * @return - */ - public List grayCode(int n) { - List result = new LinkedList<>(); - if (n >= 0) { - // ǰ벿 - result.add(0); - // λֵ0ʱ - int t = 1; - // ÿһѭλi+1λĸ൱ڳΪi+1λĸǰ벿 - for (int i = 0; i < n; i++) { - // ijΪi+1λĺ벿֣ǰ벿ɳΪiλĸ - for (int j = result.size() - 1; j >= 0; j--) { - result.add(result.get(j) ^ t); - } - // λ - t <<= 1; - } - } - return result; - } -} diff --git "a/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221.iml" "b/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221/\343\200\220089\343\200\221\343\200\220GrayCode\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/src/ListNode.java" "b/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/src/ListNode.java" deleted file mode 100644 index 69ec703..0000000 --- "a/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/src/ListNode.java" +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 17:23 - * Declaration: All Rights Reserved !!! - */ -public class ListNode { - int val; - ListNode next; - ListNode(int x) { val = x; } -} diff --git "a/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/src/Solution.java" "b/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/src/Solution.java" deleted file mode 100644 index ad51ffe..0000000 --- "a/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/src/Solution.java" +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 17:23 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Reverse a linked list from position m to n. Do it in-place and in one-pass.
-     * For example:
-     * Given 1->2->3->4->5->NULL, m = 2 and n = 4,
-     * return 1->4->3->2->5->NULL.
-     * Note:
-     * Given m, n satisfy the following condition:
-     * 1  m  n  length of list.
-     *
-     * Ŀ
-     * һmn֮Ԫؽת
-     * nmǺϷģʹԭطнʹóռ䣩
-     *
-     * ˼·
-     * ҵһҪתԪصǰprevټҪзתԪظԪؽͷ巨
-     * prev棬ͬʱϿ
-     * 
- * - * @param head - * @param m - * @param n - * @return - */ - public ListNode reverseBetween(ListNode head, int m, int n) { - - ListNode root = new ListNode(0); - ListNode p = root; - root.next = head; - - for (int i = 1; i < m && p != null; i++) { - p = p.next; - } - - if (p != null) { - ListNode q = p.next; - ListNode r; - - // mΪΪǴӵһʼ - if (m < 1) { - m = 1; - } - - n = n - m + 1; // nΪҪĽĿ - // ʱҪʹβ巨βĸΪn-1 - for (int i = 1; i < n && q.next != null; i++) { - // ΪҪβĽ - r = q.next; - - // qĺβ - q.next = r.next; - r.next = p.next; - p.next = r; - } - - head = root.next; - } - - return head; - } -} diff --git "a/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221.iml" "b/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221/\343\200\220092\343\200\221\343\200\220ReverseLinkedListII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/src/Solution.java" "b/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/src/Solution.java" deleted file mode 100644 index 012d8ed..0000000 --- "a/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/src/Solution.java" +++ /dev/null @@ -1,33 +0,0 @@ -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-07-25 - * Time: 18:19 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - public List inorderTraversal(TreeNode root) { - - List result = new LinkedList<>(); - LinkedList stack = new LinkedList<>(); - TreeNode node = root; - - while (node != null || !stack.isEmpty()) { - while (node != null) { - stack.addLast(node); - node = node.left; - } - - if (!stack.isEmpty()) { - node = stack.removeLast(); - result.add(node.val); - node = node.right; - } - } - - System.out.println(result); - return result; - } -} diff --git "a/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221.iml" "b/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221/\343\200\220094\343\200\221\343\200\220BinaryTree InorderTraversal\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/src/Solution.java" "b/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/src/Solution.java" deleted file mode 100644 index b2ee0d9..0000000 --- "a/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/src/Solution.java" +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Author: - * Date: 2015-06-18 - * Time: 17:36 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? - * - * For example, - * Given n = 3, there are a total of 5 unique BST's. - * 1 3 3 2 1 - * \ / / / \ \ - * 3 2 1 1 3 2 - * / / \ \ - * 2 1 2 3 - * - * ƹʽ - * f(k)*f(n-1-k)f(k)ʾk㣬е״f(k)f(n-1-k)ʾn-1-k - * - * f(n) = 2*f(n-1) + f(1)*f(n-2) + f(2)f(n-3) + f(3)f(n-4) + ... +f(n-2)*f(1) - * - * @param n - * @return - */ - public int numTrees(int n) { - - if (n <= 0) { - return 0; - } else if (n == 1) { - return 1; - } - - int[] result = new int[n + 1]; - result[0] = 0; - result[1] = 1; - - - // f(2)...f(n) - for (int i = 2; i <= n; i++) { - // f(i) - result[i] = 2 * result[i - 1]; - for (int j = 1; j <= i - 1 ; j++) { - result[i] += result[j]*result[i - 1 -j]; - } - - } - return result[n]; - } -} diff --git "a/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221.iml" "b/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221/\343\200\220096\343\200\221\343\200\220UniqueBinarySearchTrees\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221.iml" "b/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221/\343\200\220098\343\200\221\343\200\220ValidateBinarySearchTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/src/TreeNode.java" "b/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/src/TreeNode.java" deleted file mode 100644 index 58ea6f4..0000000 --- "a/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/src/TreeNode.java" +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 18:40 - * Declaration: All Rights Reserved !!! - */ -public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } -} diff --git "a/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221.iml" "b/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221/\343\200\220100\343\200\221\343\200\220SameTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221.iml" "b/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221/\343\200\220101\343\200\221\343\200\220SymmetricTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221.iml" "b/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221/\343\200\220102\343\200\221\343\200\220BinaryTreeLevelOrderTraversal\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221.iml" "b/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221/\343\200\220103\343\200\221\343\200\220BinaryTreeZigzagLevelOrderTraversal\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221.iml" "b/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221/\343\200\220104\343\200\221\343\200\220MaximumDepthOfBinaryTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/src/Solution.java" "b/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/src/Solution.java" deleted file mode 100644 index c639a9c..0000000 --- "a/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/src/Solution.java" +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Author: - * Date: 2015-06-23 - * Time: 14:04 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given preorder and inorder traversal of a tree, construct the binary tree.
-     *
-     * Note:
-     * You may assume that duplicates do not exist in the tree.
-     *
-     * Ŀ⣺
-     * һǰУһ
-     * ע⣺
-     *   - ԪظԪ
-     *
-     * ˼·
-     * ǰһԪǸ㣨kֵΪk±idx
-     * idxзֳǰҲһɽеݹ
-     * 
- * - * @param preorder - * @param inorder - * @return - */ - public TreeNode buildTree(int[] preorder, int[] inorder) { - - // У - if (preorder == null || inorder == null || preorder.length == 0 - || preorder.length != inorder.length) { - return null; - } - return solve(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); - } - - /** - * ȷԼ֤ - * - * @param preorder Ľ - * @param x Ŀʼλ - * @param y Ľλ - * @param inorder Ľ - * @param i Ŀʼλ - * @param j Ľλ - * @return ĸ - */ - public TreeNode solve(int[] preorder, int x, int y, int[] inorder, int i, int j) { - - if (x >= 0 && x <= y && i >= 0 && i <= j) { - // ֻһԪ - if (x == y) { - return new TreeNode(preorder[x]); - } else if (x < y) { - // ¼ - int idx = i; - while (idx <= j && inorder[idx] != preorder[x]) { - idx++; - } - - // - TreeNode root = new TreeNode(inorder[idx]); - - // Ľ - int leftLength = idx - i; - // - if (leftLength > 0) { - // x + 1, x + leftLengthʼͽλ - root.left = solve(preorder, x + 1, x + leftLength, inorder, i, idx - 1); - } - - // Ľ - int rightLength = j - idx; - if (rightLength > 0) { - // x + leftLength + 1, yʼͽλ - root.right = solve(preorder, x + leftLength + 1, y, inorder, idx + 1, j); - } - return root; - } - } - - return null; - } -} diff --git "a/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221.iml" "b/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221/\343\200\220105\343\200\221\343\200\220ConstructBinaryTreeFromPreorderAndInorderTraversal\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/Main.java" "b/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/Main.java" deleted file mode 100644 index 232e3c8..0000000 --- "a/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/Main.java" +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Author: - * Date: 2015-06-23 - * Time: 10:32 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - int[] inorder = {1,2,3,4}; - int[] postorder = {3,2,4,1}; - - TreeNode root = solution.buildTree(inorder, postorder); - print(root); - } - - public static void print(TreeNode root) { - if (root != null) { - print(root.left); - System.out.print(root.val + " "); - print(root.right); - } - } -} diff --git "a/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/Solution.java" "b/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/Solution.java" deleted file mode 100644 index 351a346..0000000 --- "a/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/src/Solution.java" +++ /dev/null @@ -1,92 +0,0 @@ - -/** - * Author: - * Date: 2015-06-23 - * Time: 10:05 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given inorder and postorder traversal of a tree, construct the binary tree.
-     *
-     * Note:
-     * You may assume that duplicates do not exist in the tree.
-     *
-     * Ŀ⣺
-     * һͺУһö
-     * ע⣺
-     * ûظԪ
-     *
-     * ˼·
-     * һԪؾĸ(ֵΪr)
-     * ֵΪrλidxidxзΪ
-     * ӦԽзݹ
-     * 
- * - * @param inorder - * @param postorder - * @return - */ - public TreeNode buildTree(int[] inorder, int[] postorder) { - - // - if (inorder == null || postorder == null || inorder.length == 0 - || inorder.length != postorder.length) { - return null; - } - - // - return solve(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); - } - - /** - * - * - * @param inorder Ľ - * @param x Ŀʼλ - * @param y Ľλ - * @param postorder Ľ - * @param i Ŀʼλ - * @param j Ľλ - * @return - */ - public TreeNode solve(int[] inorder, int x, int y, int[] postorder, int i, int j) { - - if (x >= 0 && x <= y && i >= 0 && i <= j) { - // ֻһԪأʱҲi=jɣ - if (x == y) { - return new TreeNode(postorder[j]); - } - // һԪأʱҲi 0) { - // i, i + leftLength - 1ǰʼλ - root.left = solve(inorder, x, idx - 1, postorder, i, i + leftLength - 1); - } - - // ǿգ - int rightLength = y - idx; - if (rightLength > 0) { - // i + leftLength, j - 1ǰʼλ - root.right = solve(inorder, idx + 1, y, postorder, i + leftLength, j - 1); - } - - return root; - } - } - - return null; - } -} diff --git "a/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221.iml" "b/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221/\343\200\220106\343\200\221\343\200\220ConstructBinaryTreeFromInorderAndPostorderTraversal\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221.iml" "b/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221/\343\200\220107\343\200\221\343\200\220BinaryTreeLevelOrderTraversalII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221.iml" "b/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221/\343\200\220108\343\200\221\343\200\220ConvertSortedArrayToBinarySearchTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221.iml" "b/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221/\343\200\220109\343\200\221\343\200\220ConvertSortedListToBinarySearchTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221.iml" "b/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221/\343\200\220110\343\200\221\343\200\220BalancedBinaryTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/src/Solution.java" "b/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/src/Solution.java" deleted file mode 100644 index beab356..0000000 --- "a/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/src/Solution.java" +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 18:51 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - private int min = Integer.MAX_VALUE; // ¼С - private int cur = 0; // iǰij - - /** - *
-     * ԭ
-     * 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.
-     *
-     * Ŀ
-     * һСȡ
-     *
-     * ˼·
-     * бҳСȡ
-     * 
- * - * @param root - * @return - */ - public int minDepth(TreeNode root) { - - depth(root); - return min; - } - - /** - * - * - * @param node ǰ - */ - private void depth(TreeNode node) { - - if (node == null) { - min = cur; - return; - } - - cur++; // ǰIJμ1 - // Ҷڵ㣬·ȼ¼СС - if (node.left == null && node.right == null && cur < min) { - min = cur; // Сֵ - } - // - if (node.left != null) { - depth(node.left); - } - - // - if (node.right != null) { - depth(node.right); - } - - cur--; // ԭ - - } -} diff --git "a/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221.iml" "b/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221/\343\200\220111\343\200\221\343\200\220MinimumDepthOfBinaryTree\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221.iml" "b/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221.iml" deleted file mode 100644 index 5c38831..0000000 --- "a/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221/\343\200\220112\343\200\221\343\200\220PathSum\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221.iml" "b/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221/\343\200\220113\343\200\221\343\200\220PathSumII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/src/TreeNode.java" "b/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/src/TreeNode.java" deleted file mode 100644 index c988e88..0000000 --- "a/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/src/TreeNode.java" +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:02 - * Declaration: All Rights Reserved !!! - */ -public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } -} diff --git "a/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221.iml" "b/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221/\343\200\220114\343\200\221\343\200\220FlattenBinaryTreeToLinkedList\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221.iml" "b/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221/\343\200\220116\343\200\221\343\200\220PopulatingNextRightPointersinEachNode \343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221.iml" "b/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221/\343\200\220117\343\200\221\343\200\220PopulatingNextRightPointersInEachNodeII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221/\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221.iml" "b/\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221/\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221/\343\200\220118\343\200\221\343\200\220Pascal'sTriangle\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221/\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221.iml" "b/\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221/\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221/\343\200\220119\343\200\221\343\200\220Pascal'sTriangleII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221.iml" "b/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221/\343\200\220120\343\200\221\343\200\220Triangle\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221/src/Solution.java" "b/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221/src/Solution.java" deleted file mode 100644 index f779c93..0000000 --- "a/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221/src/Solution.java" +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Author: - * Date: 2015-06-22 - * Time: 15:42 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Say you have an array for which the ith 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.
-     *
-     * Ŀ⣺
-     * һprices[]prices[i]Ʊڵiۼֻۣһν(һ)ܵõ档
-     *
-     * ˼·
-     * ֻҪҳIJֵɣ max(prices[j] C prices[i]) i < jһαɣڱʱñ
-     * low¼ prices[o....i] еСֵǵǰΪֹۼۣʱ临ӶΪ O(n)
-     * 
- * - * @param prices - * @return - */ - public int maxProfit(int[] prices) { - - if (prices == null || prices.length < 1) { - return 0; - } - - int min = prices[0]; - int profit = 0; - - // iļ۸ԿҲԿ - for (int i = 1; i < prices.length; i++) { - // ҵ͵ - if (min > prices[i]) { - // - min = prices[i]; - } - // ļ۸񲻵 - else { - // ļ۸֮ǰļ۸ - if (profit < prices[i] - min) { - // - profit = prices[i] - min; - } - } - } - - return profit; - } -} diff --git "a/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221.iml" "b/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221/\343\200\220121\343\200\221\343\200\220BestTimeToBuyAndSellStock\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220124\346\234\252\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221/\343\200\220124\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221.iml" "b/\343\200\220124\346\234\252\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221/\343\200\220124\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220124\346\234\252\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221/\343\200\220124\343\200\221\343\200\220BinaryTreeMaximumPathSum\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221/\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221.iml" "b/\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221/\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221/\343\200\220125\343\200\221\343\200\220ValidPalindrome\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220127\346\234\252\343\200\221\343\200\220WordLadder\343\200\221/src/Solution.java" "b/\343\200\220127\346\234\252\343\200\221\343\200\220WordLadder\343\200\221/src/Solution.java" deleted file mode 100644 index 5880a2f..0000000 --- "a/\343\200\220127\346\234\252\343\200\221\343\200\220WordLadder\343\200\221/src/Solution.java" +++ /dev/null @@ -1,53 +0,0 @@ -import java.util.Set; - -/** - * Author: - * Date: 2015-06-20 - * Time: 08:11 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given two words (beginWord and endWord), and a dictionary, find the length
-     * of shortest transformation sequence from beginWord to endWord, such that:
-     *
-     *   - Only one letter can be changed at a time
-     *   - Each intermediate word must exist in the dictionary
-     *
-     * For example,
-     *
-     * Given:
-     * start = "hit"
-     * end = "cog"
-     * dict = ["hot","dot","dog","lot","log"]
-     * As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
-     * return its length 5.
-     *
-     * Note:
-     *   - Return 0 if there is no such transformation sequence.
-     *   - All words have the same length.
-     *   - All words contain only lowercase alphabetic characters.
-     *
-     * Ŀ⣺
-     * ʣbeginWordendWordһֵ䣬ҴbeginWordת͵endWord̳ȣ
-     *   - һֻһĸԱı
-     *   - ÿмֱڴʵ
-     *
-     * ע⣺
-     *   - ı任У0
-     *   - еʾͬijȡ
-     *   - еֻСдĸַ
-     *
-     * ˼·
-     * 
- * - * @param beginWord - * @param endWord - * @param wordDict - * @return - */ - public int ladderLength(String beginWord, String endWord, Set wordDict) { - return 0; - } -} diff --git "a/\343\200\220127\346\234\252\343\200\221\343\200\220WordLadder\343\200\221/\343\200\220127\343\200\221\343\200\220WordLadder\343\200\221.iml" "b/\343\200\220127\346\234\252\343\200\221\343\200\220WordLadder\343\200\221/\343\200\220127\343\200\221\343\200\220WordLadder\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220127\346\234\252\343\200\221\343\200\220WordLadder\343\200\221/\343\200\220127\343\200\221\343\200\220WordLadder\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221.iml" "b/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221/\343\200\220129\343\200\221\343\200\220SumRootToLeafNumbers\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/src/Main.java" "b/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/src/Main.java" deleted file mode 100644 index 6ebf6cb..0000000 --- "a/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/src/Main.java" +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Author: - * Date: 2015-06-22 - * Time: 10:02 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { -// test01(); -// test02(); -// test03(); - test04(); - } - - - private static void test01() { - Solution solution = new Solution(); - char[][] board = { - "XXXX".toCharArray(), - "XOOX".toCharArray(), - "XXOX".toCharArray(), - "XOXX".toCharArray() - }; - - solution.solve(board); - - for (char[] line : board) { - System.out.println(new String(line)); - } - } - - private static void test02() { - Solution solution = new Solution(); - char[][] board = { - "XOXX".toCharArray(), - "OXOX".toCharArray(), - "XOXO".toCharArray(), - "OXOX".toCharArray(), - "XOXO".toCharArray(), - "OXOX".toCharArray() - }; - - solution.solve(board); - - for (char[] line : board) { - System.out.println(new String(line)); - } - } - - private static void test03() { - Solution solution = new Solution(); - char[][] board = { - "OO".toCharArray(), - "OO".toCharArray() - }; - - solution.solve(board); - - for (char[] line : board) { - System.out.println(new String(line)); - } - } - - private static void test04() { - Solution solution = new Solution(); - char[][] board = { - "OOO".toCharArray(), - "OOO".toCharArray(), - "OOO".toCharArray() - }; - - solution.solve(board); - - for (char[] line : board) { - System.out.println(new String(line)); - } - } -} diff --git "a/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/src/Solution.java" "b/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/src/Solution.java" deleted file mode 100644 index 4b460f9..0000000 --- "a/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/src/Solution.java" +++ /dev/null @@ -1,258 +0,0 @@ -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-06-22 - * Time: 08:51 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
-     * A region is captured by flipping all 'O's into 'X's in that surrounded region.
-     *
-     * For example,
-     * X X X X
-     * X O O X
-     * X X O X
-     * X O X X
-     *
-     * After running your function, the board should be:
-     * X X X X
-     * X X X X
-     * X X X X
-     * X O X X
-     *
-     * Ŀ⣺
-     * һά񣬰'X''O'ԱXΧOX
-     * ˼·
-     * ùȱķʽҲԲóȵķʽջ,dzеıΧĵ㣬ʣµľDzΧĵ
-     * 
- * - * @param board - */ - //////////////////////////////////////////////////////////////////////////////////////////////// - // ùȶȱķʽҳеġΧĵ - //////////////////////////////////////////////////////////////////////////////////////////////// - public void solve(char[][] board) { - // У - if (board == null || board.length < 1 || board[0].length < 1) { - return; - } - - boolean[][] visited = new boolean[board.length][board[0].length]; - // ʱΧһȦԪ - List round = new LinkedList<>(); - // - for (int col = 0; col < board[0].length; col++) { - // УҵOҵδʹ - if (!visited[0][col] && board[0][col] == 'O') { - round.clear(); - round.add(new Coordinate(0, col)); - bfs(board, visited, round); - } - } - - // ײ - for (int col = 0; col < board[0].length; col++) { - // УҵOҵδʹ - if (!visited[board.length - 1][col] && board[board.length - 1][col] == 'O') { - round.clear(); - round.add(new Coordinate(board.length - 1, col)); - bfs(board, visited, round); - } - } - - // - for (int row = 1; row < board.length - 1; row++) { - // УҵOҵδʹ - if (!visited[row][0] && board[row][0] == 'O') { - round.clear(); - round.add(new Coordinate(row, 0)); - bfs(board, visited, round); - } - } - - // ұ - for (int row = 1; row < board.length - 1; row++) { - // УҵOҵδʹ - if (!visited[row][board[0].length - 1] && board[row][board[0].length - 1] == 'O') { - round.clear(); - round.add(new Coordinate(row, board[0].length - 1)); - bfs(board, visited, round); - } - } - - // - for (int i = 0; i < board.length; i++) { - for (int j = 0; j < board[0].length; j++) { - // δʹֿܣһX㣬ڶO㣬OһDZXΧ - // ʱδʹĵΪXȷ - if (!visited[i][j]) { - board[i][j] = 'X'; - } - } - } - } - - /** - * ȣҲΧĵ - * - * @param board ά - * @param visited ʱ - * @param round ʱΧһȦԪ - */ - public void bfs(char[][] board, boolean[][] visited, List round) { - Coordinate c; - while (round.size() > 0) { - c = round.remove(0); - if (c.x >= 0 && c.x < board.length && c.y >= 0 && c.y < board[0].length && board[c.x][c.y] == 'O' && !visited[c.x][c.y]) { - visited[c.x][c.y] = true; - round.add(new Coordinate(c.x - 1, c.y)); - round.add(new Coordinate(c.x, c.y + 1)); - round.add(new Coordinate(c.x + 1, c.y)); - round.add(new Coordinate(c.x, c.y - 1)); - } - } - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // ùȶȱķʽҳеıΧĵ㣬ұǻᳬʱ - //////////////////////////////////////////////////////////////////////////////////////////////// - public void solve2(char[][] board) { - // У - if (board == null || board.length < 1 || board[0].length < 1) { - return; - } - - boolean[][] visited = new boolean[board.length][board[0].length]; - - // ʱΧһȦԪ - List round = new LinkedList<>(); - // Ԫ - List all = new LinkedList<>(); - - for (int i = 0; i < board.length; i++) { - for (int j = 0; j < board[0].length; j++) { - if (!visited[i][j] && board[i][j] == 'O') { - // һȦԪ - round.add(new Coordinate(i, j)); - boolean result = bfs(board, visited, round, all); - // һOڣҲڱ߽ - if (result) { - // ñ - for (Coordinate c : all) { - board[c.x][c.y] = 'X'; - } - } - - // Ԫ - round.clear(); - all.clear(); - } - } - } - - } - - /** - * ȱ - * - * @param board ά - * @param visited ʱ - * @param round ʱΧһȦԪ - * @param all Ԫ - * @return trueOڣҲڱ߽ϣXܷtrue - */ - public boolean bfs(char[][] board, boolean[][] visited, List round, List all) { - boolean result = true; - int size = round.size(); - Coordinate c; - while (size > 0) { - size--; - - // ȡԪ - c = round.remove(0); - // ӵ¼Ԫؼ - all.add(c); - // Ѿʹ - visited[c.x][c.y] = true; - // жcǷOڵ - result &= isInner(board, c.x, c.y); - - // cһǷOûзʹӵround - if (isO(board, c.x - 1, c.y) && !visited[c.x - 1][c.y]) { - round.add(new Coordinate(c.x - 1, c.y)); - } - - // cһǷOûзʹӵround - if (isO(board, c.x, c.y + 1) && !visited[c.x][c.y + 1]) { - round.add(new Coordinate(c.x, c.y + 1)); - } - - // cһǷOûзʹӵround - if (isO(board, c.x + 1, c.y) && !visited[c.x + 1][c.y]) { - round.add(new Coordinate(c.x + 1, c.y)); - } - - // cһǷOûзʹӵround - if (isO(board, c.x, c.y - 1) && !visited[c.x][c.y - 1]) { - round.add(new Coordinate(c.x, c.y - 1)); - } - } - - if (round.size() > 0) { - return bfs(board, visited, round, all) && result; - } else { - return result; - } - - } - - /** - * жϵڶάڲҲڱ߽ - * - * @param board ά - * @param x - * @param y - * @return true - */ - public boolean isInner(char[][] board, int x, int y) { - return x > 0 && x < board.length - 1 && y > 0 && y < board[0].length - 1; - } - - /** - * жϵǷO - * - * @param board ά - * @param x - * @param y - * @return true - */ - public boolean isO(char[][] board, int x, int y) { - return x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] == 'O'; - } - - /** - * - */ - public static class Coordinate { - private int x; - private int y; - - public Coordinate() { - } - - public Coordinate(int x, int y) { - this.x = x; - this.y = y; - } - - @Override - public String toString() { - return "(" + x + ", " + y + ")"; - } - } -} diff --git "a/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221.iml" "b/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221/\343\200\220130\343\200\221\343\200\220SurroundedRegions\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221/src/Solution.java" "b/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221/src/Solution.java" deleted file mode 100644 index 3b4e1ae..0000000 --- "a/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221/src/Solution.java" +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Author: - * Date: 2015-06-21 - * Time: 10:11 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * There are N gas stations along a circular route, where the amount
-     * of gas at station i is gas[i].
-     *
-     * You have a car with an unlimited gas tank and it costs cost[i] of gas
-     * to travel from station i to its next station (i+1). You begin the journey
-     * with an empty tank at one of the gas stations.
-     *
-     * Return the starting gas station's index if you can travel around the
-     * circuit once, otherwise return -1.
-     *
-     * Note:
-     *   - The solution is guaranteed to be unique.
-     *
-     * Ŀ⣺
-     * ػ·Nվڳվigas[i]
-     * гޣӼվiһվվi+1Ҫcost[i]塣
-     * 㿪ʼóʱǿյġصʼվָѡһ㿪ʼΣ
-     * ΧһΣͷؿʼļվ򷵻-1
-     *
-     * ע⣺
-     *   - 𰸱֤Ψһ
-     *
-     * ˼·
-     * վ i վ k ֮ǰȻܱ֤û׶k 󣬼׶ˡ
-     * ô˵ diff[i] + diff[i+1] + ... + diff[k] < 0diff[k]⣬diff[i]
-     * ʼۼӶ >= 0ġҲ˵diff[i] Ҳ >= 0ģʱǻбҪվ i + 1
-     * ϸһ֪ҪǴվ i+1վkûվkͼ
-     * ˣΪټվ i ͡
-     *
-     * ˣǷֵk վ׶i  k Щվ㶼Ϊˣ϶
-     * ֻҪk+1վ㳢Լɣ˽ⷨʱ临ӶȴO(n2) O(2n)֮
-     * O(2n)Ϊk+1վΪʼվȦk֤k+1Ƿ㡣
-     *
-     * ȵȣҪ
-     * ģһ¹̣
-     * a. ʼվ0ʼվ賵վpˣ
-     *      sum1 = diff[0] +diff[1] + ... + diff[p]֪sum1 < 0
-     *
-     * b. ǽp+1Ϊʼվqվֿˣ
-     *      sum2 = diff[p+1] +diff[p+2] + ... + diff[q]֪sum2 < 0
-     *
-     * c. q+1Ϊʼվһֱδѭĩվû׶
-     *      sum3 = diff[q+1] +diff[q+2] + ... + diff[size-1]֪sum3 >= 0
-     *
-     * Ҫ֪ܷ񿪻 q վʵsum3 Ļϣμ diff[0]  diff[q]
-     * sum3ǷС0֮ǰѾ֪ diff[0]  diff[p-1] ·
-     * һֱַǸֻҪsum3 + sum1Ƿ <0֪ܲܿ p+1վˡ
-     * ܴp+1վֻҪsum3 + sum1 + sum2 Ƿ < 0֪ܲܿqվˡ
-     *
-     * Ϊ sum1, sum2  < 0 sum3 + sum1 + sum2 >=0 ô
-     * sum3 + sum1 Ȼ >= 0Ҳ˵ֻҪsum3 + sum1 + sum2 >=0Ȼܿqվ
-     * sum3 + sum1 + sum2 ʵ diffܺ TotalԪѾˡ
-     *  Total ܷ >= 0Ƿվ ֱҪ
-     *
-     * ʱ临ӶȽһO(2n) O(n)
-     * 
- * - * @param gas - * @param cost - * @return - */ - public int canCompleteCircuit(int[] gas, int[] cost) { - // - if (gas == null || cost == null || gas.length == 0 || gas.length != cost.length) { - return -1; - } - - // ¼ʵʼ - int start = 0; - // ӵĵֵܲ - int total = 0; - // startλÿʼӵĵֵܲ - int sum = 0; - - for (int i = 0; i < gas.length; i++) { - total += (gas[i] - cost[i]); - - // û - if (sum < 0) { - // е - sum = gas[i] - cost[i]; - // ¼µλ - start = i; - } else { - // лͣе - sum += (gas[i] - cost[i]); - } - } - - return total >= 0 ? start : -1; - } - - - // ķᳬʱO(N^2)ʱ临Ӷ - public int canCompleteCircuit2(int[] gas, int[] cost) { - // - if (gas == null || cost == null || gas.length == 0 || gas.length != cost.length) { - return -1; - } - - // ʣµ壬ʼʱΪ0 - int leftGas = 0; - // ʼվ - int start = 0; - // վ - int end = 1; - - // δһ - while (start < gas.length) { - - // һվ - leftGas = gas[start] - cost[start]; - - // ߵһվ - if (leftGas > 0) { - // ¼һվ - end = (start + 1) % gas.length; - - // һֱԵһվͳв - while (start != end && (leftGas += (gas[end] - cost[end])) >= 0) { - end = (end + 1) % gas.length; - } - - // ˵Ѿһ - if (start == end) { - return start; - } - } - - start++; - } - - return -1; - } -} diff --git "a/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221.iml" "b/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221/\343\200\220134\343\200\221\343\200\220GasStation\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221/src/Solution.java" "b/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221/src/Solution.java" deleted file mode 100644 index 4dce0d3..0000000 --- "a/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221/src/Solution.java" +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Author: - * Date: 2015-06-18 - * Time: 10:29 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - * Given an array of integers, every element appears twice except for one. - * Find that single one. - * - * Note: Your algorithm should have a linear runtime complexity. - * Could you implement it without using extra memory? - * - * һ飬ÿԪض2γеһҳֻһε - * ע⣺㷨ʱ临ӶȣԲʹöռʵ - * - * ˼·ʹ - * - * @param nums - * @return - */ - public int singleNumber(int[] nums) { - - if (nums == null || nums.length < 1) { - throw new IllegalArgumentException("nums"); - } - - - for (int i = 1; i< nums.length; i++) { - nums[0] ^= nums[i]; - } - return nums[0]; - } -} diff --git "a/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221.iml" "b/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221/\343\200\220136\343\200\221\343\200\220SingleNumber\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221/\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221.iml" "b/\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221/\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221/\343\200\220137\343\200\221\343\200\220SingleNumberII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Main.java" "b/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Main.java" deleted file mode 100644 index 85972fb..0000000 --- "a/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Main.java" +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Author: - * Date: 2015-06-24 - * Time: 09:18 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - RandomListNode n1 = new RandomListNode(1); - RandomListNode n2 = new RandomListNode(2); - RandomListNode n3 = new RandomListNode(3); - RandomListNode n4 = new RandomListNode(4); - n1.next = n2; - n2.next = n3; - n3.next = n4; - - Solution solution = new Solution(); - RandomListNode copy = solution.copyRandomList(n1); - - print(copy); - - } - - public static void print(RandomListNode head) { - while (head != null) { - System.out.print(head.label + "->"); - head = head.next; - } - - System.out.println("null"); - } -} diff --git "a/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Solution.java" "b/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Solution.java" deleted file mode 100644 index 6b6df56..0000000 --- "a/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Solution.java" +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Author: - * Date: 2015-06-24 - * Time: 08:48 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * A linked list is given such that each node contains an additional random
-     * pointer which could point to any node in the list or null.
-     *
-     * Return a deep copy of the list.
-     *
-     * Ŀ⣺
-     * һһָnullĽָ룬
-     *
-     * ˼·
-     * һƽ㣬ƵĽڴƵĽȻһ
-     * ڶָ
-     * 
-     * 
- * - * @param head - * @return - */ - public RandomListNode copyRandomList(RandomListNode head) { - if (head == null) { - return null; - } - - copyNode(head); - linkRandomPointer(head); - - return splitList(head); - } - - /** - * ƽ㣬ƵĽڴƵĽȻһ - * - * @param head ͷ - */ - public void copyNode(RandomListNode head) { - // ¼ǰҪƵ - RandomListNode node = head; - while (node != null) { - // һµĽ - RandomListNode copyNode = new RandomListNode(node.label); - // 㴮ӵƵĽ󣬲Ȼɵ - copyNode.next = node.next; - node.next = copyNode; - node = copyNode.next; - } - } - - /** - * ָ - * - * @param head ͷ - */ - public void linkRandomPointer(RandomListNode head) { - // ¼ǰҪƵ - RandomListNode node = head; - while (node != null) { - // ָָijĽ - if (node.random != null) { - // nodeƽָ - node.next.random = node.random.next; - } - - // ָһƵĽ - node = node.next.next; - } - } - - /** - * ֣ԭԭװ - * - * @param head ͷ - * @return ͷ - */ - public RandomListNode splitList(RandomListNode head) { - // ͷ - RandomListNode copyHead = head.next; - // ǰıƵĽ - RandomListNode node = head; - // ǰƵĽ - RandomListNode copy; - - while (node != null){ - // ָƽ - copy = node.next; - - // node.nextָһƵĽ - node.next = copy.next; - - // һƵĽ㲻Ϊnull - if (node.next != null) { - // copy.nextָһƵĽ - copy.next = node.next.next; - } - - // nodeָһҪıƽ - node = node.next; - } - return copyHead; - } -} diff --git "a/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221.iml" "b/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/\343\200\220138\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/src/Main.java" "b/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/src/Main.java" deleted file mode 100644 index ad4016f..0000000 --- "a/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/src/Main.java" +++ /dev/null @@ -1,50 +0,0 @@ -import java.util.HashSet; -import java.util.Set; - -/** - * Author: - * Date: 2015-06-21 - * Time: 08:48 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { -// test01(); -// test02(); - test03(); - } - - private static void test01() { - Solution solution = new Solution(); - Set set = new HashSet<>(); - set.add("leet"); - set.add("code"); - System.out.println(solution.wordBreak("leetcode", set)); - } - - private static void test02() { - Solution solution = new Solution(); - Set set = new HashSet<>(); - System.out.println(solution.wordBreak("a", set)); - } - - - private static void test03() { - Solution solution = new Solution(); - Set set = new HashSet<>(); -// set.add("b"); - set.add("a"); - set.add("aa"); - set.add("aaa"); - set.add("aaaa"); - set.add("aaaaa"); - set.add("aaaaaa"); - set.add("aaaaaaa"); - set.add("aaaaaaaa"); - set.add("aaaaaaaaa"); - set.add("aaaaaaaaaa"); - System.out.println(solution.wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - "aaaaaaaaaaaaaaaaaaaaaaaaab", set)); - } -} diff --git "a/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221.iml" "b/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221/\343\200\220139\343\200\221\343\200\220WordBreak\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/src/ListNode.java" "b/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/src/ListNode.java" deleted file mode 100644 index a9b5f6a..0000000 --- "a/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/src/ListNode.java" +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:17 - * Declaration: All Rights Reserved !!! - */ -public class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } -} diff --git "a/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/src/Solution.java" "b/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/src/Solution.java" deleted file mode 100644 index cee01cb..0000000 --- "a/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/src/Solution.java" +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:16 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * Given a linked list, determine if it has a cycle in it.
-     * Follow up:
-     * Can you solve it without using extra space?
-     *
-     * Ŀ
-     * һжǷл
-     *
-     * ˼·
-     * ָ(fast, slow)ʼֵָͷslowÿǰһfastÿǰڻ
-     * fastضȽ뻷slow뻷ָض
-     * 
- * - * @param head - * @return - */ - public boolean hasCycle(ListNode head) { - - ListNode fast = head; - ListNode slow = head; - - while (fast != null && fast.next != null) { - fast = fast.next.next; - slow = slow.next; - if (slow == fast) { - break; - } - } - - return !(fast == null || fast.next == null); - } -} diff --git "a/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221.iml" "b/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221/\343\200\220141\343\200\221\343\200\220LinkedListCycle\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/src/ListNode.java" "b/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/src/ListNode.java" deleted file mode 100644 index fba59f9..0000000 --- "a/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/src/ListNode.java" +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:19 - * Declaration: All Rights Reserved !!! - */ -public class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } -} diff --git "a/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221.iml" "b/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221/\343\200\220142\343\200\221\343\200\220LinkedListCycleII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/RandomListNode.java" "b/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/RandomListNode.java" deleted file mode 100644 index fabb62e..0000000 --- "a/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/RandomListNode.java" +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:22 - * Declaration: All Rights Reserved !!! - */ -public class RandomListNode { - int label; - RandomListNode next, random; - - RandomListNode(int x) { - this.label = x; - } -} diff --git "a/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Solution.java" "b/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Solution.java" deleted file mode 100644 index 5128823..0000000 --- "a/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/src/Solution.java" +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Author: - * Date: 2015-08-21 - * Time: 19:21 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * ԭ
-     * A linked list is given such that each node contains an additional random pointer
-     * which could point to any node in the list or null.
-     * Return a deep copy of the list.
-     *
-     * Ŀ
-     * һһָnullĽָ룬
-     *
-     * ˼·
-     * һƽ㣬ƵĽڴƵĽȻһ
-     * ڶָ
-     * ֡ԭ͸
-     * 
- * - * @param head - * @return - */ - public RandomListNode copyRandomList(RandomListNode head) { - if (head == null) { - return null; - } - - copyNode(head); - linkRandomPointer(head); - - return splitList(head); - } - - /** - * ƽ㣬ƵĽڴƵĽȻһ - * - * @param head ͷ - */ - public void copyNode(RandomListNode head) { - // ¼ǰҪƵ - RandomListNode node = head; - while (node != null) { - // һµĽ - RandomListNode copyNode = new RandomListNode(node.label); - // 㴮ӵƵĽ󣬲Ȼɵ - copyNode.next = node.next; - node.next = copyNode; - node = copyNode.next; - } - } - - /** - * ָ - * - * @param head ͷ - */ - public void linkRandomPointer(RandomListNode head) { - // ¼ǰҪƵ - RandomListNode node = head; - while (node != null) { - // ָָijĽ - if (node.random != null) { - // nodeƽָ - node.next.random = node.random.next; - } - - // ָһƵĽ - node = node.next.next; - } - } - - /** - * ֣ԭԭװ - * - * @param head ͷ - * @return ͷ - */ - public RandomListNode splitList(RandomListNode head) { - // ͷ - RandomListNode copyHead = head.next; - // ǰıƵĽ - RandomListNode node = head; - // ǰƵĽ - RandomListNode copy; - - while (node != null) { - // ָƽ - copy = node.next; - - // node.nextָһƵĽ - node.next = copy.next; - - // һƵĽ㲻Ϊnull - if (node.next != null) { - // copy.nextָһƵĽ - copy.next = node.next.next; - } - - // nodeָһҪıƽ - node = node.next; - } - return copyHead; - } -} diff --git "a/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221.iml" "b/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221/\343\200\220143\343\200\221\343\200\220CopyListWithRandomPointer\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221.iml" "b/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221/\343\200\220144\343\200\221\343\200\220BinaryTreePreorderTraversal\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/src/Solution.java" "b/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/src/Solution.java" deleted file mode 100644 index 0bba339..0000000 --- "a/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/src/Solution.java" +++ /dev/null @@ -1,95 +0,0 @@ -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-06-22 - * Time: 14:54 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a binary tree, return the postorder traversal of its nodes' values.
-     *
-     * For example:
-     * Given binary tree {1,#,2,3},
-     *      1
-     *       \
-     *        2
-     *       /
-     *      3
-     * return [3,2,1].
-     *
-     * Note: Recursive solution is trivial, could you do it iteratively?
-     *
-     * Ŀ⣺
-     * һŶĺĽֵ
-     *
-     * ע⣺
-     *   - ݹⷨף볢ʽ
-     *
-     * ˼·
-     * ǵݹ
-     * ݺ˳ȷٷʸڵ㣬ÿ˵
-     * ְͬķ˳бķǵݹʵ˵ҪһЩҪ֤
-     * ʺܷʣ˼·£
-     *
-     * һڵP
-     * 1ȽڵPջ
-     * 2PӺҺӣPӻҺӣҺѾ
-     *      ֱڵPջջڵPΪһĽڵ㣬ٽʱ
-     *      ջΪǰڵ㣻
-     * 32еPҺӺջǰڵΪջ㣬
-     *      ֮ظ2
-     * 4ֱջգ
-     * 
- * - * @param root - * @return - */ - public List postorderTraversal(TreeNode root) { - List list = new LinkedList<>(); - - if (root != null) { - // ˫˶Уջʹ - Deque deque = new LinkedList<>(); - // ָǰһĽ - TreeNode prev = null; - // ָǰĽ - TreeNode curr; - // ջ - deque.addLast(root); - // ջǿ - while (!deque.isEmpty()) { - // ȡջԪأɾ - curr = deque.getLast(); - if ((curr.left == null && curr.right == null) // ǰԪ - // prev == null && curr.left == prevǰֻѾ - // prev == null && curr.right == prevǰѾ - || (prev != null && (curr.left == prev || curr.right == prev))) { - // ɾջԪ - curr = deque.removeLast(); - // ֵջ - list.add(curr.val); - // һĽ - prev = curr; - } else { - - // δ꣬ǿջ - - if (curr.right != null) { - deque.addLast(curr.right); - } - - if (curr.left != null) { - deque.addLast(curr.left); - } - } - } - } - - return list; - } -} diff --git "a/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221.iml" "b/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221/\343\200\220145\343\200\221\343\200\220BinaryTreePostorderTraversal\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221.iml" "b/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221/\343\200\220147\343\200\221\343\200\220InsertionSortList\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/src/Main.java" "b/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/src/Main.java" deleted file mode 100644 index f6672ab..0000000 --- "a/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/src/Main.java" +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Author: - * Date: 2015-06-20 - * Time: 07:14 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - System.out.println(solution.evalRPN(new String[]{"0","3","/"})); - } -} diff --git "a/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/src/Solution.java" "b/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/src/Solution.java" deleted file mode 100644 index 499adc9..0000000 --- "a/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/src/Solution.java" +++ /dev/null @@ -1,75 +0,0 @@ -import java.util.Queue; -import java.util.Stack; - -/** - * Author: - * Date: 2015-06-20 - * Time: 06:58 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Evaluate the value of an arithmetic expression in Reverse Polish Notation.
-     * Valid operators are +, -, *, /. Each operand may be an integer or another expression.
-     *
-     * Some examples:
-     * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
-     * ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
-     *
-     * Ŀ⣺
-     * 沨ʽֵЧǣ+-*/ÿҪôһҪôһʽ
-     *
-     * ˼·
-     * ʹջв
-     * 
- * - * @param tokens - * @return - */ - public int evalRPN(String[] tokens) { - // У - if (tokens == null || tokens.length < 1) { - throw new IllegalArgumentException(); - } - - int op1; - int op2; - // ջ - Stack stack = new Stack<>(); - - for (String token : tokens) { - // ˵ҪȡջԪؽ - if ("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token)) { - // ȡջԪ - op2 = stack.pop(); - op1 = stack.pop(); - - // - switch (token.charAt(0)) { - case '+': - op1 += op2; - break; - case '-': - op1 -= op2; - break; - case '*': - op1 *= op2; - break; - case '/': - op1 /= op2; - break; - } - // ջ - stack.push(op1); - } - // ˵Dzջ - else { - stack.push(Integer.parseInt(token)); - } - } - - // ջֻʣһԪأǾĽ - return stack.pop(); - } -} diff --git "a/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221.iml" "b/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221/\343\200\220150\343\200\221\343\200\220EvaluateReversePolishNotation\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221.iml" "b/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221/\343\200\220151\343\200\221\343\200\220ReverseWordsInAString\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221.iml" "b/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221/\343\200\220152\343\200\221\343\200\220MaximumProductSubarray\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221.iml" "b/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221/\343\200\220153\343\200\221\343\200\220FindMinimumInRotatedSortedArray\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221.iml" "b/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221/\343\200\220154\343\200\221\343\200\220FindMinimumInRotatedSortedArrayII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220155\343\200\221\343\200\220MinStack\343\200\221/\343\200\220155\343\200\221\343\200\220MinStack\343\200\221.iml" "b/\343\200\220155\343\200\221\343\200\220MinStack\343\200\221/\343\200\220155\343\200\221\343\200\220MinStack\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220155\343\200\221\343\200\220MinStack\343\200\221/\343\200\220155\343\200\221\343\200\220MinStack\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220162\346\234\252\343\200\221\343\200\220FindPeakElement\343\200\221/src/Solution.java" "b/\343\200\220162\346\234\252\343\200\221\343\200\220FindPeakElement\343\200\221/src/Solution.java" deleted file mode 100644 index ad5b5f3..0000000 --- "a/\343\200\220162\346\234\252\343\200\221\343\200\220FindPeakElement\343\200\221/src/Solution.java" +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Author: - * Date: 2015-06-19 - * Time: 17:30 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * A peak element is an element that is greater than its neighbors.
-     *
-     * Given an input array where num[i]  num[i+1], find a peak element and return its index.
-     *
-     * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
-     *
-     * You may imagine that num[-1] = num[n] = -.
-     *
-     * For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return
-     * the index number 2.
-     *
-     * Note:
-     * Your solution should be in logarithmic complexity.
-     *
-     * Ŀ⣺
-     * ֵԪءֵָھӵԪ
-     *
-     * һnum[i]  num[i+1]ҵһֵԪز±ꡣ
-     *
-     * ֵܰ·һɡ
-     *
-     * Լnum[-1] = num[n] = -ޣʼԪصĩβԪصҲΪ
-     *
-     * 磬[1, 2, 3, 1]У3ǷֵԪأĺӦ÷±2
-     *
-     * ע⣺
-     * ΪӶȡ
-     * 
- * - * @param nums - * @return - */ - public int findPeakElement(int[] nums) { - return 0; - } - -} diff --git "a/\343\200\220162\346\234\252\343\200\221\343\200\220FindPeakElement\343\200\221/\343\200\220162\343\200\221\343\200\220FindPeakElement\343\200\221.iml" "b/\343\200\220162\346\234\252\343\200\221\343\200\220FindPeakElement\343\200\221/\343\200\220162\343\200\221\343\200\220FindPeakElement\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220162\346\234\252\343\200\221\343\200\220FindPeakElement\343\200\221/\343\200\220162\343\200\221\343\200\220FindPeakElement\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/src/Solution.java" "b/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/src/Solution.java" deleted file mode 100644 index 5b782f6..0000000 --- "a/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/src/Solution.java" +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Author: - * Date: 2015-06-17 - * Time: 21:51 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - * Write a function that takes an unsigned integer and returns the number of 1' bits it has - * (also known as the Hamming weight). - * - * For example, the 32-bit integer 11' has binary representation 00000000000000000000000000001011, - * so the function should return 3. - * - * еλ - * - * @param n - * @return - */ - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - - int count = 0; - while (n != 0) { - count++; - n = (n - 1) & n; - } - return count; - } -} diff --git "a/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221.iml" "b/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221/\343\200\220191\343\200\221\343\200\220NumberOf1Bits\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221.iml" "b/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221/\343\200\220198\343\200\221\343\200\220HouseRobber\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221.iml" "b/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221/\343\200\220199\343\200\221\343\200\220BinaryTreeRightSideView\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221/src/Solution.java" "b/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221/src/Solution.java" deleted file mode 100644 index 47991f4..0000000 --- "a/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221/src/Solution.java" +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Author: - * Date: 2015-06-20 - * Time: 11:00 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
-     * An island is surrounded by water and is formed by connecting adjacent lands horizontally
-     * or vertically. You may assume all four edges of the grid are all surrounded by water.
-     *
-     * Example 1:
-     *      11110
-     *      11010
-     *      11000
-     *      00000
-     * Answer: 1
-     *
-     * Example 2:
-     *      11000
-     *      11000
-     *      00100
-     *      00011
-     * Answer: 3
-     *
-     * Ŀ⣺
-     * һάĵͼ'1'½أ0ˮ滷ˮ
-     * ڵ½ˮƽֱӶγɵġԼĸ߶ˮΧ
-     *
-     * ˼·
-     * һһӦķʱǾ󣬶ÿԪʱйȱȱͳƵĿ
-     *
-     * 
- * - * @param grid - * @return - */ - public int numIslands(char[][] grid) { - // У - if (grid == null || grid.length == 0 || grid[0].length == 0) { - return 0; - } - - // ԪĬֵfalse - boolean[][] visited = new boolean[grid.length][grid[0].length]; - - int result = 0; - for (int i = 0; i < grid.length; i++) { - for (int j = 0; j < grid[0].length; j++) { - // λûбʹҴλǵ¹ȱ - if (!visited[i][j] && grid[i][j] == '1') { - result++; - bfs(grid, visited, i, j); - } - } - } - return result; - } - - /** - * - * @param grid - * @param visited ʱǾ - * @param row - * @param col - */ - private void bfs(char[][] grid, boolean[][] visited, int row, int col) { - - if (row >= 0 && row < grid.length // кϷ - && col >= 0 && col < grid[0].length // кϷ - && !visited[row][col] // ûзʹ - && grid[row][col] == '1') { // ǵ½ - - // ǴλѾʹ - visited[row][col] = true; - - // - bfs(grid, visited, row - 1, col); - // - bfs(grid, visited, row, col + 1); - // - bfs(grid, visited, row + 1, col); - // - bfs(grid, visited, row, col - 1); - } - } -} diff --git "a/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221.iml" "b/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221/\343\200\220200\343\200\221\343\200\220NumberOfIslands\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221/\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221.iml" "b/\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221/\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221/\343\200\220201\343\200\221\343\200\220BitwiseANDOfNumbersRange\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/src/Solution.java" "b/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/src/Solution.java" deleted file mode 100644 index 5df793f..0000000 --- "a/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/src/Solution.java" +++ /dev/null @@ -1,51 +0,0 @@ -import java.util.HashSet; - -/** - * Author: - * Date: 2015-06-17 - * Time: 21:36 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - * Write an algorithm to determine if a number is "happy". - * A happy number is a number defined by the following process: Starting with any positive integer, - * replace the number by the sum of the squares of its digits, and repeat the process until the number - * equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those - * numbers for which this process ends in 1 are happy numbers. - * - * ĿҪһϸλֵƽͣΪ1Ϊhappy number - * ܴijʼѭ - * - * @param n - * @return - */ - public boolean isHappy(int n) { - - if (n < 1) { - return false; - } - - // ڱмֵĽ - HashSet set = new HashSet<>(32); - - int tmp; - int newN; - - // nΪ1nֵظ֣ѭ - while (n != 1 && !set.contains(n)) { - set.add(n); - newN = 0; - while (n > 0) { - tmp = n % 10; - n /= 10; - newN += tmp * tmp; - } - - n = newN; - } - - return n == 1; - } - -} diff --git "a/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221.iml" "b/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221/\343\200\220202\343\200\221\343\200\220HappyNumber \343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221.iml" "b/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221/\343\200\220203\343\200\221\343\200\220RemoveLinkedList Elements\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221/\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221.iml" "b/\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221/\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221/\343\200\220204\343\200\221\343\200\220CountPrimes\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221/\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221.iml" "b/\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221/\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221/\343\200\220205\343\200\221\343\200\220IsomorphicStrings\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/src/Solution.java" "b/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/src/Solution.java" deleted file mode 100644 index 202cdf3..0000000 --- "a/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/src/Solution.java" +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Author: - * Date: 2015-06-19 - * Time: 11:17 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - * Reverse a singly linked list. - * ת - * ʹͷ巨 - * - * @param head - * @return - */ - public ListNode reverseList(ListNode head) { - // ͷ - ListNode root = new ListNode(0); - ListNode nextNode; - while (head != null) { - nextNode = head.next; - head.next = root.next; - root.next = head; - head = nextNode; - } - - return root.next; - } - - /** - * TODO ʹõݹⷨ - * @param head - * @return - */ - public ListNode reverseList2(ListNode head) { - if (head == null) { - return null; - } - - reverseList2(head.next).next = head; - - return null; - } -} diff --git "a/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221.iml" "b/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221/\343\200\220206\343\200\221\343\200\220ReverseLinkedList\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/src/Main.java" "b/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/src/Main.java" deleted file mode 100644 index cd77742..0000000 --- "a/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/src/Main.java" +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Author: - * Date: 2015-06-19 - * Time: 20:01 - * Declaration: All Rights Reserved !!! - */ -public class Main { - public static void main(String[] args) { - Solution solution = new Solution(); - System.out.println(solution.findKthLargest(new int[]{2 , 1}, 2)); - } -} diff --git "a/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/src/Solution.java" "b/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/src/Solution.java" deleted file mode 100644 index 8119edf..0000000 --- "a/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/src/Solution.java" +++ /dev/null @@ -1,81 +0,0 @@ -import java.util.Collections; - -/** - * Author: - * Date: 2015-06-19 - * Time: 19:36 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Find the kth largest element in an unsorted array. Note that it is the kth
-     * largest element in the sorted order, not the kth distinct element.
-     *
-     * For example,
-     * Given [3,2,1,5,6,4] and k = 2, return 5.
-     *
-     * Note:
-     * You may assume k is always valid, 1  k  array's length.
-     *
-     * Ŀ⣺
-     * һδҳkԪءע֮ĵk󣬶ǵkظԪ
-     * ԼkһЧģ 1  k  鳤
-     *
-     * ˼·
-     * O(n)ⷨѡQuickSelect㷨
-     * 
- * - * @param nums - * @param k - * @return - */ - public int findKthLargest(int[] nums, int k) { - - if (k < 1 || nums == null || nums.length < k) { - throw new IllegalArgumentException(); - } - - return findKthLargest(nums, 0, nums.length - 1, k); - } - - public int findKthLargest(int[] nums, int start, int end, int k) { - - // ֵ - int pivot = nums[start]; - int lo = start; - int hi = end; - - while (lo < hi) { - // Сֵƶ - while (lo < hi && nums[hi] >= pivot) { - hi--; - } - nums[lo] = nums[hi]; - - // ֵƶұ - while (lo < hi && nums[lo] <= pivot) { - lo++; - } - nums[hi] = nums[lo]; - } - - nums[lo] = pivot; - - // Ѿҵ - if (end - lo + 1 == k) { - return pivot; - } - // kloλõұ - else if (end - lo + 1 > k){ - return findKthLargest(nums, lo + 1, end, k); - } - // kloλõ - else { - // k-(end-lo+1) - // (end-lo+1)ʾloλÿʼendλõԪظҰ벿 - // ԭĵkk-(end-lo+1) - return findKthLargest(nums, start, lo - 1, k - (end - lo + 1)); - } - } -} diff --git "a/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221.iml" "b/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221/\343\200\220215\343\200\221\343\200\220KthLargestElementInAnArray\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/src/Solution.java" "b/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/src/Solution.java" deleted file mode 100644 index e2c8e6f..0000000 --- "a/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/src/Solution.java" +++ /dev/null @@ -1,101 +0,0 @@ -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * Author: - * Date: 2015-06-21 - * Time: 21:31 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - /** - *
-     * Find all possible combinations of k numbers that add up to a number n,
-     * given that only numbers from 1 to 9 can be used and each combination
-     * should be a unique set of numbers.
-     *
-     * Ensure that numbers within the set are sorted in ascending order.
-     *
-     * Example 1:
-     * Input: k = 3, n = 7
-     * Output:
-     * [[1,2,4]]
-     *
-     * Example 2:
-     * Input: k = 3, n = 9
-     * Output:
-     * [[1,2,6], [1,3,5], [2,3,4]]
-     *
-     * Ŀ⣺
-     * Ѱk֮͵nϣֻʹ1-9ÿһеӦΨһġ
-     * ȷеԵ˳С
-     *
-     * ˼·
-     * ݷ
-     * 
- * - * @param k - * @param n - * @return - */ - public List> combinationSum3(int k, int n) { - // ڱн - List> result = new LinkedList<>(); - // ڱм - List list = new LinkedList<>(); - // ͽн - if (k > 0 && k <= 9) { - solve(k, 1, n, 0, list, result); - } - - // ؽ - return result; - } - - /** - * ⷽ - * - * @param k ÿԪظ - * @param cur ǰkԪ - * @param remainder k - cur + 1Ԫصĺ - * @param prevVal cur-1Ԫصȡֵ - * @param list Ԫصļ - * @param result н - */ - public void solve(int k, int cur, int remainder, int prevVal, List list, List> result) { - // һԪ - if (cur == k) { - // remainderΪһԪصֵǰһԪصֵҲܳ9 - if (remainder > prevVal && remainder <= 9) { - // Ԫֵ - list.add(remainder); - - // µĶ - List one = new LinkedList<>(); - for (Integer i : list) { - one.add(i); - } - - // - result.add(one); - // ɾһԪأֳԭ - list.remove(list.size() - 1); - } - } - // һԪ - else if (cur < k){ - for (int i = prevVal + 1; i <= 9 - (k - cur); i++) { - // Ԫ - list.add(i); - // ݹ - solve(k, cur + 1, remainder - i, i, list, result); - // ֳԭ - list.remove(list.size() - 1); - - } - } - - - } -} diff --git "a/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221.iml" "b/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221/\343\200\220216\343\200\221\343\200\220CombinationSumIII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/src/Solution.java" "b/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/src/Solution.java" deleted file mode 100644 index 67fdbb9..0000000 --- "a/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/src/Solution.java" +++ /dev/null @@ -1,46 +0,0 @@ -import java.util.HashSet; -import java.util.Set; - -/** - * Author: - * Date: 2015-06-18 - * Time: 09:40 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - - - /** - * Given an array of integers, find if the array contains any duplicates. - * Your function should return true if any value appears at least twice in the - * array, and it should return false if every element is distinct. - *

- * Ŀ⣺һ飬жǷظԪءһֳΣ - * ĺӦ÷trueÿһԪضΨһģfalse - * - * ˼·setݽṹ - * - * @param nums - * @return - */ - public boolean containsDuplicate(int[] nums) { - - // Ԫظ1ŽIJ - if (nums != null && nums.length > 1) { - //һhashSet - Set set = new HashSet<>(nums.length); - for(int i : nums) { - // ԪѾھͷtrue - if (set.contains(i)) { - return true; - } - // ûоӵԪؼ - else { - set.add(i); - } - } - } - - return false; - } -} diff --git "a/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221.iml" "b/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221/\343\200\220217\343\200\221\343\200\220ContainsDuplicate \343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221/src/Solution.java" "b/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221/src/Solution.java" deleted file mode 100644 index 2fa0545..0000000 --- "a/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221/src/Solution.java" +++ /dev/null @@ -1,55 +0,0 @@ -import java.util.HashMap; -import java.util.Map; - -/** - * Author: - * Date: 2015-06-19 - * Time: 14:10 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - - /** - * Given an array of integers and an integer k, find out whether there there are - * two distinct indices i and j in the array such that nums[i] = nums[j] and the - * difference between i and j is at most k. - * - * Ŀ⣺ - * һnumsһkҽͬ±ijnums[i] = nums[j] - * |i-j|<=kʱtrue򷵻false - * - * ˼· - * nums[0...n-1]һmapУ(muns[i], i)nums[k]Ѿڣ - * Ƚ֮ǰ±ڵ±IJֵֵk˵ֵ - * ʹµ±Ϊֵ - * - * @param nums - * @param k - * @return - */ - public boolean containsNearbyDuplicate(int[] nums, int k) { - // ж - if (nums == null || nums.length < 2 || k < 1) { - return false; - } - - Map map = new HashMap<>(); - for (int i = 0; i < nums.length; i++) { - - // ûжӦkeyӽȥ - if (!map.containsKey(nums[i])) { - map.put(nums[i], i); - } - // ѾжӦkey-value - else { - // ԭֵӦ±꣬һСڵ± - int value = map.get(nums[i]); - if (i - value <= k) { - return true; - } - map.put(nums[i], i); - } - } - return false; - } -} diff --git "a/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221.iml" "b/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221/\343\200\220219\343\200\221\343\200\220ContainsDuplicateII\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/src/Solution.java" "b/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/src/Solution.java" deleted file mode 100644 index f2ea311..0000000 --- "a/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/src/Solution.java" +++ /dev/null @@ -1,78 +0,0 @@ -import java.util.*; - -/** - * Author: - * Date: 2015-06-19 - * Time: 15:32 - * Declaration: All Rights Reserved !!! - */ -public class Solution { - - /** - *

-     * Find the total area covered by two rectilinear rectangles in a 2D plane.
-     * Each rectangle is defined by its bottom left corner and top right
-     * corner as shown in the figure.
-     *
-     * Assume that the total area is never beyond the maximum possible value of int.
-     *
-     * *****************************(C,D):(3,4)
-     * *                           *
-     * *                           *
-     * *           *************************************(G,H):(9,2)
-     * *           *               *                   *
-     * *           *               *                   *
-     * *           *               *                   *
-     * *           *               *                   *
-     * *           *(0,0)          *                   *
-     * *****************************                   *
-     * (A,B):(-3,0)*                                   *
-     *             *                                   *
-     *             * (E,F):(0-1)                     *
-     *             *************************************
-     *
-     *   ***************************        ***************************
-     *   *            D            *        *            H            *
-     *   *                         *        *                         *
-     *   *A                       C*        *E                       G*
-     *   *                         *        *                         *
-     *   *                         *        *                         *
-     *   *            B            *        *            F            *
-     *   ***************************        ***************************
-     *
-     *
-     *
-     * 
- * Ŀ⣺ - * ܹǵ - *

- * ˼· - * 㷽Ϊ1+2-ιͬĸ - * - * @param A - * @param B - * @param C - * @param D - * @param E - * @param F - * @param G - * @param H - * @return - */ - public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { - long area = (long) (C - A) * (D - B) + (long)(G - E) * (H - F); - // Math.min(C, G) ʾұ߱ߵСı - // Math.max(A, E) ʾ߱ߵı - // ļԽ飬ҪݷΧ - long width = Math.max((long)Math.min(C, G) - (long)Math.max(A, E), 0); - // Math.min(D, H) ʾ߱ߵСı - // Math.max(B, F) ʾױ߱ߵı - long height = Math.max((long)Math.min(D, H) - (long)Math.max(B, F), 0); - - System.out.println(width +":" + height + "=" + width*height); - - return (int)(area - width * height); - } - - -} diff --git "a/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221.iml" "b/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221/\343\200\220223\343\200\221\343\200\220RectangleArea\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221/\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221.iml" "b/\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221/\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221/\343\200\220225\343\200\221\343\200\220ImplementStackUsingQueues\343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git "a/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221.iml" "b/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221.iml" deleted file mode 100644 index c90834f..0000000 --- "a/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221/\343\200\220226\343\200\221\343\200\220InvertBinaryTree \343\200\221.iml" +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file