├── .gitignore ├── note ├── 100 │ └── README.md ├── 101 │ └── README.md ├── 104 │ └── README.md ├── 107 │ └── README.md ├── 108 │ └── README.md ├── 110 │ └── README.md ├── 111 │ └── README.md ├── 112 │ └── README.md ├── 118 │ └── README.md ├── 119 │ └── README.md ├── 121 │ └── README.md ├── 122 │ └── README.md ├── 543 │ └── README.md ├── 554 │ └── README.md ├── 011 │ ├── water.png │ └── README.md ├── 004 │ ├── my_draw.jpg │ └── README.md ├── 031 │ └── README.md ├── 058 │ └── README.md ├── 007 │ └── README.md ├── 069 │ └── README.md ├── 083 │ └── README.md ├── 070 │ └── README.md ├── 050 │ └── README.md ├── 035 │ └── README.md ├── 088 │ └── README.md ├── 021 │ └── README.md ├── 014 │ └── README.md ├── 003 │ └── README.md ├── 049 │ └── README.md ├── 066 │ └── README.md ├── 067 │ └── README.md ├── 028 │ └── README.md ├── 019 │ └── README.md ├── 002 │ └── README.md ├── 016 │ └── README.md ├── 001 │ └── README.md ├── 033 │ └── README.md ├── 020 │ └── README.md ├── 038 │ └── README.md ├── 009 │ └── README.md ├── 015 │ └── README.md ├── 043 │ └── README.md ├── 024 │ └── README.md ├── 056 │ └── README.md ├── 057 │ └── README.md ├── 053 │ └── README.md ├── 026 │ └── README.md ├── 027 │ └── README.md ├── 022 │ └── README.md ├── 029 │ └── README.md ├── 017 │ └── README.md ├── 025 │ └── README.md ├── 012 │ └── README.md ├── 013 │ └── README.md ├── 023 │ └── README.md ├── 008 │ └── README.md ├── 006 │ └── README.md ├── 030 │ └── README.md └── 044 │ └── README.md ├── src └── com │ └── blankj │ ├── easy │ ├── _069 │ │ └── Solution.java │ ├── _070 │ │ └── Solution.java │ ├── _058 │ │ └── Solution.java │ ├── _122 │ │ └── Solution.java │ ├── _007 │ │ └── Solution.java │ ├── _119 │ │ └── Solution.java │ ├── _104 │ │ └── Solution.java │ ├── _121 │ │ └── Solution.java │ ├── _027 │ │ └── Solution.java │ ├── _112 │ │ └── Solution.java │ ├── _543 │ │ └── Solution.java │ ├── _028 │ │ └── Solution.java │ ├── _026 │ │ └── Solution.java │ ├── _014 │ │ └── Solution.java │ ├── _083 │ │ └── Solution.java │ ├── _035 │ │ └── Solution.java │ ├── _108 │ │ └── Solution.java │ ├── _088 │ │ └── Solution.java │ ├── _110 │ │ └── Solution.java │ ├── _066 │ │ └── Solution.java │ ├── _100 │ │ └── Solution.java │ ├── _020 │ │ └── Solution.java │ ├── _038 │ │ └── Solution.java │ ├── _118 │ │ └── Solution.java │ ├── _021 │ │ └── Solution.java │ ├── _013 │ │ └── Solution.java │ ├── _001 │ │ └── Solution.java │ ├── _107 │ │ └── Solution.java │ ├── _009 │ │ └── Solution.java │ ├── _111 │ │ └── Solution.java │ ├── _053 │ │ └── Solution.java │ ├── _067 │ │ └── Solution.java │ └── _101 │ │ └── Solution.java │ ├── medium │ ├── _050 │ │ └── Solution.java │ ├── _011 │ │ └── Solution.java │ ├── _012 │ │ └── Solution.java │ ├── _033 │ │ └── Solution.java │ ├── _029 │ │ └── Solution.java │ ├── _019 │ │ └── Solution.java │ ├── _003 │ │ └── Solution.java │ ├── _024 │ │ └── Solution.java │ ├── _016 │ │ └── Solution.java │ ├── _002 │ │ └── Solution.java │ ├── _043 │ │ └── Solution.java │ ├── _049 │ │ └── Solution.java │ ├── _554 │ │ └── Solution.java │ ├── _056 │ │ └── Solution.java │ ├── _015 │ │ └── Solution.java │ ├── _057 │ │ └── Solution.java │ ├── _008 │ │ └── Solution.java │ ├── _022 │ │ └── Solution.java │ ├── _017 │ │ └── Solution.java │ ├── _006 │ │ └── Solution.java │ └── _005 │ │ └── Solution.java │ ├── hard │ ├── _025 │ │ └── Solution.java │ ├── _004 │ │ └── Solution.java │ ├── _068 │ │ └── Solution.java │ ├── _023 │ │ └── Solution.java │ ├── _030 │ │ └── Solution.java │ └── _010 │ │ └── Solution.java │ └── structure │ ├── ListNode.java │ ├── Interval.java │ └── TreeNode.java └── Companies.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.iml 3 | .idea 4 | out 5 | -------------------------------------------------------------------------------- /note/011/water.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awesome-interview/awesome-java-leetcode/master/note/011/water.png -------------------------------------------------------------------------------- /note/004/my_draw.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awesome-interview/awesome-java-leetcode/master/note/004/my_draw.jpg -------------------------------------------------------------------------------- /src/com/blankj/easy/_069/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._069; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/08 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int mySqrt(int x) { 13 | long n = x; 14 | while (n * n > x) { 15 | n = (n + x / n) >> 1; 16 | } 17 | return (int) n; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.mySqrt(10)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_070/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._070; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/09 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int climbStairs(int n) { 13 | int a = 1, b = 1; 14 | while (--n > 0) { 15 | b += a; 16 | a = b - a; 17 | } 18 | return b; 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | System.out.println(solution.climbStairs(3)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_058/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._058; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/05 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int lengthOfLastWord(String s) { 13 | int p = s.length() - 1; 14 | while (p >= 0 && s.charAt(p) == ' ') p--; 15 | int end = p; 16 | while (p >= 0 && s.charAt(p) != ' ') p--; 17 | return end - p; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.lengthOfLastWord("word ")); 23 | System.out.println(solution.lengthOfLastWord("hello world")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_122/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._122; 2 | 3 | 4 | /** 5 | *
6 | * author: Blankj 7 | * blog : http://blankj.com 8 | * time : 2017/10/11 9 | * desc : 10 | *11 | */ 12 | public class Solution { 13 | public int maxProfit(int[] prices) { 14 | int max = 0; 15 | for (int i = 1; i < prices.length; ++i) { 16 | if (prices[i] > prices[i - 1]) max += prices[i] - prices[i - 1]; 17 | } 18 | return max; 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | System.out.println(solution.maxProfit(new int[]{7, 1, 5, 3, 6, 4})); 24 | System.out.println(solution.maxProfit(new int[]{7, 6, 4, 3, 1})); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_050/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._050; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/18 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public double myPow(double x, int n) { 13 | if (n < 0) return helper(1 / x, -n); 14 | return helper(x, n); 15 | } 16 | 17 | private double helper(double x, int n) { 18 | if (n == 0) return 1; 19 | if (n == 1) return x; 20 | double d = helper(x, n >>> 1); 21 | if (n % 2 == 0) return d * d; 22 | return d * d * x; 23 | } 24 | 25 | public static void main(String[] args) { 26 | Solution solution = new Solution(); 27 | System.out.println(solution.myPow(8.88023, 3)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_007/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._007; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/19 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int reverse(int x) { 13 | long res = 0; 14 | for (; x != 0; x /= 10) 15 | res = res * 10 + x % 10; 16 | return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; 17 | } 18 | 19 | public static void main(String[] args) { 20 | Solution solution = new Solution(); 21 | System.out.println(solution.reverse(123)); 22 | System.out.println(solution.reverse(-123)); 23 | System.out.println(solution.reverse(100)); 24 | System.out.println(solution.reverse(1000000003)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/com/blankj/easy/_119/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._119; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | *
9 | * author: Blankj 10 | * blog : http://blankj.com 11 | * time : 2017/10/11 12 | * desc : 13 | *14 | */ 15 | public class Solution { 16 | public List
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/09 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public int maxDepth(TreeNode root) { 16 | if (root == null) return 0; 17 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.maxDepth(TreeNode.createTestData("[]"))); 23 | System.out.println(solution.maxDepth(TreeNode.createTestData("[1,2,2,3,4,4,3]"))); 24 | System.out.println(solution.maxDepth(TreeNode.createTestData("[9,-42,-42,null,76,76,null,null,13,null,13]"))); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_121/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._121; 2 | 3 | 4 | /** 5 | *
6 | * author: Blankj 7 | * blog : http://blankj.com 8 | * time : 2017/10/11 9 | * desc : 10 | *11 | */ 12 | public class Solution { 13 | public int maxProfit(int[] prices) { 14 | int max = 0, minPrice = Integer.MAX_VALUE; 15 | for (int i = 0; i < prices.length; ++i) { 16 | if (prices[i] < minPrice) minPrice = prices[i]; 17 | int delta = prices[i] - minPrice; 18 | if (delta > max) max = delta; 19 | } 20 | return max; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Solution solution = new Solution(); 25 | System.out.println(solution.maxProfit(new int[]{7, 1, 5, 3, 6, 4})); 26 | System.out.println(solution.maxProfit(new int[]{7, 6, 4, 3, 1})); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_027/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._027; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/31 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int removeElement(int[] nums, int val) { 13 | int tail = 0; 14 | for (int i = 0, len = nums.length; i < len; ++i) { 15 | if (nums[i] != val) { 16 | nums[tail++] = nums[i]; 17 | } 18 | } 19 | return tail; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Solution solution = new Solution(); 24 | int[] data = new int[]{0, 3, 1, 1, 2, 3, 3, 3}; 25 | int len = solution.removeElement(data, 3); 26 | for (int i = 0; i < len; i++) { 27 | System.out.print(data[i] + (i == len - 1 ? "" : ", ")); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_112/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._112; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/11 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public boolean hasPathSum(TreeNode root, int sum) { 16 | if (root == null) return false; 17 | if (root.left == null && root.right == null) return sum == root.val; 18 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | TreeNode testData = TreeNode.createTestData("[5,4,8,11,null,13,4,7,2,null,null,null,1]"); 24 | TreeNode.print(testData); 25 | System.out.println(solution.hasPathSum(testData, 22)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_543/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._543; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/13 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | int max = 0; 16 | 17 | public int diameterOfBinaryTree(TreeNode root) { 18 | helper(root); 19 | return max; 20 | } 21 | 22 | private int helper(TreeNode root) { 23 | if (root == null) return 0; 24 | int l = helper(root.left); 25 | int r = helper(root.right); 26 | if (l + r > max) max = l + r; 27 | return Math.max(l, r) + 1; 28 | } 29 | 30 | public static void main(String[] args) { 31 | Solution solution = new Solution(); 32 | System.out.println(solution.diameterOfBinaryTree(TreeNode.createTestData("[1,2,3,4,5]"))); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_028/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._028; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/01 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int strStr(String haystack, String needle) { 13 | int l1 = haystack.length(), l2 = needle.length(); 14 | if (l1 < l2) return -1; 15 | for (int i = 0; ; i++) { 16 | if (i + l2 > l1) return -1; 17 | for (int j = 0; ; j++) { 18 | if (j == l2) return i; 19 | if (haystack.charAt(i + j) != needle.charAt(j)) break; 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | System.out.println(solution.strStr("12345", "23")); 27 | System.out.println(solution.strStr("12345", "")); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_011/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._011; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/23 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int maxArea(int[] height) { 13 | int l = 0, r = height.length - 1; 14 | int max = 0, h = 0; 15 | while (l < r) { 16 | h = Math.min(height[l], height[r]); 17 | max = Math.max(max, (r - l) * h); 18 | while (height[l] <= h && l < r) ++l; 19 | while (height[r] <= h && l < r) --r; 20 | } 21 | return max; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | System.out.println(solution.maxArea(new int[]{1, 2, 4, 3})); // 4 27 | System.out.println(solution.maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));// 49 28 | } 29 | } -------------------------------------------------------------------------------- /note/031/README.md: -------------------------------------------------------------------------------- 1 | # [Next Permutation][title] 2 | 3 | ## Description 4 | 5 | Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers. 6 | 7 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 8 | 9 | The replacement must be **in-place** and use only constant extra memory. 10 | 11 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 12 | 13 | `1,2,3` → `1,3,2` 14 | `3,2,1` → `1,2,3` 15 | `1,1,5` → `1,5,1` 16 | 17 | **Tags:** Array 18 | 19 | 20 | ## 思路 21 | 22 | 题意是 23 | 24 | ```java 25 | 26 | ``` 27 | 28 | 29 | ## 结语 30 | 31 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 32 | 33 | 34 | 35 | [title]: https://leetcode.com/problems/next-permutation 36 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 37 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_026/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._026; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/30 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int removeDuplicates(int[] nums) { 13 | int len = nums.length; 14 | if (len <= 1) return len; 15 | int tail = 1; 16 | for (int i = 1; i < len; ++i) { 17 | if (nums[i - 1] != nums[i]) { 18 | nums[tail++] = nums[i]; 19 | } 20 | } 21 | return tail; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | int[] data = new int[]{0, 1, 1, 2, 3, 3, 3}; 27 | int len = solution.removeDuplicates(data); 28 | for (int i = 0; i < len; i++) { 29 | System.out.print(data[i] + (i == len - 1 ? "" : ", ")); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_012/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._012; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2018/01/25 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String intToRoman(int num) { 13 | String M[] = {"", "M", "MM", "MMM"}; 14 | String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 15 | String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 16 | String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 17 | return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.intToRoman(621));// DCXXI 23 | System.out.println(solution.intToRoman(348));// CCCXLVIII 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_014/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._014; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/26 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String longestCommonPrefix(String[] strs) { 13 | int len = strs.length; 14 | if (len == 0) return ""; 15 | int minLen = 0x7fffffff; 16 | for (String str : strs) minLen = Math.min(minLen, str.length()); 17 | for (int j = 0; j < minLen; ++j) 18 | for (int i = 1; i < len; ++i) 19 | if (strs[0].charAt(j) != strs[i].charAt(j)) 20 | return strs[0].substring(0, j); 21 | return strs[0].substring(0, minLen); 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | System.out.println(solution.longestCommonPrefix(new String[]{"abc", "abcd", "ab"})); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_083/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._083; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/05/10 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode deleteDuplicates(ListNode head) { 15 | if (head == null || head.next == null) return head; 16 | ListNode curr = head; 17 | while (curr.next != null) { 18 | if (curr.next.val == curr.val) { 19 | curr.next = curr.next.next; 20 | } else { 21 | curr = curr.next; 22 | } 23 | } 24 | return head; 25 | } 26 | 27 | public static void main(String[] args) { 28 | Solution solution = new Solution(); 29 | ListNode.print(solution.deleteDuplicates(ListNode.createTestData("[1,1,2]"))); 30 | ListNode.print(solution.deleteDuplicates(ListNode.createTestData("[1,1,2,3,3]"))); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_035/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._035; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/02 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int searchInsert(int[] nums, int target) { 13 | int left = 0, right = nums.length - 1, mid = (right + left) >> 1; 14 | while (left <= right) { 15 | if (target <= nums[mid]) right = mid - 1; 16 | else left = mid + 1; 17 | mid = (right + left) >> 1; 18 | } 19 | return left; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Solution solution = new Solution(); 24 | int[] nums = new int[]{1, 3, 5, 6}; 25 | System.out.println(solution.searchInsert(nums, 5)); 26 | System.out.println(solution.searchInsert(nums, 2)); 27 | System.out.println(solution.searchInsert(nums, 7)); 28 | System.out.println(solution.searchInsert(nums, 0)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_033/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._033; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/16 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int search(int[] nums, int target) { 13 | int l = 0, r = nums.length - 1, mid; 14 | while (l <= r) { 15 | mid = l + r >>> 1; 16 | if (nums[mid] == target) return mid; 17 | else if (nums[mid] >= nums[l]) { 18 | if (nums[l] <= target && target < nums[mid]) r = mid - 1; 19 | else l = mid + 1; 20 | } else { 21 | if (nums[mid] < target && target <= nums[r]) l = mid + 1; 22 | else r = mid - 1; 23 | } 24 | } 25 | return -1; 26 | } 27 | 28 | public static void main(String[] args) { 29 | Solution solution = new Solution(); 30 | System.out.println(solution.search(new int[]{2, 1}, 1)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_108/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._108; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/09 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public TreeNode sortedArrayToBST(int[] nums) { 16 | if (nums == null || nums.length == 0) return null; 17 | return helper(nums, 0, nums.length - 1); 18 | } 19 | 20 | private TreeNode helper(int[] nums, int left, int right) { 21 | if (left > right) return null; 22 | int mid = (left + right) >>> 1; 23 | TreeNode node = new TreeNode(nums[mid]); 24 | node.left = helper(nums, left, mid - 1); 25 | node.right = helper(nums, mid + 1, right); 26 | return node; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | TreeNode.print(solution.sortedArrayToBST(new int[]{0, 1, 2, 3, 4, 5, 6, 7})); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_088/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._088; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/06/01 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public void merge(int[] nums1, int m, int[] nums2, int n) { 15 | int p = m-- + n-- - 1; 16 | while (m >= 0 && n >= 0) 17 | nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; 18 | while (n >= 0) 19 | nums1[p--] = nums2[n--]; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Solution solution = new Solution(); 24 | int[] nums1 = new int[10]; 25 | for (int i = 0; i < 5; ++i) { 26 | nums1[i] = 2 * i; 27 | } 28 | int[] nums2 = new int[5]; 29 | for (int i = 0; i < 5; ++i) { 30 | nums2[i] = 2 * i + 1; 31 | } 32 | solution.merge(nums1, 5, nums2, 5); 33 | System.out.println(Arrays.toString(nums1)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_110/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._110; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/09 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public boolean isBalanced(TreeNode root) { 16 | return helper(root) != -1; 17 | } 18 | 19 | private int helper(TreeNode node) { 20 | if (node == null) return 0; 21 | int l = helper(node.left); 22 | if (l == -1) return -1; 23 | int r = helper(node.right); 24 | if (r == -1) return -1; 25 | if (Math.abs(l - r) > 1) return -1; 26 | return 1 + Math.max(l, r); 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | TreeNode testData = TreeNode.createTestData("[1,2,2,3,3,3,3,4,4,4,4,4,4,null,null,5,5]"); 32 | TreeNode.print(testData); 33 | System.out.println(solution.isBalanced(testData)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_066/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._066; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/05/06 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public int[] plusOne(int[] digits) { 15 | int p = digits.length - 1; 16 | if (digits[p] < 9) { 17 | digits[p] = ++digits[p]; 18 | } else { 19 | do { 20 | digits[p--] = 0; 21 | } while (p >= 0 && digits[p] == 9); 22 | if (digits[0] != 0) { 23 | ++digits[p]; 24 | } else { 25 | digits = new int[digits.length + 1]; 26 | digits[0] = 1; 27 | } 28 | } 29 | return digits; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | int[] digits = solution.plusOne(new int[]{9, 9, 9}); 35 | System.out.println(Arrays.toString(digits)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_100/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._100; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/08 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public boolean isSameTree(TreeNode p, TreeNode q) { 16 | if (p == null || q == null) return p == q; 17 | if (p.val != q.val) return false; 18 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | System.out.println(solution.isSameTree( 24 | TreeNode.createTestData("[1,2,2,null,3,null,3]"), 25 | TreeNode.createTestData("[1,2,2,null,3,null,3]")) 26 | ); 27 | System.out.println(solution.isSameTree( 28 | TreeNode.createTestData("[1,2,2,null,3,null,3]"), 29 | TreeNode.createTestData("[1,2,2,null,3,null,null]")) 30 | ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_029/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._029; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2018/01/31 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int divide(int dividend, int divisor) { 13 | if (dividend == Integer.MIN_VALUE && divisor == -1) { 14 | return Integer.MAX_VALUE; 15 | } 16 | long dvd = Math.abs((long) dividend); 17 | long dvr = Math.abs((long) divisor); 18 | int res = 0; 19 | while (dvd >= dvr) { 20 | long temp = dvr, multiple = 1; 21 | while (dvd >= temp << 1) { 22 | temp <<= 1; 23 | multiple <<= 1; 24 | } 25 | dvd -= temp; 26 | res += multiple; 27 | } 28 | return (dividend < 0) ^ (divisor < 0) ? -res : res; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Solution solution = new Solution(); 33 | System.out.println(solution.divide(-2147483648, 1)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_020/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._020; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/28 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public boolean isValid(String s) { 13 | char[] stack = new char[s.length() + 1]; 14 | int top = 1; 15 | for (char c : s.toCharArray()) { 16 | if (c == '(' || c == '[' || c == '{') { 17 | stack[top++] = c; 18 | } else if (c == ')' && stack[--top] != '(') { 19 | return false; 20 | } else if (c == ']' && stack[--top] != '[') { 21 | return false; 22 | } else if (c == '}' && stack[--top] != '{') { 23 | return false; 24 | } 25 | } 26 | return top == 1; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | System.out.println(solution.isValid("()[]{}({[]})")); 32 | System.out.println(solution.isValid("(])]")); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_019/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._019; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/04/27 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode removeNthFromEnd(ListNode head, int n) { 15 | ListNode pre = head; 16 | ListNode afterPreN = head; 17 | while (n-- != 0) { 18 | afterPreN = afterPreN.next; 19 | } 20 | if (afterPreN != null) { 21 | while (afterPreN.next != null) { 22 | pre = pre.next; 23 | afterPreN = afterPreN.next; 24 | } 25 | pre.next = pre.next.next; 26 | } else { 27 | head = head.next; 28 | } 29 | return head; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | ListNode.print(solution.removeNthFromEnd(ListNode.createTestData("[1,2,3,4,5]"), 2)); 35 | ListNode.print(solution.removeNthFromEnd(ListNode.createTestData("[1]"), 1)); 36 | } 37 | } -------------------------------------------------------------------------------- /src/com/blankj/easy/_038/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._038; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/03 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String countAndSay(int n) { 13 | String str = "1"; 14 | while (--n > 0) { 15 | int times = 1; 16 | StringBuilder sb = new StringBuilder(); 17 | char[] chars = str.toCharArray(); 18 | int len = chars.length; 19 | for (int j = 1; j < len; j++) { 20 | if (chars[j - 1] == chars[j]) { 21 | times++; 22 | } else { 23 | sb.append(times).append(chars[j - 1]); 24 | times = 1; 25 | } 26 | } 27 | str = sb.append(times).append(chars[len - 1]).toString(); 28 | } 29 | return str; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | for (int i = 1; i < 6; i++) { 35 | System.out.println(solution.countAndSay(i)); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_118/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._118; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Collections; 6 | import java.util.List; 7 | 8 | /** 9 | *
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/11 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/11 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int lengthOfLongestSubstring(String s) { 13 | int len; 14 | if (s == null || (len = s.length()) == 0) return 0; 15 | int preP = 0, max = 0; 16 | int[] hash = new int[128]; 17 | for (int i = 0; i < len; ++i) { 18 | char c = s.charAt(i); 19 | if (hash[c] > preP) { 20 | preP = hash[c]; 21 | } 22 | int l = i - preP + 1; 23 | hash[c] = i + 1; 24 | if (l > max) max = l; 25 | } 26 | return max; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | System.out.println(solution.lengthOfLongestSubstring("abcabcbb")); 32 | System.out.println(solution.lengthOfLongestSubstring("bbbbb")); 33 | System.out.println(solution.lengthOfLongestSubstring("pwwkew")); 34 | System.out.println(solution.lengthOfLongestSubstring("Abcabcbb")); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_021/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._021; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/04/29 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 15 | ListNode head = new ListNode(0); 16 | ListNode temp = head; 17 | while (l1 != null && l2 != null) { 18 | if (l1.val < l2.val) { 19 | temp.next = l1; 20 | l1 = l1.next; 21 | } else { 22 | temp.next = l2; 23 | l2 = l2.next; 24 | } 25 | temp = temp.next; 26 | } 27 | temp.next = l1 != null ? l1 : l2; 28 | return head.next; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Solution solution = new Solution(); 33 | ListNode listNode0 = ListNode.createTestData("[1,3,5,7,9]"); 34 | ListNode listNode1 = ListNode.createTestData("[2,4,6,8,10]"); 35 | ListNode.print(listNode0); 36 | ListNode.print(listNode1); 37 | ListNode.print(solution.mergeTwoLists(listNode0, listNode1)); 38 | } 39 | } -------------------------------------------------------------------------------- /src/com/blankj/medium/_024/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._024; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2018/01/31 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | // public ListNode swapPairs(ListNode head) { 15 | // if (head == null || head.next == null) return head; 16 | // ListNode node = head.next; 17 | // head.next = swapPairs(node.next); 18 | // node.next = head; 19 | // return node; 20 | // } 21 | 22 | public ListNode swapPairs(ListNode head) { 23 | ListNode preHead = new ListNode(0), cur = preHead; 24 | preHead.next = head; 25 | while (cur.next != null && cur.next.next != null) { 26 | ListNode temp = cur.next.next; 27 | cur.next.next = temp.next; 28 | temp.next = cur.next; 29 | cur.next = temp; 30 | cur = cur.next.next; 31 | } 32 | return preHead.next; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | ListNode.print(solution.swapPairs(ListNode.createTestData("[1,2,3,4]"))); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_013/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._013; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/04/25 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public int romanToInt(String s) { 16 | Map
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2018/01/25 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public int threeSumClosest(int[] nums, int target) { 15 | int delta = 0x7fffffff, res = 0; 16 | Arrays.sort(nums); 17 | int len = nums.length - 2; 18 | for (int i = 0; i < len; i++) { 19 | int left = i + 1, right = nums.length - 1; 20 | while (left < right) { 21 | int sum = nums[i] + nums[left] + nums[right]; 22 | int curDelta = Math.abs(sum - target); 23 | if (curDelta == 0) return sum; 24 | if (curDelta < delta) { 25 | delta = curDelta; 26 | res = sum; 27 | } 28 | if (sum > target) --right; 29 | else ++left; 30 | } 31 | } 32 | return res; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | System.out.println(solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /note/058/README.md: -------------------------------------------------------------------------------- 1 | # [Length of Last Word][title] 2 | 3 | ## Description 4 | 5 | Given a string *s* consists of upper/lower-case alphabets and empty space characters `' '`, return the length of last word in the string. 6 | 7 | If the last word does not exist, return 0. 8 | 9 | **Note:** A word is defined as a character sequence consists of non-space characters only. 10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: "Hello World" 15 | Output: 5 16 | ``` 17 | 18 | **Tags:** String 19 | 20 | 21 | ## 思路 22 | 23 | 题意是让你从一个只包含大小字母和空格字符的字符串中得到最后一个单词的长度,很简单,我们倒序遍历,先得到最后一个非空格字符的索引,然后再得到它前面的空格字符索引,两者相减即可。当然,我们使用 API 来完成这件事更加方便,只需一行代码 `return s.trim().length() - s.trim().lastIndexOf(" ") - 1;`,但我相信作者出这道题的目的肯定不是考你 API 的使用,所以我们还是用自己的思路来实现。 24 | 25 | ```java 26 | class Solution { 27 | public int lengthOfLastWord(String s) { 28 | int p = s.length() - 1; 29 | while (p >= 0 && s.charAt(p) == ' ') p--; 30 | int end = p; 31 | while (p >= 0 && s.charAt(p) != ' ') p--; 32 | return end - p; 33 | } 34 | } 35 | ``` 36 | 37 | 38 | ## 结语 39 | 40 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 41 | 42 | 43 | 44 | [title]: https://leetcode.com/problems/length-of-last-word 45 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 46 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_002/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._002; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/10/11 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 15 | ListNode node = new ListNode(0); 16 | ListNode n1 = l1, n2 = l2, t = node; 17 | int sum = 0; 18 | while (n1 != null || n2 != null) { 19 | sum /= 10; 20 | if (n1 != null) { 21 | sum += n1.val; 22 | n1 = n1.next; 23 | } 24 | if (n2 != null) { 25 | sum += n2.val; 26 | n2 = n2.next; 27 | } 28 | t.next = new ListNode(sum % 10); 29 | t = t.next; 30 | } 31 | if (sum / 10 != 0) t.next = new ListNode(1); 32 | return node.next; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | ListNode.print(solution.addTwoNumbers( 38 | ListNode.createTestData("[2,4,3]"), 39 | ListNode.createTestData("[5,6,4]") 40 | )); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /note/007/README.md: -------------------------------------------------------------------------------- 1 | # [Reverse Integer][title] 2 | 3 | ## Description 4 | 5 | Given a 32-bit signed integer, reverse digits of an integer. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 123 11 | Output: 321 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: -123 18 | Output: -321 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: 120 25 | Output: 21 26 | ``` 27 | 28 | **Note:** 29 | 30 | Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 31 | 32 | **Tags:** Math 33 | 34 | 35 | ## 思路 36 | 37 | 题意是给你一个整型数,求它的逆序整型数,而且有个小坑点,当它的逆序整型数溢出的话,那么就返回 0,用我们代码表示的话可以求得结果保存在 long 中,最后把结果和整型的两个范围比较即可。 38 | 39 | ```java 40 | class Solution { 41 | public int reverse(int x) { 42 | long res = 0; 43 | for (; x != 0; x /= 10) 44 | res = res * 10 + x % 10; 45 | return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; 46 | } 47 | } 48 | ``` 49 | 50 | 51 | ## 结语 52 | 53 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 54 | 55 | 56 | 57 | [title]: https://leetcode.com/problems/reverse-integer 58 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 59 | -------------------------------------------------------------------------------- /note/104/README.md: -------------------------------------------------------------------------------- 1 | # [Maximum Depth of Binary Tree][title] 2 | 3 | ## Description 4 | 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 8 | 9 | **Note:** A leaf is a node with no children. 10 | 11 | **Example:** 12 | 13 | Given binary tree `[3,9,20,null,null,15,7]`, 14 | 15 | ``` 16 | 3 17 | / \ 18 | 9 20 19 | / \ 20 | 15 7 21 | ``` 22 | 23 | return its depth = 3. 24 | 25 | **Tags:** Tree, Depth-first Search 26 | 27 | 28 | ## 思路 29 | 30 | 题意是找到二叉树的最大深度,很明显,深搜即可,每深入一次节点加一即可,然后取左右子树的最大深度。 31 | 32 | ```java 33 | /** 34 | * Definition for a binary tree node. 35 | * public class TreeNode { 36 | * int val; 37 | * TreeNode left; 38 | * TreeNode right; 39 | * TreeNode(int x) { val = x; } 40 | * } 41 | */ 42 | class Solution { 43 | public int maxDepth(TreeNode root) { 44 | if (root == null) return 0; 45 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 46 | } 47 | } 48 | ``` 49 | 50 | 51 | ## 结语 52 | 53 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 54 | 55 | 56 | 57 | [title]: https://leetcode.com/problems/maximum-depth-of-binary-tree 58 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 59 | -------------------------------------------------------------------------------- /note/069/README.md: -------------------------------------------------------------------------------- 1 | # [Sqrt(x)][title] 2 | 3 | ## Description 4 | 5 | Implement `int sqrt(int x)`. 6 | 7 | Compute and return the square root of *x*, where *x* is guaranteed to be a non-negative integer. 8 | 9 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: 4 15 | Output: 2 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: 8 22 | Output: 2 23 | Explanation: The square root of 8 is 2.82842..., and since 24 | the decimal part is truncated, 2 is returned. 25 | ``` 26 | 27 | **Tags:** Binary Search, Math 28 | 29 | 30 | ## 思路 31 | 32 | 题意是求平方根,参考 [牛顿迭代法求平方根](https://wenku.baidu.com/view/6b74c622bcd126fff7050bfe.html),然后再参考维基百科的 [Integer square root](https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division) 即可。 33 | 34 | ```java 35 | class Solution { 36 | public int mySqrt(int x) { 37 | long n = x; 38 | while (n * n > x) { 39 | n = (n + x / n) >> 1; 40 | } 41 | return (int) n; 42 | } 43 | } 44 | ``` 45 | 46 | 47 | ## 结语 48 | 49 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 50 | 51 | 52 | 53 | [title]: https://leetcode.com/problems/sqrtx 54 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 55 | -------------------------------------------------------------------------------- /note/119/README.md: -------------------------------------------------------------------------------- 1 | # [Pascal's Triangle II][title] 2 | 3 | ## Description 4 | 5 | Given a non-negative index *k* where *k* ≤ 33, return the *k*th index row of the Pascal's triangle. 6 | 7 | Note that the row index starts from 0. 8 | 9 |  10 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 11 | 12 | **Example:** 13 | 14 | ``` 15 | Input: 3 16 | Output: [1,3,3,1] 17 | ``` 18 | 19 | **Follow up:** 20 | 21 | Could you optimize your algorithm to use only *O*(*k*) extra space? 22 | 23 | **Tags:** Array 24 | 25 | 26 | ## 思路 27 | 28 | 题意是指定输出帕斯卡尔三角形的某一行,模拟即可,优化后的代码如下所示。 29 | 30 | ```java 31 | class Solution { 32 | public List
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/04/21 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | // public int[] twoSum(int[] nums, int target) { 16 | // for (int i = 0; i < nums.length; ++i) { 17 | // for (int j = i + 1; j < nums.length; ++j) { 18 | // if (nums[i] + nums[j] == target) { 19 | // return new int[]{i, j}; 20 | // } 21 | // } 22 | // } 23 | // return null; 24 | // } 25 | 26 | public int[] twoSum(int[] nums, int target) { 27 | int len = nums.length; 28 | HashMap
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/09 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public List
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/10/16 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode reverseKGroup(ListNode head, int k) { 15 | if (head == null || k == 1) return head; 16 | ListNode node = new ListNode(0), pre = node; 17 | node.next = head; 18 | for (int i = 1; head != null; ++i) { 19 | if (i % k == 0) { 20 | pre = reverse(pre, head.next); 21 | head = pre.next; 22 | } else { 23 | head = head.next; 24 | } 25 | } 26 | return node.next; 27 | } 28 | 29 | private ListNode reverse(ListNode pre, ListNode next) { 30 | ListNode head = pre.next; 31 | ListNode move = head.next; 32 | while (move != next) { 33 | head.next = move.next; 34 | move.next = pre.next; 35 | pre.next = move; 36 | move = head.next; 37 | } 38 | return head; 39 | } 40 | 41 | public static void main(String[] args) { 42 | Solution solution = new Solution(); 43 | ListNode.print(solution.reverseKGroup(ListNode.createTestData("[1,2,3,4,5,6,7,8]"), 3)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_009/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._009; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/24 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // public boolean isPalindrome(int x) { 13 | // if (x < 0) return false; 14 | // int copyX = x, reverse = 0; 15 | // while (copyX > 0) { 16 | // reverse = reverse * 10 + copyX % 10; 17 | // copyX /= 10; 18 | // } 19 | // return x == reverse; 20 | // } 21 | 22 | public boolean isPalindrome(int x) { 23 | if (x < 0 || (x != 0 && x % 10 == 0)) return false; 24 | int halfReverseX = 0; 25 | while (x > halfReverseX) { 26 | halfReverseX = halfReverseX * 10 + x % 10; 27 | x /= 10; 28 | } 29 | return halfReverseX == x || halfReverseX / 10 == x; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | System.out.println(solution.isPalindrome(-1)); 35 | System.out.println(solution.isPalindrome(10010)); 36 | 37 | System.out.println(solution.isPalindrome(0)); 38 | System.out.println(solution.isPalindrome(11)); 39 | System.out.println(solution.isPalindrome(111)); 40 | System.out.println(solution.isPalindrome(222222222)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /note/083/README.md: -------------------------------------------------------------------------------- 1 | # [Remove Duplicates from Sorted List][title] 2 | 3 | ## Description 4 | 5 | Given a sorted linked list, delete all duplicates such that each element appear only *once*. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 1->1->2 11 | Output: 1->2 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: 1->1->2->3->3 18 | Output: 1->2->3 19 | ``` 20 | 21 | **Tags:** Linked List 22 | 23 | 24 | ## 思路 25 | 26 | 题意是删除链表中重复的元素,很简单,我们只需要遍历一遍链表,遇到链表中相邻元素相同时,把当前指针指向下下个元素即可。 27 | 28 | ```java 29 | /** 30 | * Definition for singly-linked list. 31 | * public class ListNode { 32 | * int val; 33 | * ListNode next; 34 | * ListNode(int x) { val = x; } 35 | * } 36 | */ 37 | class Solution { 38 | public ListNode deleteDuplicates(ListNode head) { 39 | if (head == null || head.next == null) return head; 40 | ListNode curr = head; 41 | while (curr.next != null) { 42 | if (curr.next.val == curr.val) { 43 | curr.next = curr.next.next; 44 | } else { 45 | curr = curr.next; 46 | } 47 | } 48 | return head; 49 | } 50 | } 51 | ``` 52 | 53 | 54 | ## 结语 55 | 56 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 57 | 58 | 59 | 60 | [title]: https://leetcode.com/problems/remove-duplicates-from-sorted-list 61 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 62 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_043/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._043; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/17 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String multiply(String num1, String num2) { 13 | if (num1.equals("0") || num2.equals("0")) return "0"; 14 | int l1 = num1.length(), l2 = num2.length(), l = l1 + l2; 15 | char[] ans = new char[l]; 16 | char[] c1 = num1.toCharArray(); 17 | char[] c2 = num2.toCharArray(); 18 | for (int i = l1 - 1; i >= 0; --i) { 19 | int c = c1[i] - '0'; 20 | for (int j = l2 - 1; j >= 0; --j) { 21 | ans[i + j + 1] += c * (c2[j] - '0'); 22 | } 23 | } 24 | for (int i = l - 1; i > 0; --i) { 25 | if (ans[i] > 9) { 26 | ans[i - 1] += ans[i] / 10; 27 | ans[i] %= 10; 28 | } 29 | } 30 | StringBuilder sb = new StringBuilder(); 31 | int i = 0; 32 | for (; ; ++i) if (ans[i] != 0) break; 33 | for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0')); 34 | return sb.toString(); 35 | } 36 | 37 | public static void main(String[] args) { 38 | Solution solution = new Solution(); 39 | System.out.println(solution.multiply("132", "19")); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /note/070/README.md: -------------------------------------------------------------------------------- 1 | # [Climbing Stairs][title] 2 | 3 | ## Description 4 | 5 | You are climbing a stair case. It takes *n* steps to reach to the top. 6 | 7 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 8 | 9 | **Note:** Given *n* will be a positive integer. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: 2 15 | Output: 2 16 | Explanation: There are two ways to climb to the top. 17 | 1. 1 step + 1 step 18 | 2. 2 steps 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: 3 25 | Output: 3 26 | Explanation: There are three ways to climb to the top. 27 | 1. 1 step + 1 step + 1 step 28 | 2. 1 step + 2 steps 29 | 3. 2 steps + 1 step 30 | ``` 31 | 32 | **Tags:** Dynamic Programming 33 | 34 | 35 | ## 思路 36 | 37 | 题意是爬楼梯,每次你只能爬一步或者两步,问到顶层共有多少种方案。我们假设到顶层共有 `f(n)` 种,那么 `f(n) = f(n - 1) + f(n - 2)` 肯定是成立的,意思就是我们迈向顶层的最后一步是在倒数第一级台阶或者在倒数第二级台阶。算法我对空间复杂度进行了优化,因为在迭代过程中只需要两个变量即可。 38 | 39 | ```java 40 | class Solution { 41 | public int climbStairs(int n) { 42 | int a = 1, b = 1; 43 | while (--n > 0) { 44 | b += a; 45 | a = b - a; 46 | } 47 | return b; 48 | } 49 | } 50 | ``` 51 | 52 | 53 | ## 结语 54 | 55 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 56 | 57 | 58 | 59 | [title]: https://leetcode.com/problems/climbing-stairs 60 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 61 | -------------------------------------------------------------------------------- /note/050/README.md: -------------------------------------------------------------------------------- 1 | # [Pow(x, n)][title] 2 | 3 | ## Description 4 | 5 | Implement [pow(*x*, *n*)](http://www.cplusplus.com/reference/valarray/pow/), which calculates *x* raised to the power *n* (xn). 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 2.00000, 10 11 | Output: 1024.00000 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: 2.10000, 3 18 | Output: 9.26100 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: 2.00000, -2 25 | Output: 0.25000 26 | Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 27 | ``` 28 | 29 | **Note:** 30 | 31 | - -100.0 < *x* < 100.0 32 | - *n* is a 32-bit signed integer, within the range [−231, 231 − 1] 33 | 34 | **Tags:** Math, Binary Search 35 | 36 | 37 | ## 思路 38 | 39 | 题意是让你计算 `x^n`,如果直接计算肯定会超时,那么我们可以想到可以使用二分法来降低时间复杂度。 40 | 41 | ```java 42 | class Solution { 43 | public double myPow(double x, int n) { 44 | if (n < 0) return helper(1 / x, -n); 45 | return helper(x, n); 46 | } 47 | 48 | private double helper(double x, int n) { 49 | if (n == 0) return 1; 50 | if (n == 1) return x; 51 | double d = helper(x, n >>> 1); 52 | if (n % 2 == 0) return d * d; 53 | return d * d * x; 54 | } 55 | } 56 | ``` 57 | 58 | 59 | ## 结语 60 | 61 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 62 | 63 | 64 | 65 | [title]: https://leetcode.com/problems/powx-n 66 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 67 | -------------------------------------------------------------------------------- /note/035/README.md: -------------------------------------------------------------------------------- 1 | # [Search Insert Position][title] 2 | 3 | ## Description 4 | 5 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 6 | 7 | You may assume no duplicates in the array. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: [1,3,5,6], 5 13 | Output: 2 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: [1,3,5,6], 2 20 | Output: 1 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: [1,3,5,6], 7 27 | Output: 4 28 | ``` 29 | 30 | **Example 1:** 31 | 32 | ``` 33 | Input: [1,3,5,6], 0 34 | Output: 0 35 | ``` 36 | 37 | **Tags:** Array, Binary Search 38 | 39 | 40 | ## 思路 41 | 42 | 题意是让你从一个没有重复元素的已排序数组中找到插入位置的索引。因为数组已排序,所以我们可以想到二分查找法,因为查找到的条件是找到第一个等于或者大于 `target` 的元素的位置,所以二分法略作变动即可。 43 | 44 | ```java 45 | class Solution { 46 | public int searchInsert(int[] nums, int target) { 47 | int left = 0, right = nums.length - 1, mid = (right + left) >> 1; 48 | while (left <= right) { 49 | if (target <= nums[mid]) right = mid - 1; 50 | else left = mid + 1; 51 | mid = (right + left) >> 1; 52 | } 53 | return left; 54 | } 55 | } 56 | ``` 57 | 58 | 59 | ## 结语 60 | 61 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 62 | 63 | 64 | 65 | [title]: https://leetcode.com/problems/search-insert-position 66 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 67 | -------------------------------------------------------------------------------- /note/088/README.md: -------------------------------------------------------------------------------- 1 | # [Merge Sorted Array][title] 2 | 3 | ## Description 4 | 5 | Given two sorted integer arrays *nums1* and *nums2*, merge *nums2* into *nums1* as one sorted array. 6 | 7 | **Note:** 8 | 9 | - The number of elements initialized in *nums1* and *nums2* are *m* and *n* respectively. 10 | - You may assume that *nums1* has enough space (size that is greater or equal to *m* + *n*) to hold additional elements from *nums2*. 11 | 12 | **Example:** 13 | 14 | ``` 15 | Input: 16 | nums1 = [1,2,3,0,0,0], m = 3 17 | nums2 = [2,5,6], n = 3 18 | 19 | Output: [1,2,2,3,5,6] 20 | ``` 21 | 22 | **Tags:** Array, Two Pointers 23 | 24 | 25 | ## 思路 26 | 27 | 题意是给两个已排序的数组 `nums1` 和 `nums2`,合并 `nums2` 到 `nums1` 中,两数组元素个数分别为 `m` 和 `n`,而且 `nums1` 数组的长度足够容纳 `m + n` 个元素,如果我们按顺序排下去,那肯定要开辟一个新数组来保存元素,如果我们选择逆序,这样利用 `nums1` 自身空间足矣,不会出现覆盖的情况,依次把大的元素插入到 `nums1` 的末尾,确保 `nums2` 中的元素全部插入到 `nums1` 即可。 28 | 29 | ```java 30 | class Solution { 31 | public void merge(int[] nums1, int m, int[] nums2, int n) { 32 | int p = m-- + n-- - 1; 33 | while (m >= 0 && n >= 0) 34 | nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; 35 | while (n >= 0) 36 | nums1[p--] = nums2[n--]; 37 | } 38 | } 39 | ``` 40 | 41 | 42 | ## 结语 43 | 44 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 45 | 46 | 47 | 48 | [title]: https://leetcode.com/problems/merge-sorted-array 49 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 50 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_049/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._049; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | *
12 | * author: Blankj 13 | * blog : http://blankj.com 14 | * time : 2017/10/18 15 | * desc : 16 | *17 | */ 18 | public class Solution { 19 | public List
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/13 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public int leastBricks(List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/18 8 | * desc : 9 | *10 | */ 11 | public class ListNode { 12 | 13 | public int val; 14 | public ListNode next; 15 | 16 | public ListNode(int x) { 17 | val = x; 18 | } 19 | 20 | /** 21 | * 创建测试数据 22 | * 23 | * @param data [XX,XX,XX] 24 | * @return {@link ListNode} 25 | */ 26 | public static ListNode createTestData(String data) { 27 | if (data.equals("[]")) return null; 28 | data = data.substring(1, data.length() - 1); 29 | String[] split = data.split(","); 30 | int len = split.length; 31 | ListNode[] listNode = new ListNode[len + 1]; 32 | listNode[0] = new ListNode(Integer.valueOf(split[0])); 33 | for (int i = 1; i < len; i++) { 34 | listNode[i] = new ListNode(Integer.valueOf(split[i])); 35 | listNode[i - 1].next = listNode[i]; 36 | } 37 | return listNode[0]; 38 | } 39 | 40 | public static void print(ListNode listNode) { 41 | if (listNode == null) { 42 | System.out.println("null"); 43 | return; 44 | } 45 | StringBuilder str = new StringBuilder("[" + String.valueOf(listNode.val)); 46 | ListNode p = listNode.next; 47 | while (p != null) { 48 | str.append(",").append(String.valueOf(p.val)); 49 | p = p.next; 50 | } 51 | System.out.println(str.append("]")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /note/003/README.md: -------------------------------------------------------------------------------- 1 | # [Longest Substring Without Repeating Characters][title] 2 | 3 | ## Description 4 | 5 | Given a string, find the length of the **longest substring** without repeating characters. 6 | 7 | **Examples:** 8 | 9 | Given `"abcabcbb"`, the answer is `"abc"`, which the length is 3. 10 | 11 | Given `"bbbbb"`, the answer is `"b"`, with the length of 1. 12 | 13 | Given `"pwwkew"`, the answer is `"wke"`, with the length of 3. Note that the answer must be a **substring**, `"pwke"` is a *subsequence* and not a substring. 14 | 15 | **Tags:** Hash Table, Two Pointers, String 16 | 17 | 18 | ## 思路 19 | 20 | 题意是计算不带重复字符的最长子字符串的长度,开辟一个 hash 数组来存储该字符上次出现的位置,比如 `hash[a] = 3` 就是代表 `a` 字符前一次出现的索引在 3,遍历该字符串,获取到上次出现的最大索引(只能向前,不能退后),与当前的索引做差获取的就是本次所需长度,从中迭代出最大值就是最终答案。 21 | 22 | ```java 23 | class Solution { 24 | public int lengthOfLongestSubstring(String s) { 25 | int len; 26 | if (s == null || (len = s.length()) == 0) return 0; 27 | int preP = 0, max = 0; 28 | int[] hash = new int[128]; 29 | for (int i = 0; i < len; ++i) { 30 | char c = s.charAt(i); 31 | if (hash[c] > preP) { 32 | preP = hash[c]; 33 | } 34 | int l = i - preP + 1; 35 | hash[c] = i + 1; 36 | if (l > max) max = l; 37 | } 38 | return max; 39 | } 40 | } 41 | ``` 42 | 43 | 44 | ## 结语 45 | 46 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 47 | 48 | 49 | 50 | [title]: https://leetcode.com/problems/longest-substring-without-repeating-characters 51 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 52 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_111/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._111; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | import java.util.LinkedList; 7 | 8 | /** 9 | *
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/10 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public int minDepth(TreeNode root) { 18 | // if (root == null) return 0; 19 | // int l = minDepth(root.left); 20 | // int r = minDepth(root.right); 21 | // if (l != 0 && r != 0) return 1 + Math.min(l, r); 22 | // return l + r + 1; 23 | // } 24 | 25 | public int minDepth(TreeNode root) { 26 | if (root == null) return 0; 27 | LinkedList
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/19 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/04 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // public int maxSubArray(int[] nums) { 13 | // int len = nums.length, dp = nums[0], max = dp; 14 | // for (int i = 1; i < len; ++i) { 15 | // dp = nums[i] + (dp > 0 ? dp : 0); 16 | // if (dp > max) max = dp; 17 | // } 18 | // return max; 19 | // } 20 | public int maxSubArray(int[] nums) { 21 | return helper(nums, 0, nums.length - 1); 22 | } 23 | 24 | private int helper(int[] nums, int left, int right) { 25 | if (left >= right) return nums[left]; 26 | int mid = (left + right) >> 1; 27 | int leftAns = helper(nums, left, mid); 28 | int rightAns = helper(nums, mid + 1, right); 29 | int leftMax = nums[mid], rightMax = nums[mid + 1]; 30 | int temp = 0; 31 | for (int i = mid; i >= left; --i) { 32 | temp += nums[i]; 33 | if (temp > leftMax) leftMax = temp; 34 | } 35 | temp = 0; 36 | for (int i = mid + 1; i <= right; ++i) { 37 | temp += nums[i]; 38 | if (temp > rightMax) rightMax = temp; 39 | } 40 | return Math.max(Math.max(leftAns, rightAns), leftMax + rightMax); 41 | } 42 | 43 | public static void main(String[] args) { 44 | Solution solution = new Solution(); 45 | int[] nums0 = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}; 46 | System.out.println(solution.maxSubArray(nums0)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /note/121/README.md: -------------------------------------------------------------------------------- 1 | # [Best Time to Buy and Sell Stock][title] 2 | 3 | ## Description 4 | 5 | Say you have an array for which the *i*th element is the price of a given stock on day *i*. 6 | 7 | If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 8 | 9 | Note that you cannot sell a stock before you buy one. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: [7,1,5,3,6,4] 15 | Output: 5 16 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 17 | Not 7-1 = 6, as selling price needs to be larger than buying price. 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: [7,6,4,3,1] 24 | Output: 0 25 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 26 | ``` 27 | 28 | **Tags:** Array, Dynamic Programmin 29 | 30 | 31 | ## 思路 32 | 33 | 题意是给出一个数组代表每天的股票金额,让你在最多买卖一次的情况下算出最大的收益额,最简单的就是模拟即可,每次记录当前值减去最小值的差值,与上一次的进行比较然后更新最大值即可。 34 | 35 | ```java 36 | class Solution { 37 | public int maxProfit(int[] prices) { 38 | int max = 0, minPrice = Integer.MAX_VALUE; 39 | for (int i = 0; i < prices.length; ++i) { 40 | if (prices[i] < minPrice) minPrice = prices[i]; 41 | int delta = prices[i] - minPrice; 42 | if (delta > max) max = delta; 43 | } 44 | return max; 45 | } 46 | } 47 | ``` 48 | 49 | 50 | ## 结语 51 | 52 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 53 | 54 | 55 | 56 | [title]: https://leetcode.com/problems/best-time-to-buy-and-sell-stock 57 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 58 | -------------------------------------------------------------------------------- /src/com/blankj/structure/Interval.java: -------------------------------------------------------------------------------- 1 | package com.blankj.structure; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/19 11 | * desc : 12 | *13 | */ 14 | public class Interval { 15 | public int start; 16 | public int end; 17 | 18 | public Interval() { 19 | start = 0; 20 | end = 0; 21 | } 22 | 23 | public Interval(int s, int e) { 24 | start = s; 25 | end = e; 26 | } 27 | 28 | /** 29 | * 创建测试数据 30 | * 31 | * @param data [[X,X],[X,X],[X,X]] 32 | * @return {@link List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/12 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 13 | int len = nums1.length + nums2.length; 14 | if (len % 2 == 0) { 15 | return (helper(nums1, 0, nums2, 0, len / 2) + helper(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0; 16 | } 17 | return helper(nums1, 0, nums2, 0, (len + 1) / 2); 18 | } 19 | 20 | private int helper(int[] nums1, int m, int[] nums2, int n, int k) { 21 | if (m >= nums1.length) return nums2[n + k - 1]; 22 | if (n >= nums2.length) return nums1[m + k - 1]; 23 | if (k == 1) return Math.min(nums1[m], nums2[n]); 24 | 25 | int p1 = m + k / 2 - 1; 26 | int p2 = n + k / 2 - 1; 27 | int mid1 = p1 < nums1.length ? nums1[p1] : Integer.MAX_VALUE; 28 | int mid2 = p2 < nums2.length ? nums2[p2] : Integer.MAX_VALUE; 29 | if (mid1 < mid2) { 30 | return helper(nums1, m + k / 2, nums2, n, k - k / 2); 31 | } 32 | return helper(nums1, m, nums2, n + k / 2, k - k / 2); 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | System.out.println(solution.findMedianSortedArrays( 38 | new int[]{1, 3}, 39 | new int[]{2} 40 | )); 41 | System.out.println(solution.findMedianSortedArrays( 42 | new int[]{1, 2}, 43 | new int[]{3, 4} 44 | )); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /note/543/README.md: -------------------------------------------------------------------------------- 1 | # [Diameter of Binary Tree][title] 2 | 3 | ## Description 4 | 5 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the **longest** path between any two nodes in a tree. This path may or may not pass through the root. 6 | 7 | **Example:** 8 | Given a binary tree 9 | 10 | ``` 11 | 1 12 | / \ 13 | 2 3 14 | / \ 15 | 4 5 16 | ``` 17 | 18 | Return **3**, which is the length of the path [4,2,1,3] or [5,2,1,3]. 19 | 20 | **Note:** The length of path between two nodes is represented by the number of edges between them. 21 | 22 | **Tags:** Tree 23 | 24 | 25 | ## 思路 26 | 27 | 题意是让你算出二叉树中最远的两个节点的距离,分别计算左右子树的最大高度,然后不断迭代出其和的最大值就是最终结果。 28 | 29 | ```java 30 | /** 31 | * Definition for a binary tree node. 32 | * public class TreeNode { 33 | * int val; 34 | * TreeNode left; 35 | * TreeNode right; 36 | * TreeNode(int x) { val = x; } 37 | * } 38 | */ 39 | class Solution { 40 | int max = 0; 41 | 42 | public int diameterOfBinaryTree(TreeNode root) { 43 | helper(root); 44 | return max; 45 | } 46 | 47 | private int helper(TreeNode root) { 48 | if (root == null) return 0; 49 | int l = helper(root.left); 50 | int r = helper(root.right); 51 | if (l + r > max) max = l + r; 52 | return Math.max(l, r) + 1; 53 | } 54 | } 55 | ``` 56 | 57 | 58 | ## 结语 59 | 60 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 61 | 62 | 63 | 64 | [title]: https://leetcode.com/problems/diameter-of-binary-tree 65 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 66 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_015/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._015; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | /** 8 | *
9 | * author: Blankj 10 | * blog : http://blankj.com 11 | * time : 2017/10/14 12 | * desc : 13 | *14 | */ 15 | public class Solution { 16 | public List
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/24 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/23 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int myAtoi(String str) { 13 | int i = 0, ans = 0, sign = 1, len = str.length(); 14 | while (i < len && str.charAt(i) == ' ') ++i; 15 | if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) { 16 | sign = str.charAt(i++) == '+' ? 1 : -1; 17 | } 18 | for (; i < len; ++i) { 19 | int tmp = str.charAt(i) - '0'; 20 | if (tmp < 0 || tmp > 9) break; 21 | if (ans > Integer.MAX_VALUE / 10 22 | || (ans == Integer.MAX_VALUE / 10 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) { 23 | return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; 24 | } else { 25 | ans = ans * 10 + tmp; 26 | } 27 | } 28 | return sign * ans; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Solution solution = new Solution(); 33 | System.out.println(solution.myAtoi(" +1")); 34 | System.out.println(solution.myAtoi(" -1")); 35 | System.out.println(solution.myAtoi("")); 36 | System.out.println(solution.myAtoi("a1")); 37 | System.out.println(solution.myAtoi("100000000000000000000")); 38 | System.out.println(solution.myAtoi("-100000000000000000000")); 39 | System.out.println(solution.myAtoi("-3924x8fc")); 40 | System.out.println(solution.myAtoi(String.valueOf(Integer.MIN_VALUE))); 41 | System.out.println(solution.myAtoi(String.valueOf(Integer.MAX_VALUE))); 42 | } 43 | } -------------------------------------------------------------------------------- /note/028/README.md: -------------------------------------------------------------------------------- 1 | # [Implement strStr()][title] 2 | 3 | ## Description 4 | 5 | Implement [strStr()](http://www.cplusplus.com/reference/cstring/strstr/). 6 | 7 | Return the index of the first occurrence of needle in haystack, or **-1** if needle is not part of haystack. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: haystack = "hello", needle = "ll" 13 | Output: 2 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: haystack = "aaaaa", needle = "bba" 20 | Output: -1 21 | ``` 22 | 23 | **Clarification:** 24 | 25 | What should we return when `needle` is an empty string? This is a great question to ask during an interview. 26 | 27 | For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's [strstr()](http://www.cplusplus.com/reference/cstring/strstr/) and Java's [indexOf()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)). 28 | 29 | Tags:** Two Pointers, String 30 | 31 | 32 | ## 思路 33 | 34 | 题意是从主串中找到子串的索引,如果找不到则返回-1,当子串长度大于主串,直接返回-1,然后我们只需要遍历比较即可。 35 | 36 | ```java 37 | class Solution { 38 | public int strStr(String haystack, String needle) { 39 | int l1 = haystack.length(), l2 = needle.length(); 40 | if (l1 < l2) return -1; 41 | for (int i = 0; ; i++) { 42 | if (i + l2 > l1) return -1; 43 | for (int j = 0; ; j++) { 44 | if (j == l2) return i; 45 | if (haystack.charAt(i + j) != needle.charAt(j)) break; 46 | } 47 | } 48 | } 49 | } 50 | ``` 51 | 52 | 53 | ## 结语 54 | 55 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 56 | 57 | 58 | 59 | [title]: https://leetcode.com/problems/implement-strstr 60 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 61 | -------------------------------------------------------------------------------- /note/100/README.md: -------------------------------------------------------------------------------- 1 | # [Same Tree][title] 2 | 3 | ## Description 4 | 5 | Given two binary trees, write a function to check if they are the same or not. 6 | 7 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: 1 1 13 | / \ / \ 14 | 2 3 2 3 15 | 16 | [1,2,3], [1,2,3] 17 | 18 | Output: true 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: 1 1 25 | / \ 26 | 2 2 27 | 28 | [1,2], [1,null,2] 29 | 30 | Output: false 31 | ``` 32 | 33 | **Example 3:** 34 | 35 | ``` 36 | Input: 1 1 37 | / \ / \ 38 | 2 1 1 2 39 | 40 | [1,2,1], [1,1,2] 41 | 42 | Output: false 43 | ``` 44 | 45 | **Tags:** Tree, Depth-first Search 46 | 47 | 48 | ## 思路 49 | 50 | 题意是比较两棵二叉树是否相同,那么我们就深搜比较各个节点即可。 51 | 52 | ```java 53 | /** 54 | * Definition for a binary tree node. 55 | * public class TreeNode { 56 | * int val; 57 | * TreeNode left; 58 | * TreeNode right; 59 | * TreeNode(int x) { val = x; } 60 | * } 61 | */ 62 | class Solution { 63 | public boolean isSameTree(TreeNode p, TreeNode q) { 64 | if (p == null && q == null) return true; 65 | if (p == null || q == null) return false; 66 | if (p.val == q.val) { 67 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 68 | } 69 | return false; 70 | } 71 | } 72 | ``` 73 | 74 | 75 | ## 结语 76 | 77 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 78 | 79 | 80 | 81 | [title]: https://leetcode.com/problems/same-tree 82 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 83 | -------------------------------------------------------------------------------- /note/019/README.md: -------------------------------------------------------------------------------- 1 | # [Remove Nth Node From End of List][title] 2 | 3 | ## Description 4 | 5 | Given a linked list, remove the *n*-th node from the end of list and return its head. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Given linked list: 1->2->3->4->5, and n = 2. 11 | 12 | After removing the second node from the end, the linked list becomes 1->2->3->5. 13 | ``` 14 | 15 | **Note:** 16 | 17 | Given *n* will always be valid. 18 | 19 | **Follow up:** 20 | 21 | Could you do this in one pass? 22 | 23 | **Tags:** Linked List, Two Pointers 24 | 25 | 26 | ## 思路 27 | 28 | 题意是让你删除链表中的倒数第 n 个数,我的解法是利用双指针,这两个指针相差 n 个元素,当后面的指针扫到链表末尾的时候,自然它前面的那个指针所指向的下一个元素就是要删除的元素,即 `pre.next = pre.next.next;`,但是如果一开始后面的指针指向的为空,此时代表的意思就是要删除第一个元素,即 `head = head.next;`。 29 | 30 | ```java 31 | /** 32 | * Definition for singly-linked list. 33 | * public class ListNode { 34 | * int val; 35 | * ListNode next; 36 | * ListNode(int x) { val = x; } 37 | * } 38 | */ 39 | class Solution { 40 | public ListNode removeNthFromEnd(ListNode head, int n) { 41 | ListNode pre = head; 42 | ListNode afterPreN = head; 43 | while (n-- != 0) { 44 | afterPreN = afterPreN.next; 45 | } 46 | if (afterPreN != null) { 47 | while (afterPreN.next != null) { 48 | pre = pre.next; 49 | afterPreN = afterPreN.next; 50 | } 51 | pre.next = pre.next.next; 52 | } else { 53 | head = head.next; 54 | } 55 | return head; 56 | } 57 | } 58 | ``` 59 | 60 | 61 | ## 结语 62 | 63 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 64 | 65 | 66 | 67 | [title]: https://leetcode.com/problems/remove-nth-node-from-end-of-list 68 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 69 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_067/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._067; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/07 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String addBinary(String a, String b) { 13 | StringBuilder sb = new StringBuilder(); 14 | int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1; 15 | while (p1 >= 0 && p2 >= 0) { 16 | carry += a.charAt(p1--) - '0'; 17 | carry += b.charAt(p2--) - '0'; 18 | sb.insert(0, (char) (carry % 2 + '0')); 19 | carry >>= 1; 20 | } 21 | while (p1 >= 0) { 22 | carry += a.charAt(p1--) - '0'; 23 | sb.insert(0, (char) (carry % 2 + '0')); 24 | carry >>= 1; 25 | } 26 | while (p2 >= 0) { 27 | carry += b.charAt(p2--) - '0'; 28 | sb.insert(0, (char) (carry % 2 + '0')); 29 | carry >>= 1; 30 | } 31 | if (carry == 1) { 32 | sb.insert(0, '1'); 33 | } 34 | return sb.toString(); 35 | } 36 | 37 | // public String addBinary(String a, String b) { 38 | // StringBuilder sb = new StringBuilder(); 39 | // int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1; 40 | // while (p1 >= 0 || p2 >= 0 || carry == 1) { 41 | // carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0; 42 | // carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0; 43 | // sb.insert(0, (char) (carry % 2 + '0')); 44 | // carry >>= 1; 45 | // } 46 | // return sb.print(); 47 | // } 48 | 49 | public static void main(String[] args) { 50 | Solution solution = new Solution(); 51 | System.out.println(solution.addBinary("11", "1")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /note/002/README.md: -------------------------------------------------------------------------------- 1 | # [Add Two Numbers][title] 2 | 3 | ## Description 4 | 5 | You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order** and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 6 | 7 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 8 | 9 | **Example** 10 | 11 | ``` 12 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 13 | Output: 7 -> 0 -> 8 14 | Explanation: 342 + 465 = 807. 15 | ``` 16 | 17 | **Tags:** Linked List, Math 18 | 19 | 20 | ## 思路 21 | 22 | 题意我也是看了好久才看懂,就是以链表表示一个数,低位在前,高位在后,所以题中的例子就是 `342 + 465 = 807`,所以我们模拟计算即可。 23 | 24 | ```java 25 | /** 26 | * Definition for singly-linked list. 27 | * public class ListNode { 28 | * int val; 29 | * ListNode next; 30 | * ListNode(int x) { val = x; } 31 | * } 32 | */ 33 | class Solution { 34 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 35 | ListNode node = new ListNode(0); 36 | ListNode n1 = l1, n2 = l2, t = node; 37 | int sum = 0; 38 | while (n1 != null || n2 != null) { 39 | sum /= 10; 40 | if (n1 != null) { 41 | sum += n1.val; 42 | n1 = n1.next; 43 | } 44 | if (n2 != null) { 45 | sum += n2.val; 46 | n2 = n2.next; 47 | } 48 | t.next = new ListNode(sum % 10); 49 | t = t.next; 50 | } 51 | if (sum / 10 != 0) t.next = new ListNode(1); 52 | return node.next; 53 | } 54 | } 55 | ``` 56 | 57 | 58 | ## 结语 59 | 60 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 61 | 62 | 63 | 64 | [title]: https://leetcode.com/problems/add-two-numbers 65 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 66 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_022/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._022; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | 8 | /** 9 | *
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2018/01/30 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public List
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/09 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public boolean isSymmetric(TreeNode root) { 18 | // return root == null || helper(root.left, root.right); 19 | // } 20 | // 21 | // private boolean helper(TreeNode left, TreeNode right) { 22 | // if (left == null || right == null) return left == right; 23 | // if (left.val != right.val) return false; 24 | // return helper(left.left, right.right) && helper(left.right, right.left); 25 | // } 26 | 27 | public boolean isSymmetric(TreeNode root) { 28 | if (root == null) return true; 29 | LinkedList
9 | * author: Blankj 10 | * blog : http://blankj.com 11 | * time : 2017/10/15 12 | * desc : 13 | *14 | */ 15 | public class Solution { 16 | // private static String[] map = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 17 | // 18 | // public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/12/11 8 | * desc : 9 | *10 | */ 11 | class Solution { 12 | 13 | // public String convert(String s, int numRows) { 14 | // if (numRows <= 1) return s; 15 | // int len = s.length(); 16 | // char[] chars = s.toCharArray(); 17 | // int cycle = 2 * (numRows - 1); 18 | // StringBuilder sb = new StringBuilder(); 19 | // for (int j = 0; j < len; j += cycle) { 20 | // sb.append(chars[j]); 21 | // } 22 | // for (int i = 1; i < numRows - 1; i++) { 23 | // int step = 2 * i; 24 | // for (int j = i; j < len; j += step) { 25 | // sb.append(chars[j]); 26 | // step = cycle - step; 27 | // } 28 | // } 29 | // for (int j = numRows - 1; j < len; j += cycle) { 30 | // sb.append(chars[j]); 31 | // } 32 | // return sb.toString(); 33 | // } 34 | 35 | public String convert(String s, int numRows) { 36 | if (numRows <= 1) return s; 37 | int len = s.length(); 38 | char[] chars = s.toCharArray(); 39 | StringBuilder[] sbs = new StringBuilder[numRows]; 40 | for (int i = 0; i < numRows; i++) { 41 | sbs[i] = new StringBuilder(); 42 | } 43 | int i = 0; 44 | while (i < len) { 45 | for (int j = 0; j < numRows && i < len; ++j) { 46 | sbs[j].append(chars[i++]); 47 | } 48 | for (int j = numRows - 2; j >= 1 && i < len; --j) { 49 | sbs[j].append(chars[i++]); 50 | } 51 | } 52 | for (i = 1; i < numRows; i++) { 53 | sbs[0].append(sbs[i]); 54 | } 55 | return sbs[0].toString(); 56 | } 57 | 58 | public static void main(String[] args) { 59 | Solution solution = new Solution(); 60 | System.out.println(solution.convert("PAYPALISHIRING", 3));// PAHNAPLSIIGYIR 61 | System.out.println(solution.convert("ABCD", 4)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /note/043/README.md: -------------------------------------------------------------------------------- 1 | # [Multiply Strings][title] 2 | 3 | ## Description 4 | 5 | 1. Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: num1 = "2", num2 = "3" 11 | Output: "6" 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: num1 = "123", num2 = "456" 18 | Output: "56088" 19 | ``` 20 | 21 | **Note:** 22 | 23 | 1. The length of both `num1` and `num2` is < 110. 24 | 2. Both `num1` and `num2` contain only digits `0-9`. 25 | 3. Both `num1` and `num2` do not contain any leading zero, except the number 0 itself. 26 | 4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly. 27 | 28 | **Tags:** Math, String 29 | 30 | 31 | ## 思路 32 | 33 | 题意是让你计算两个非负字符串的乘积,我们模拟小学数学的方式来做,一位一位模拟计算,再各位累加。 34 | 35 | ```java 36 | class Solution { 37 | public String multiply(String num1, String num2) { 38 | if (num1.equals("0") || num2.equals("0")) return "0"; 39 | int l1 = num1.length(), l2 = num2.length(), l = l1 + l2; 40 | char[] ans = new char[l]; 41 | char[] c1 = num1.toCharArray(); 42 | char[] c2 = num2.toCharArray(); 43 | for (int i = l1 - 1; i >= 0; --i) { 44 | int c = c1[i] - '0'; 45 | for (int j = l2 - 1; j >= 0; --j) { 46 | ans[i + j + 1] += c * (c2[j] - '0'); 47 | } 48 | } 49 | for (int i = l - 1; i > 0; --i) { 50 | if (ans[i] > 9) { 51 | ans[i - 1] += ans[i] / 10; 52 | ans[i] %= 10; 53 | } 54 | } 55 | StringBuilder sb = new StringBuilder(); 56 | int i = 0; 57 | for (; ; ++i) if (ans[i] != 0) break; 58 | for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0')); 59 | return sb.toString(); 60 | } 61 | } 62 | ``` 63 | 64 | 65 | ## 结语 66 | 67 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 68 | 69 | 70 | 71 | [title]: https://leetcode.com/problems/multiply-strings 72 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 73 | -------------------------------------------------------------------------------- /note/024/README.md: -------------------------------------------------------------------------------- 1 | # [Swap Nodes in Pairs][title] 2 | 3 | ## Description 4 | 5 | Given a linked list, swap every two adjacent nodes and return its head. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Given 1->2->3->4, you should return the list as 2->1->4->3. 11 | ``` 12 | 13 | **Note:** 14 | 15 | - Your algorithm should use only constant extra space. 16 | - You may **not** modify the values in the list's nodes, only nodes itself may be changed. 17 | 18 | **Tags:** Linked List 19 | 20 | 21 | ## 思路 0 22 | 23 | 题意是让你交换链表中相邻的两个节点,最终返回交换后链表的头,限定你空间复杂度为 O(1)。我们可以用递归来算出子集合的结果,递归的终点就是指针指到链表末少于两个元素时,如果不是终点,那么我们就对其两节点进行交换,这里我们需要一个临时节点来作为交换桥梁,就不多说了。 24 | 25 | ```java 26 | /** 27 | * Definition for singly-linked list. 28 | * public class ListNode { 29 | * int val; 30 | * ListNode next; 31 | * ListNode(int x) { val = x; } 32 | * } 33 | */ 34 | class Solution { 35 | public ListNode swapPairs(ListNode head) { 36 | if (head == null || head.next == null) return head; 37 | ListNode node = head.next; 38 | head.next = swapPairs(node.next); 39 | node.next = head; 40 | return node; 41 | } 42 | } 43 | ``` 44 | 45 | 46 | ## 思路 1 47 | 48 | 另一种实现方式就是用循环来实现了,两两交换节点,也需要一个临时节点来作为交换桥梁,直到当前指针指到链表末少于两个元素时停止,代码很简单,如下所示。 49 | 50 | ```java 51 | /** 52 | * Definition for singly-linked list. 53 | * public class ListNode { 54 | * int val; 55 | * ListNode next; 56 | * ListNode(int x) { val = x; } 57 | * } 58 | */ 59 | class Solution { 60 | public ListNode swapPairs(ListNode head) { 61 | ListNode preHead = new ListNode(0), cur = preHead; 62 | preHead.next = head; 63 | while (cur.next != null && cur.next.next != null) { 64 | ListNode temp = cur.next.next; 65 | cur.next.next = temp.next; 66 | temp.next = cur.next; 67 | cur.next = temp; 68 | cur = cur.next.next; 69 | } 70 | return preHead.next; 71 | } 72 | } 73 | ``` 74 | 75 | 76 | ## 结语 77 | 78 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 79 | 80 | 81 | 82 | [title]: https://leetcode.com/problems/swap-nodes-in-pairs 83 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 84 | -------------------------------------------------------------------------------- /note/056/README.md: -------------------------------------------------------------------------------- 1 | # [Merge Intervals][title] 2 | 3 | ## Description 4 | 5 | Given a collection of intervals, merge all overlapping intervals. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [[1,3],[2,6],[8,10],[15,18]] 11 | Output: [[1,6],[8,10],[15,18]] 12 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 13 | ``` 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: [[1,4],[4,5]] 19 | Output: [[1,5]] 20 | Explanation: Intervals [1,4] and [4,5] are considerred overlapping. 21 | ``` 22 | 23 | **Tags:** Array, Sort 24 | 25 | 26 | ## 思路 27 | 28 | 题意是给你一组区间,让你把区间合并成没有交集的一组区间。我们可以把区间按 `start` 进行排序,然后遍历排序后的区间,如果当前的 `start` 小于前者的 `end`,那么说明这两个存在交集,我们取两者中较大的 `end` 即可;否则的话直接插入到结果序列中即可。 29 | 30 | ```java 31 | /** 32 | * Definition for an interval. 33 | * public class Interval { 34 | * int start; 35 | * int end; 36 | * Interval() { start = 0; end = 0; } 37 | * Interval(int s, int e) { start = s; end = e; } 38 | * } 39 | */ 40 | class Solution { 41 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/11/04 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // int st, end; 13 | // 14 | // public String longestPalindrome(String s) { 15 | //// st = 0; 16 | //// end = 0; 17 | // int len = s.length(); 18 | // if (len <= 1) return s; 19 | // char[] chars = s.toCharArray(); 20 | // for (int i = 0; i < len; i++) { 21 | // helper(chars, i, i); 22 | // helper(chars, i, i + 1); 23 | // } 24 | // return s.substring(st, end + 1); 25 | // } 26 | // 27 | // private void helper(char[] chars, int l, int r) { 28 | // while (l >= 0 && r < chars.length && chars[l] == chars[r]) { 29 | // --l; 30 | // ++r; 31 | // } 32 | // if (end - st < r - l - 2) { 33 | // st = l + 1; 34 | // end = r - 1; 35 | // } 36 | // } 37 | 38 | // public String longestPalindrome(String s) { 39 | // int len = s.length(); 40 | // if (len <= 1) return s; 41 | // int st = 0, end = 0; 42 | // char[] chars = s.toCharArray(); 43 | // boolean[][] dp = new boolean[len][len]; 44 | // for (int i = 0; i < len; i++) { 45 | // dp[i][i] = true; 46 | // for (int j = 0; j < i; j++) { 47 | // if (j + 1 == i) { 48 | // dp[j][i] = chars[j] == chars[i]; 49 | // } else { 50 | // dp[j][i] = dp[j + 1][i - 1] && chars[j] == chars[i]; 51 | // } 52 | // if (dp[j][i] && i - j > end - st) { 53 | // st = j; 54 | // end = i; 55 | // } 56 | // } 57 | // } 58 | // return s.substring(st, end + 1); 59 | // } 60 | 61 | public String longestPalindrome(String s) { 62 | 63 | return s; 64 | } 65 | 66 | public static void main(String[] args) { 67 | Solution solution = new Solution(); 68 | System.out.println(solution.longestPalindrome("babad")); 69 | System.out.println(solution.longestPalindrome("cbbd")); 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/com/blankj/hard/_068/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.hard._068; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/11/01 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | 16 | public List
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/15 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public ListNode mergeKLists(ListNode[] lists) { 18 | // if (lists.length == 0) return null; 19 | // return helper(lists, 0, lists.length - 1); 20 | // } 21 | // 22 | // private ListNode helper(ListNode[] lists, int left, int right) { 23 | // if (left >= right) return lists[left]; 24 | // int mid = left + right >>> 1; 25 | // ListNode l0 = helper(lists, left, mid); 26 | // ListNode l1 = helper(lists, mid + 1, right); 27 | // return merge2Lists(l0, l1); 28 | // } 29 | // 30 | // private ListNode merge2Lists(ListNode l0, ListNode l1) { 31 | // ListNode node = new ListNode(0), tmp = node; 32 | // while (l0 != null && l1 != null) { 33 | // if (l0.val <= l1.val) { 34 | // tmp.next = new ListNode(l0.val); 35 | // l0 = l0.next; 36 | // } else { 37 | // tmp.next = new ListNode(l1.val); 38 | // l1 = l1.next; 39 | // } 40 | // tmp = tmp.next; 41 | // } 42 | // tmp.next = l0 != null ? l0 : l1; 43 | // return node.next; 44 | // } 45 | 46 | public ListNode mergeKLists(ListNode[] lists) { 47 | if (lists.length == 0) return null; 48 | PriorityQueue
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/06/05 8 | * desc : 9 | *10 | */ 11 | public class TreeNode { 12 | 13 | public int val; 14 | public TreeNode left; 15 | public TreeNode right; 16 | 17 | public TreeNode(int x) { 18 | val = x; 19 | } 20 | 21 | /** 22 | * 创建测试数据 23 | * 24 | * @param data [XX,XX,null,xx] 25 | * @return {@link TreeNode} 26 | */ 27 | public static TreeNode createTestData(String data) { 28 | if (data.equals("[]")) return null; 29 | data = data.substring(1, data.length() - 1); 30 | String[] split = data.split(","); 31 | int len = len = split.length; 32 | TreeNode[] treeNodes = new TreeNode[len]; 33 | data = data.substring(1, data.length() - 1); 34 | for (int i = 0; i < len; i++) { 35 | if (!split[i].equals("null")) { 36 | treeNodes[i] = new TreeNode(Integer.valueOf(split[i])); 37 | } 38 | } 39 | for (int i = 0; i < len; i++) { 40 | if (treeNodes[i] != null) { 41 | int leftIndex = i * 2 + 1; 42 | if (leftIndex < len) { 43 | treeNodes[i].left = treeNodes[leftIndex]; 44 | } 45 | int rightIndex = leftIndex + 1; 46 | if (rightIndex < len) { 47 | treeNodes[i].right = treeNodes[rightIndex]; 48 | } 49 | } 50 | } 51 | return treeNodes[0]; 52 | } 53 | 54 | private static final String space = " "; 55 | 56 | /** 57 | * 竖向打印二叉树 58 | * 59 | * @param root 二叉树根节点 60 | */ 61 | public static void print(TreeNode root) { 62 | print(root, 0); 63 | } 64 | 65 | private static void print(TreeNode node, int deep) { 66 | if (node == null) { 67 | printSpace(deep); 68 | System.out.println("#"); 69 | return; 70 | } 71 | print(node.right, deep + 1); 72 | printSpace(deep); 73 | printNode(node.val); 74 | print(node.left, deep + 1); 75 | } 76 | 77 | private static void printSpace(int count) { 78 | for (int i = 0; i < count; i++) { 79 | System.out.printf(space); 80 | } 81 | } 82 | 83 | private static void printNode(int val) { 84 | StringBuilder res = new StringBuilder(val + "<"); 85 | int spaceNum = space.length() - res.length(); 86 | for (int i = 0; i < spaceNum; i++) { 87 | res.append(" "); 88 | } 89 | System.out.println(res); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /note/017/README.md: -------------------------------------------------------------------------------- 1 | # [Letter Combinations of a Phone Number][title] 2 | 3 | ## Description 4 | 5 | Given a digit string, return all possible letter combinations that the number could represent. 6 | 7 | A mapping of digit to letters (just like on the telephone buttons) is given below. 8 | 9 |  10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: "23" 15 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 16 | ``` 17 | 18 | **Note:** 19 | 20 | Although the above answer is in lexicographical order, your answer could be in any order you want. 21 | 22 | **Tags:** String, Backtracking 23 | 24 | 25 | ## 思路 0 26 | 27 | 题意是给你按键,让你组合出所有不同结果,首先想到的肯定是回溯了,对每个按键的所有情况进行回溯,回溯的终点就是结果字符串长度和按键长度相同。 28 | 29 | ```java 30 | class Solution { 31 | private static String[] map = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 32 | 33 | public List
13 | * author: Blankj 14 | * blog : http://blankj.com 15 | * time : 2018/02/01 16 | * desc : 17 | *18 | */ 19 | public class Solution { 20 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/13 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // public boolean isMatch(String s, String p) { 13 | // if (p.isEmpty()) return s.isEmpty(); 14 | // if (p.length() == 1) { 15 | // return s.length() == 1 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); 16 | // } 17 | // if (p.charAt(1) != '*') { 18 | // if (s.isEmpty()) return false; 19 | // return (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') 20 | // && isMatch(s.substring(1), p.substring(1)); 21 | // } 22 | // // match 1 or more preceding element 23 | // while (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) { 24 | // if (isMatch(s, p.substring(2))) return true; 25 | // s = s.substring(1); 26 | // } 27 | // // match 0 preceding element 28 | // return isMatch(s, p.substring(2)); 29 | // } 30 | // 31 | // public boolean isMatch(String s, String p) { 32 | // if (p.isEmpty()) return s.isEmpty(); 33 | // if (p.length() > 1 && p.charAt(1) == '*') { 34 | // return isMatch(s, p.substring(2)) 35 | // || (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') 36 | // && isMatch(s.substring(1), p)); 37 | // } 38 | // return !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') 39 | // && isMatch(s.substring(1), p.substring(1)); 40 | // } 41 | 42 | public boolean isMatch(String s, String p) { 43 | if (p.length() == 0) return s.length() == 0; 44 | int sL = s.length(), pL = p.length(); 45 | boolean[][] dp = new boolean[sL + 1][pL + 1]; 46 | char[] sc = s.toCharArray(), pc = p.toCharArray(); 47 | dp[0][0] = true; 48 | for (int i = 2; i <= pL; ++i) { 49 | if (pc[i - 1] == '*' && dp[0][i - 2]) { 50 | dp[0][i] = true; 51 | } 52 | } 53 | for (int i = 1; i <= sL; ++i) { 54 | for (int j = 1; j <= pL; ++j) { 55 | if (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]) { 56 | dp[i][j] = dp[i - 1][j - 1]; 57 | } 58 | if (pc[j - 1] == '*') { 59 | if (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') { 60 | dp[i][j] = dp[i - 1][j] || dp[i][j - 2]; 61 | } else { 62 | dp[i][j] = dp[i][j - 2]; 63 | } 64 | } 65 | } 66 | } 67 | return dp[sL][pL]; 68 | } 69 | 70 | public static void main(String[] args) { 71 | Solution solution = new Solution(); 72 | System.out.println(solution.isMatch("aa", "a")); // false 73 | System.out.println(solution.isMatch("aa", "aa")); // true 74 | System.out.println(solution.isMatch("aaa", "aa")); // false 75 | System.out.println(solution.isMatch("aa", "a*")); // true 76 | System.out.println(solution.isMatch("aa", ".*")); // true 77 | System.out.println(solution.isMatch("ab", ".*")); // true 78 | System.out.println(solution.isMatch("aab", "c*a*b"));// true 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Companies.md: -------------------------------------------------------------------------------- 1 | # LeetCode companies 2 | 3 | ### Google 4 | ``` 5 | 4,10,17,20,22,23,31,42,44,50,54,56,57,66,128,133,139,140,146,155,158 6 | 159,162,163,166,173,200,208,212,214,218,224,228,230,231,239,240,246 7 | 247,249,251,253,257,259,261,266,269,270,271,272,274,276,279,280,281 8 | 282,284,286,288,289,293,294,295,297,298,302,305,308,309,310,312,313 9 | 314,315,316,317,318,320,321,323,324,326,327,329,330,331,332,336,340 10 | 341,345,346,348,351,353,354,356,357,358,359,360,361,362,363,368,369 11 | 370,373,374,375,377,378,379,380,382,388,389,391,393,394,397,399,400 12 | 401,402,406,407,408,409,411,415,417,418,421,422,425,444,447,448,451 13 | 459,460,463,465,469,471,474,475,480,481-487,490,493,494,498,501,503 14 | 505,506,514,520,521,522,524,526,527,530,531,533,534,535,541,542,543 15 | 544,545,551,552,560,562,568,569,572 16 | ``` 17 | 18 | ### Facebook 19 | ``` 20 | 1,10,13,15,17,20,23,25,26,28,33,38,43,44,49,50,56,57,67,68,69,71,75,76 21 | 78,79,80,85,88,90,91,98,102,117,121,125,127,128,133,139,146,157,158,161 22 | 168,173,200,206,208,209,210,211,215,218,221,234,235,236,238,252,253,257 23 | 261,265,269,273,274,275,277,278,282,283,285,286,297,301,311,314,325,334 24 | 341,377,380,398,404,410,461,477,494,523,525,534,535,543,554 25 | ``` 26 | 27 | ### Linkedin 28 | ``` 29 | 1,21,23,33,34,46,47,50,53,56,57,65,68,76,101-104,127,149,150,152 30 | 156,170,173,18,198,205,236,238,243,244,245,254,256,277,297,311,339 31 | 364,366,367,464,515 32 | ``` 33 | 34 | ### Microsoft 35 | ``` 36 | 1,2,4,5,8,13,15,20,21,23-26,28,33,46,47,48,53-56,71,73,75,79,88,91 37 | 94,98,101,102,103,106,112,114,116,117,121,124,125,138,141,146,151,153 38 | 160,162,165,168,171,173,174,186,189,191,200,204,206,208,212,213,215 39 | 218,232,235,236,237,238,258,268,270,273,285,297,300,333,348,365,387 40 | 419,445,452,513,567 41 | ``` 42 | 43 | ### Amazon 44 | ``` 45 | 1,2,3,5,8,15,1,20,21,,23,42,48,49,73,78,89,98,102,119,121,126,127,138 46 | 139,141,146,155,160,167,186,199,200,204,206,215,234,235,236,238,239,240 47 | 242,297,355,380,387,396,414,438,449,451,459,460,508,516,517,529,532,534 48 | 535,536,537,538,545,579 49 | ``` 50 | 51 | ### Uber 52 | ``` 53 | 1,8,10,13,17,22,23,24,33,36,37,39,49,54,76,78,91,104,121,125,133,138 54 | 139,140,146,155,161,171,186,202,206,208,230,242,249,254,262,266,290 55 | 291,297,337,373,380,432,450,516,534,535 56 | ``` 57 | 58 | ### Yelp 59 | ``` 60 | 1,3,14,49,56,126,127,151,206,207,218,242,347,380,381,564 61 | ``` 62 | 63 | ### Apple 64 | ``` 65 | 1,4,7,21,28,36,42,48,69,70,102,104,118,149,151,165,190,191,206,207,215 66 | 221,236,237,238,240,257,284,383 67 | ``` 68 | 69 | ### Bloomberg 70 | ``` 71 | 1,2,3,5,7,8,11,13,15,16,20,24,26,33,42,49,50,53,56,62,63,69,79,88,98,100,101,102 72 | 103,105,110,113,117,121,122,131,138,139,141,146,151,155,158,160,172,189,206,208 73 | 215,225,230,232,266,268,2774,283,287,297,386,387,445,556 74 | ``` 75 | 76 | ### Yahoo 77 | ``` 78 | 1,4,13,104,139,141,146,206,217,284,297,479,491 79 | ``` 80 | 81 | ### Airbnb 82 | ``` 83 | 1,2,10,20,23,68,108,136,160,190,198,202,212,217,219,220,221,227,251 84 | 269,336,385,415 85 | ``` 86 | 87 | ### Snapchat 88 | ``` 89 | 36,37,39,40,44,76,96,127,140,146,151,155,161,206,253,269,270,289,312,314, 90 | 377,402,403,439,527 91 | ``` 92 | 93 | ### Two Sigma 94 | ``` 95 | 44,289,342,349,547 96 | ``` 97 | 98 | ### Indeed 99 | ``` 100 | 453,563 101 | ``` 102 | 103 | ### Mathworks 104 | ``` 105 | 500,566 106 | ``` 107 | 108 | ### Alibaba 109 | ``` 110 | 548,555 111 | ``` 112 | 113 | ### Baidu 114 | ``` 115 | 124,395,397,410,413,446,488,576 116 | ``` 117 | 118 | ### Zappos 119 | ``` 120 | 557 121 | ``` 122 | 123 | ### eBay 124 | ``` 125 | 416,572 126 | ``` 127 | -------------------------------------------------------------------------------- /note/008/README.md: -------------------------------------------------------------------------------- 1 | # [String to Integer (atoi)][title] 2 | 3 | ## Description 4 | 5 | Implement `atoi` which converts a string to an integer. 6 | 7 | The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. 8 | 9 | The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. 10 | 11 | If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. 12 | 13 | If no valid conversion could be performed, a zero value is returned. 14 | 15 | **Note:** 16 | 17 | - Only the space character `' '` is considered as whitespace character. 18 | - Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: "42" 24 | Output: 42 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: " -42" 31 | Output: -42 32 | Explanation: The first non-whitespace character is '-', which is the minus sign. 33 | Then take as many numerical digits as possible, which gets 42. 34 | ``` 35 | 36 | **Example 3:** 37 | 38 | ``` 39 | Input: "4193 with words" 40 | Output: 4193 41 | Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. 42 | ``` 43 | 44 | **Example 4:** 45 | 46 | ``` 47 | Input: "words and 987" 48 | Output: 0 49 | Explanation: The first non-whitespace character is 'w', which is not a numerical 50 | digit or a +/- sign. Therefore no valid conversion could be performed. 51 | ``` 52 | 53 | **Example 5:** 54 | 55 | ``` 56 | Input: "-91283472332" 57 | Output: -2147483648 58 | Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. 59 | Thefore INT_MIN (−2^31) is returned. 60 | ``` 61 | 62 | **Tags:** Math, String 63 | 64 | 65 | ## 思路 66 | 67 | 题意是把一个字符串转为整型,但要注意所给的要求,先去除最前面的空格,然后判断正负数,注意正数可能包含 `+`,如果之后存在非数字或全为空则返回 `0`,而如果合法的值超过 int 表示的最大范围,则根据正负号返回 `INT_MAX` 或 `INT_MIN`。 68 | 69 | ```java 70 | class Solution { 71 | public int myAtoi(String str) { 72 | int i = 0, ans = 0, sign = 1, len = str.length(); 73 | while (i < len && str.charAt(i) == ' ') ++i; 74 | if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) { 75 | sign = str.charAt(i++) == '+' ? 1 : -1; 76 | } 77 | for (; i < len; ++i) { 78 | int tmp = str.charAt(i) - '0'; 79 | if (tmp < 0 || tmp > 9) break; 80 | if (ans > Integer.MAX_VALUE / 10 81 | || (ans == Integer.MAX_VALUE / 10 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) { 82 | return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; 83 | } else { 84 | ans = ans * 10 + tmp; 85 | } 86 | } 87 | return sign * ans; 88 | } 89 | } 90 | ``` 91 | 92 | 93 | ## 结语 94 | 95 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 96 | 97 | 98 | 99 | [title]: https://leetcode.com/problems/string-to-integer-atoi 100 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 101 | -------------------------------------------------------------------------------- /note/006/README.md: -------------------------------------------------------------------------------- 1 | # [ZigZag Conversion][title] 2 | 3 | ## Description 4 | 5 | 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) 6 | 7 | ``` 8 | P A H N 9 | A P L S I I G 10 | Y I R 11 | ``` 12 | 13 | And then read line by line: `"PAHNAPLSIIGYIR"` 14 | 15 | Write the code that will take a string and make this conversion given a number of rows: 16 | 17 | ``` 18 | string convert(string s, int numRows); 19 | ``` 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: s = "PAYPALISHIRING", numRows = 3 25 | Output: "PAHNAPLSIIGYIR" 26 | ``` 27 | 28 | **Example 2:** 29 | 30 | ``` 31 | Input: s = "PAYPALISHIRING", numRows = 4 32 | Output: "PINALSIGYAHRPI" 33 | Explanation: 34 | 35 | P I N 36 | A L S I G 37 | Y A H R 38 | P I 39 | ``` 40 | 41 | **Tags:** String 42 | 43 | 44 | ## 思路 0 45 | 46 | 题意是让你把字符串按波浪形排好,然后返回横向读取的字符串。 47 | 48 | 听不懂的话,看下面的表示应该就明白了: 49 | 50 | ``` 51 | 0 2n-2 4n-4 52 | 1 2n-3 2n-1 4n-5 4n-5 53 | 2 2n-4 2n 4n-6 . 54 | . . . . . 55 | . n+1 . 3n-1 . 56 | n-2 n 3n-4 3n-2 5n-6 57 | n-1 3n-3 5n-5 58 | ``` 59 | 60 | 那么我们可以根据上面找规律,可以看到波峰和波谷是单顶点的,它们周期是 `2 * (n - 1)`,单独处理即可;中间的部分每个周期会出现两次,规律很好找,留给读者自己想象,不懂的可以结合以下代码。 61 | 62 | ```java 63 | class Solution { 64 | public String convert(String s, int numRows) { 65 | if (numRows <= 1) return s; 66 | int len = s.length(); 67 | char[] chars = s.toCharArray(); 68 | int cycle = 2 * (numRows - 1); 69 | StringBuilder sb = new StringBuilder(); 70 | for (int j = 0; j < len; j += cycle) { 71 | sb.append(chars[j]); 72 | } 73 | for (int i = 1; i < numRows - 1; i++) { 74 | int step = 2 * i; 75 | for (int j = i; j < len; j += step) { 76 | sb.append(chars[j]); 77 | step = cycle - step; 78 | } 79 | } 80 | for (int j = numRows - 1; j < len; j += cycle) { 81 | sb.append(chars[j]); 82 | } 83 | return sb.toString(); 84 | } 85 | } 86 | ``` 87 | 88 | 89 | ## 思路 1 90 | 91 | 另外一种思路就是开辟相应行数的 `StringBuilder` 对象,然后模拟波浪生成的样子分别插入到相应的 `StringBuilder` 对象,比较直白简单,具体代码如下。 92 | 93 | ```java 94 | class Solution { 95 | public String convert(String s, int numRows) { 96 | if (numRows <= 1) return s; 97 | int len = s.length(); 98 | char[] chars = s.toCharArray(); 99 | StringBuilder[] sbs = new StringBuilder[numRows]; 100 | for (int i = 0; i < numRows; i++) { 101 | sbs[i] = new StringBuilder(); 102 | } 103 | int i = 0; 104 | while (i < len) { 105 | for (int j = 0; j < numRows && i < len; ++j) { 106 | sbs[j].append(chars[i++]); 107 | } 108 | for (int j = numRows - 2; j >= 1 && i < len; --j) { 109 | sbs[j].append(chars[i++]); 110 | } 111 | } 112 | for (i = 1; i < numRows; i++) { 113 | sbs[0].append(sbs[i]); 114 | } 115 | return sbs[0].toString(); 116 | } 117 | } 118 | ``` 119 | 120 | 121 | ## 结语 122 | 123 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 124 | 125 | 126 | 127 | [title]: https://leetcode.com/problems/zigzag-conversion 128 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 129 | -------------------------------------------------------------------------------- /note/030/README.md: -------------------------------------------------------------------------------- 1 | # [Substring with Concatenation of All Words][title] 2 | 3 | ## Description 4 | 5 | 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. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 11 | s = "barfoothefoobarman", 12 | words = ["foo","bar"] 13 | Output: [0,9] 14 | Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively. 15 | The output order does not matter, returning [9,0] is fine too. 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: 22 | s = "wordgoodgoodgoodbestword", 23 | words = ["word","good","best","word"] 24 | Output: [] 25 | ``` 26 | 27 | **Tags:** Hash Table, Two Pointers, String 28 | 29 | 30 | ## 思路 31 | 32 | 题意是给一个字符串 `s` 和等长度的单词数组 `words`,我们要找到的就是在 `s` 串中由所有单词组成的子串的索引(不要求顺序),不明白的话看下例子也就理解了,比如例子 1 的结果 [0, 9]:[`barfoo`,`foobar`] 就是符合的子串。 33 | 34 | 我们把 `words` 每个单词出现的次数都存入到一个 `map` 中,然后遍历 `s` 串,依次截取单词长度的子串做比较,如果都符合那就加入结果,如果不符合,我们要把和它相关联的不符合的都剔除掉,这样在之后的遍历就可以跳过该位置从而达到优化的目的。 35 | 36 | ```java 37 | public class Solution { 38 | public List