├── png ├── 011_1.png ├── 073_1.png ├── 073_2.png ├── 073_3.png ├── 073_4.png ├── 073_5.png ├── 313_1.png ├── 313_2.png ├── 313_3.png ├── 313_4.png ├── 313_5.png ├── 313_6.png ├── 361_1.png ├── 361_2.png ├── 361_3.png └── 373_1.png ├── Medium ├── 319 Bulb Switcher.txt ├── 136 Single Number.txt ├── 268 Missing Number.txt ├── 201 Bitwise AND of Numbers Range.txt ├── 392 Is Subsequence.txt ├── 280 Wiggle Sort.txt ├── 096 Unique Binary Search Trees.txt ├── 122 Best Time to Buy and Sell Stock II.txt ├── 089 Gray Code.txt ├── 162 Find Peak Element.txt ├── 357 Count Numbers with Unique Digits.txt ├── 367 Valid Perfect Square.txt ├── 343 Integer Break.txt ├── 386 Lexicographical Numbers.txt ├── 137 Single Number II.txt ├── 377 Combination Sum IV.txt ├── 334 Increasing Triplet Subsequence.txt ├── 053 Maximum Subarray.txt ├── 012 Integer to Roman.txt ├── 365 Water and Jug Problem.txt ├── 372 Super Pow.txt ├── 338 Counting Bits.txt ├── 153 Find Minimum in Rotated Sorted Array.txt ├── 370 Range Addition.txt ├── 398 Random Pick Index.txt ├── 279 Perfect Squares.txt ├── 062 Unique Paths.txt ├── 274 H-Index.txt ├── 260 Single Number III.txt ├── 022 Generate Parentheses.txt ├── 277 Find the Celebrity.txt ├── 240 Search a 2D Matrix II.txt ├── 048 Rotate Image.txt ├── 238 Product of Array Except Self.txt ├── 080 Remove Duplicates from Sorted Array II.txt ├── 167 Two Sum II - Input array is sorted.txt ├── 163 Missing Ranges.txt ├── 120 Triangle.txt ├── 256 Paint House.txt ├── 259 3Sum Smaller.txt ├── 078 Subsets.txt ├── 064 Minimum Path Sum.txt ├── 328 Odd Even Linked List.txt ├── 129 Sum Root to Leaf Numbers.txt ├── 144 Binary Tree Preorder Traversal.txt ├── 323 Number of Connected Components in an Undirected Graph.txt ├── 275 H-Index II.txt ├── 063 Unique Paths II.txt ├── 035 Search Insert Position.txt ├── 075 Sort Colors.txt ├── 375 Guess Number Higher or Lower II.txt ├── 059 Spiral Matrix II.txt ├── 376 Wiggle Subsequence.txt ├── 213 House Robber II.txt ├── 216 Combination Sum III.txt ├── 046 Permutations.txt ├── 108 Convert Sorted Array to Binary Search Tree.txt ├── 094 Binary Tree Inorder Traversal.txt ├── 230 Kth Smallest Element in a BST.txt ├── 298 Binary Tree Longest Consecutive Sequence.txt ├── 245 Shortest Word Distance III.txt ├── 264 Ugly Number II.txt ├── 077 Combinations.txt ├── 254 Factor Combinations.txt ├── 285 Inorder Successor in BST.txt ├── 147 Insertion Sort List.txt ├── 300 Longest Increasing Subsequence.txt ├── 318 Maximum Product of Word Lengths.txt ├── 090 Subsets II.txt ├── 116 Populating Next Right Pointers in Each Node.txt ├── 378 Kth Smallest Element in a Sorted Matrix.txt ├── 251 Flatten 2D Vector.txt ├── 331 Verify Preorder Serialization of a Binary Tree.txt ├── 081 Search in Rotated Sorted Array II.txt ├── 366 Find Leaves of Binary Tree.txt ├── 142 Linked List Cycle II.txt ├── 369 Plus One Linked List.txt ├── 247 Strobogrammatic Number II.txt ├── 382 Linked List Random Node.txt ├── 011 Container With Most Water.txt ├── 039 Combination Sum.txt ├── 199 Binary Tree Right Side View.txt ├── 114 Flatten Binary Tree to Linked List.txt ├── 368 Largest Divisible Subset.txt ├── 200 Number of Islands.txt ├── 395 Longest Substring with At Least K Repeating Characters.txt ├── 281 Zigzag Iterator.txt ├── 253 Meeting Rooms II.txt ├── 173 Binary Search Tree Iterator.txt ├── 113 Path Sum II.txt ├── 261 Graph Valid Tree.txt ├── 284 Peeking Iterator.txt ├── 016 3Sum Closest.txt ├── 215 Kth Largest Element in an Array.txt ├── 109 Convert Sorted List to Binary Search Tree.txt ├── 394 Decode String.txt ├── 362 Design Hit Counter.txt ├── 384 Shuffle an Array.txt ├── 388 Longest Absolute File Path.txt ├── 250 Count Univalue Subtrees.txt ├── 393 UTF-8 Validation.txt ├── 086 Partition List.txt ├── 034 Search for a Range.txt ├── 074 Search a 2D Matrix.txt ├── 309 Best Time to Buy and Sell Stock with Cooldown.txt ├── 333 Largest BST Subtree.txt ├── 289 Game of Life.txt ├── 294 Flip Game II.txt ├── 105 Construct Binary Tree from Preorder and Inorder Traversal.txt ├── 348 Design Tic-Tac-Toe.txt ├── 106 Construct Binary Tree from Inorder and Postorder Traversal.txt ├── 373 Find K Pairs with Smallest Sums.txt ├── 092 Reverse Linked List II.txt ├── 241 Different Ways to Add Parentheses.txt ├── 360 Sort Transformed Array.txt ├── 314 Binary Tree Vertical Order Traversal.txt ├── 103 Binary Tree Zigzag Level Order Traversal.txt ├── 379 Design Phone Directory.txt ├── 313 Super Ugly Number.txt ├── 347 Top K Frequent Elements.txt ├── 361 Bomb Enemy.txt ├── 286 Walls and Gates.txt ├── 421 Maximum XOR of Two Numbers in an Array.txt ├── 156 Binary Tree Upside Down.txt ├── 073 Set Matrix Zeroes.txt ├── 166 Fraction to Recurring Decimal.txt ├── 311 Sparse Matrix Multiplication.txt ├── 341 Flatten Nested List Iterator.txt ├── 364 Nested List Weight Sum II.txt ├── 353 Design Snake Game.txt ├── 337 House Robber III.txt ├── 320 Generalized Abbreviation.txt ├── 095 Unique Binary Search Trees II.txt └── 244 Shortest Word Distance II.txt ├── Easy ├── 198 House Robber.txt ├── 121 Best Time to Buy and Sell Stock.txt ├── 374 Guess Number Higher or Lower.txt └── 013 Roman to Integer.txt ├── getList.py ├── Hard ├── 033 Search in Rotated Sorted Array.txt ├── 123 Best Time to Buy and Sell Stock III.txt ├── 265 Paint House II.txt ├── 312 Burst Balloons.txt ├── 296 Best Meeting Point.txt ├── 145 Binary Tree Postorder Traversal.txt ├── 340 Longest Substring with At Most K Distinct Characters.txt ├── 159 Longest Substring with At Most Two Distinct Characters.txt ├── 188 Best Time to Buy and Sell Stock IV.txt ├── 410 Split Array Largest Sum.txt ├── 287 Find the Duplicate Number.txt ├── 291 Word Pattern II.txt ├── 273 Integer to English Words.txt ├── 380 Insert Delete GetRandom O(1).txt ├── 329 Longest Increasing Path in a Matrix.txt ├── 146 LRU Cache.txt ├── 305 Number of Islands II.txt ├── 297 Serialize and Deserialize Binary Tree.txt ├── 381 Insert Delete GetRandom O(1) - Duplicates allowed.txt ├── 269 Alien Dictionary.txt ├── 052 N-Queens.txt └── 051 N-Queens.txt ├── list.txt └── README.md /png/011_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/011_1.png -------------------------------------------------------------------------------- /png/073_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/073_1.png -------------------------------------------------------------------------------- /png/073_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/073_2.png -------------------------------------------------------------------------------- /png/073_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/073_3.png -------------------------------------------------------------------------------- /png/073_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/073_4.png -------------------------------------------------------------------------------- /png/073_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/073_5.png -------------------------------------------------------------------------------- /png/313_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/313_1.png -------------------------------------------------------------------------------- /png/313_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/313_2.png -------------------------------------------------------------------------------- /png/313_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/313_3.png -------------------------------------------------------------------------------- /png/313_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/313_4.png -------------------------------------------------------------------------------- /png/313_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/313_5.png -------------------------------------------------------------------------------- /png/313_6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/313_6.png -------------------------------------------------------------------------------- /png/361_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/361_1.png -------------------------------------------------------------------------------- /png/361_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/361_2.png -------------------------------------------------------------------------------- /png/361_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/361_3.png -------------------------------------------------------------------------------- /png/373_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/all4win/LeetCode/HEAD/png/373_1.png -------------------------------------------------------------------------------- /Medium/319 Bulb Switcher.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int bulbSwitch(int n) { 3 | return (int) Math.floor(Math.sqrt(n)); 4 | } 5 | } -------------------------------------------------------------------------------- /Medium/136 Single Number.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int singleNumber(int[] nums) { 3 | int temp = 0; 4 | for (int num : nums) { 5 | temp = temp ^ num; 6 | } 7 | return temp; 8 | } 9 | } -------------------------------------------------------------------------------- /Medium/268 Missing Number.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int missingNumber(int[] nums) { 3 | int result = nums.length; 4 | for (int i = 0; i < nums.length; i++) { 5 | result = result ^ i ^nums[i]; 6 | } 7 | return result; 8 | } 9 | } -------------------------------------------------------------------------------- /Medium/201 Bitwise AND of Numbers Range.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int rangeBitwiseAnd(int m, int n) { 3 | int bit = 0; 4 | while (m != n) { 5 | m = m >> 1; 6 | n = n >> 1; 7 | bit += 1; 8 | } 9 | return m << bit; 10 | } 11 | } -------------------------------------------------------------------------------- /Medium/392 Is Subsequence.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isSubsequence(String s, String t) { 3 | int j = 0; 4 | for (int i = 0; i < t.length(); i++) { 5 | if (j == s.length()) { 6 | return true; 7 | } 8 | if (t.charAt(i) == s.charAt(j)) { 9 | j += 1; 10 | } 11 | } 12 | return j == s.length(); 13 | } 14 | } -------------------------------------------------------------------------------- /Medium/280 Wiggle Sort.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void wiggleSort(int[] nums) { 3 | boolean toggle = true; 4 | for(int i = 1; i < nums.length; i++){ 5 | if((toggle && nums[i] < nums[i-1]) || (!toggle && nums[i] > nums[i-1])){ 6 | int tmp = nums[i-1]; 7 | nums[i-1] = nums[i]; 8 | nums[i] = tmp; 9 | } 10 | toggle = !toggle; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Medium/096 Unique Binary Search Trees.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numTrees(int n) { 3 | int[] bst = new int[n + 1]; 4 | bst[0] = 1; 5 | bst[1] = 1; 6 | for (int i = 2; i <= n; i++) { 7 | int sum = 0; 8 | for (int j = 0; j < i; j++) { 9 | sum += bst[j] * bst[i - 1 - j]; 10 | } 11 | bst[i] = sum; 12 | } 13 | return bst[n]; 14 | } 15 | } -------------------------------------------------------------------------------- /Medium/122 Best Time to Buy and Sell Stock II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | if (prices == null || prices.length == 0) { 4 | return 0; 5 | } 6 | 7 | int profit = 0; 8 | for (int i = 1; i < prices.length; i++) { 9 | int diff = prices[i] - prices[i - 1]; 10 | profit += diff > 0 ? diff : 0; 11 | } 12 | return profit; 13 | } 14 | } -------------------------------------------------------------------------------- /Medium/089 Gray Code.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List grayCode(int n) { 3 | List codes = new ArrayList<>(); 4 | codes.add(0); 5 | int count = 1; 6 | while (n > 0) { 7 | for (int i = count - 1; i >= 0; i--) { 8 | codes.add(codes.get(i) + count); 9 | } 10 | count = count << 1; 11 | n -= 1; 12 | } 13 | return codes; 14 | } 15 | } -------------------------------------------------------------------------------- /Medium/162 Find Peak Element.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findPeakElement(int[] nums) { 3 | int start = 0; 4 | int end = nums.length - 1; 5 | while (start < end) { 6 | int mid = (end - start) / 2 + start; 7 | if (nums[mid] > nums[mid + 1]) { 8 | end = mid; 9 | } else { 10 | start = mid + 1; 11 | } 12 | } 13 | return start; 14 | } 15 | } -------------------------------------------------------------------------------- /Medium/357 Count Numbers with Unique Digits.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int countNumbersWithUniqueDigits(int n) { 3 | int[] count = new int[11]; 4 | count[0] = 1; 5 | count[1] = 10; 6 | int max = (n > 10) ? 10 : n; 7 | int temp = 9; 8 | for (int i = 2; i <= max; i++) { 9 | temp = temp * (11 - i); 10 | count[i] = count[i - 1] + temp; 11 | } 12 | return count[max]; 13 | } 14 | } -------------------------------------------------------------------------------- /Medium/367 Valid Perfect Square.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPerfectSquare(int num) { 3 | int end = Math.min(46340, num); 4 | int start = 1; 5 | while (start < end) { 6 | int mid = (start + end) / 2; 7 | if (num > mid * mid) { 8 | start = mid + 1; 9 | } else { 10 | end = mid; 11 | } 12 | } 13 | return num == start * start; 14 | } 15 | } -------------------------------------------------------------------------------- /Easy/198 House Robber.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int rob(int[] nums) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | int first = 0; 7 | int notFirst = 0; 8 | for (int i = 0; i < nums.length; i++) { 9 | int temp = notFirst + nums[i]; 10 | notFirst = Math.max(first, notFirst); 11 | first = temp; 12 | } 13 | return Math.max(first, notFirst); 14 | } 15 | } -------------------------------------------------------------------------------- /Medium/343 Integer Break.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int integerBreak(int n) { 3 | if (n == 2) { 4 | return 1; 5 | } 6 | if (n == 3) { 7 | return 2; 8 | } 9 | int times = n / 3; 10 | int remains = n % 3; 11 | int p = (int) Math.pow(3, times); 12 | if (remains == 0) { 13 | return p; 14 | } 15 | if (remains == 1) { 16 | return p / 3 * 4; 17 | } 18 | return p * 2; 19 | } 20 | } -------------------------------------------------------------------------------- /Easy/121 Best Time to Buy and Sell Stock.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | if (prices == null || prices.length == 0) { 4 | return 0; 5 | } 6 | int profit = 0; 7 | int min = prices[0]; 8 | for (int price : prices) { 9 | if (price < min) { 10 | min = price; 11 | } else { 12 | profit = Math.max(profit, price - min); 13 | } 14 | } 15 | return profit; 16 | } 17 | } -------------------------------------------------------------------------------- /Medium/386 Lexicographical Numbers.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List lexicalOrder(int n) { 3 | List result = new ArrayList(); 4 | append(1, n, result); 5 | return result; 6 | } 7 | 8 | private void append(int m, int n, List result) { 9 | result.add(m); 10 | if (m * 10 <= n) { 11 | append(m * 10, n, result); 12 | } 13 | if (m < n && m % 10 < 9) { 14 | append(m + 1, n, result); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Medium/137 Single Number II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int singleNumber(int[] nums) { 3 | int[] bits = new int[32]; 4 | int max = 0; 5 | for (int num : nums) { 6 | for (int i = 0; i < 32; i++) { 7 | bits[i] += (num & 1); 8 | num = num >> 1; 9 | } 10 | } 11 | int result = 0; 12 | for (int i = 31; i >= 0; i--) { 13 | result = (result << 1) + (bits[i] % 3); 14 | } 15 | 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /Medium/377 Combination Sum IV.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int combinationSum4(int[] nums, int target) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | Arrays.sort(nums); 7 | int[] res = new int[target + 1]; 8 | res[0] = 1; 9 | for (int i = 1; i <= target; i++) { 10 | for (int j = 0; j < nums.length && nums[j] <= i; j++) { 11 | res[i] += res[i - nums[j]]; 12 | } 13 | } 14 | return res[target]; 15 | } 16 | } -------------------------------------------------------------------------------- /Medium/334 Increasing Triplet Subsequence.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean increasingTriplet(int[] nums) { 3 | int[] temp = new int[2]; 4 | temp[0] = Integer.MAX_VALUE; 5 | temp[1] = Integer.MAX_VALUE; 6 | for (int num : nums) { 7 | if (temp[0] >= num) { 8 | temp[0] = num; 9 | } else if (temp[1] >= num) { 10 | temp[1] = num; 11 | } else { 12 | return true; 13 | } 14 | } 15 | return false; 16 | } 17 | } -------------------------------------------------------------------------------- /Medium/053 Maximum Subarray.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int max = Integer.MIN_VALUE; 4 | if (nums == null || nums.length == 0) { 5 | return max; 6 | } 7 | int prev = nums[0]; 8 | max = prev; 9 | for (int i = 1; i < nums.length; i++) { 10 | int cur = Math.max(prev + nums[i], nums[i]); 11 | if (cur > max) { 12 | max = cur; 13 | } 14 | prev = cur; 15 | } 16 | return max; 17 | } 18 | } -------------------------------------------------------------------------------- /Medium/012 Integer to Roman.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String intToRoman(int num) { 3 | StringBuilder sb = new StringBuilder(); 4 | String [] symbol = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 5 | int [] value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 6 | for(int i = 0; num > 0; i++) { 7 | while (num >= value[i]) { 8 | num -= value[i]; 9 | sb.append(symbol[i]); 10 | } 11 | } 12 | return sb.toString(); 13 | } 14 | } -------------------------------------------------------------------------------- /Medium/365 Water and Jug Problem.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean canMeasureWater(int x, int y, int z) { 3 | if (z > x + y) { 4 | return false; 5 | } 6 | if (z == 0) { 7 | return true; 8 | } 9 | int gcd = 1; 10 | int min = (x < y) ? x : y; 11 | int max = (x < y) ? y : x; 12 | while (min > 0) { 13 | int temp = min; 14 | min = max % min; 15 | max = temp; 16 | } 17 | gcd = max; 18 | return z % gcd == 0; 19 | } 20 | } -------------------------------------------------------------------------------- /Medium/372 Super Pow.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int superPow(int a, int[] b) { 3 | int magicNum = 1337; 4 | a = a % magicNum; 5 | int prod = 1; 6 | for (int i = b.length - 1; i >= 0; i--) { 7 | int temp = 1; 8 | for (int j = 0; j <= 9; j++) { 9 | if (b[i] == j) { 10 | prod = (prod * temp) % magicNum; 11 | } 12 | temp = (temp * a) % magicNum; 13 | } 14 | a = temp; 15 | } 16 | return prod; 17 | } 18 | } -------------------------------------------------------------------------------- /Medium/338 Counting Bits.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] countBits(int num) { 3 | if (num == 0) { 4 | return new int[1]; 5 | } 6 | int[] result = new int[num + 1]; 7 | result[0] = 0; 8 | int range = 1; 9 | for (int i = 1; i <= num; i++) { 10 | if (i < (range << 1)) { 11 | result[i] = result[i - range] + 1; 12 | } else { 13 | result[i] = 1; 14 | range = range << 1; 15 | } 16 | } 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /Medium/153 Find Minimum in Rotated Sorted Array.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findMin(int[] nums) { 3 | int start = 0; 4 | int end = nums.length - 1; 5 | while (start < end) { 6 | int mid = (end - start) / 2 + start; 7 | int a = nums[start]; 8 | int b = nums[end]; 9 | int c = nums[mid]; 10 | if (a < b || c < b) { 11 | end = mid; 12 | } else { 13 | start = mid + 1; 14 | } 15 | } 16 | return nums[start]; 17 | } 18 | } -------------------------------------------------------------------------------- /Medium/370 Range Addition.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] getModifiedArray(int length, int[][] updates) { 3 | int[] result = new int[length]; 4 | for (int[] operation : updates) { 5 | result[operation[0]] += operation[2]; 6 | if (operation[1] < length - 1) { 7 | result[operation[1] + 1] -= operation[2]; 8 | } 9 | } 10 | int temp = 0; 11 | for (int i = 0; i < length; i++) { 12 | temp += result[i]; 13 | result[i] = temp; 14 | } 15 | return result; 16 | } 17 | } -------------------------------------------------------------------------------- /Medium/398 Random Pick Index.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | int[] nums; 3 | Random rand; 4 | 5 | public Solution(int[] nums) { 6 | this.nums = nums; 7 | rand = new Random(); 8 | } 9 | 10 | public int pick(int target) { 11 | int count = 0; 12 | int idx = -1; 13 | for (int i = 0; i < nums.length; i++) { 14 | if (nums[i] == target) { 15 | count += 1; 16 | if (rand.nextInt(count) == 0) { 17 | idx = i; 18 | } 19 | } 20 | } 21 | return idx; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/279 Perfect Squares.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numSquares(int n) { 3 | int[] dp = new int[n + 1]; 4 | dp[0] = 0; 5 | int root = 1; 6 | for (int i = 1; i <= n; i++) { 7 | if (root * root == i) { 8 | dp[i] = 1; 9 | root += 1; 10 | } else { 11 | int temp = i; 12 | for (int j = 1; j < root; j++) { 13 | temp = Math.min(temp, dp[i - j * j]); 14 | } 15 | dp[i] = temp + 1; 16 | } 17 | } 18 | return dp[n]; 19 | } 20 | } -------------------------------------------------------------------------------- /Medium/062 Unique Paths.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePaths(int m, int n) { 3 | if (m < 1 || n < 1) { 4 | return 0; 5 | } 6 | int[][] paths = new int[m][n]; 7 | for (int i = 0; i < m; i++) { 8 | paths[i][0] = 1; 9 | } 10 | for (int i = 0; i < n; i++) { 11 | paths[0][i] = 1; 12 | } 13 | for (int i = 1; i < m; i++) { 14 | for (int j = 1; j < n; j++) { 15 | paths[i][j] = paths[i][j - 1] + paths[i - 1][j]; 16 | } 17 | } 18 | return paths[m - 1][n - 1]; 19 | } 20 | } -------------------------------------------------------------------------------- /Medium/274 H-Index.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int hIndex(int[] citations) { 3 | if (citations == null || citations.length == 0) { 4 | return 0; 5 | } 6 | int n = citations.length; 7 | int[] count = new int[n + 2]; 8 | for (int num : citations) { 9 | num = Math.min(num, n + 1); 10 | count[num] += 1; 11 | } 12 | 13 | for (int i = n; i >= 0; i--) { 14 | count[i] += count[i + 1]; 15 | if (count[i] >= i) { 16 | return i; 17 | } 18 | } 19 | return 0; 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/260 Single Number III.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] singleNumber(int[] nums) { 3 | int flag = 0; 4 | for (int num : nums) { 5 | flag ^= num; 6 | } 7 | int mask = 1; 8 | while (flag % 2 == 0) { 9 | flag = flag >> 1; 10 | mask = mask << 1; 11 | } 12 | int[] result = new int[2]; 13 | for (int num : nums) { 14 | if ((num & mask) != 0) { 15 | result[0] ^= num; 16 | } else { 17 | result[1] ^= num; 18 | } 19 | } 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /Medium/022 Generate Parentheses.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List generateParenthesis(int n) { 3 | List list = new ArrayList<>(); 4 | dfs(list, n, n, ""); 5 | return list; 6 | } 7 | 8 | private void dfs(List list, int left, int right, String s) { 9 | if (left == 0 && right == 0) { 10 | list.add(s); 11 | return; 12 | } 13 | if (left < right) { 14 | dfs(list, left, right - 1, s + ")"); 15 | } 16 | if (left > 0) { 17 | dfs(list, left - 1, right, s + "("); 18 | } 19 | return; 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/277 Find the Celebrity.txt: -------------------------------------------------------------------------------- 1 | /* The knows API is defined in the parent class Relation. 2 | boolean knows(int a, int b); */ 3 | 4 | public class Solution extends Relation { 5 | public int findCelebrity(int n) { 6 | int celebrity = 0; 7 | for (int i = 0; i < n; i++) { 8 | celebrity = (knows(celebrity, i)) ? i : celebrity; 9 | } 10 | for (int i = 0; i < n; i++) { 11 | if (i != celebrity) { 12 | if (knows(celebrity, i) || !knows(i, celebrity)) { 13 | return -1; 14 | } 15 | } 16 | } 17 | return celebrity; 18 | } 19 | } -------------------------------------------------------------------------------- /Medium/240 Search a 2D Matrix II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 4 | return false; 5 | } 6 | int i = 0; 7 | int j = matrix[0].length - 1; 8 | while (i < matrix.length && j >= 0) { 9 | int cur = matrix[i][j]; 10 | if (cur == target) { 11 | return true; 12 | } 13 | if (cur < target) { 14 | i += 1; 15 | } else { 16 | j -= 1; 17 | } 18 | } 19 | return false; 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/048 Rotate Image.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void rotate(int[][] matrix) { 3 | if (matrix == null || matrix.length < 2) { 4 | return; 5 | } 6 | int n = matrix.length; 7 | for (int i = 0; i < n / 2; i++) { 8 | for (int j = 0; j < n - 1 - 2 * i; j++) { 9 | int temp = matrix[n - 1 - i - j][i]; 10 | matrix[n - 1 - i - j][i] = matrix[n - 1 - i][n - 1 - i - j]; 11 | matrix[n - 1 - i][n - 1 - i - j] = matrix[i + j][n - 1 - i]; 12 | matrix[i + j][n - 1 - i] = matrix[i][i + j]; 13 | matrix[i][i + j] = temp; 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Medium/238 Product of Array Except Self.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | if (nums == null || nums.length == 0) { 4 | return null; 5 | } 6 | 7 | int[] output = new int[nums.length]; 8 | output[0] = 1; 9 | 10 | int temp = 1; 11 | for (int i = 0; i < nums.length - 1; i++) { 12 | temp *= nums[i]; 13 | output[i + 1] = temp; 14 | } 15 | 16 | temp = 1; 17 | for (int i = nums.length - 1; i > 0; i--) { 18 | temp *= nums[i]; 19 | output[i - 1] *= temp; 20 | } 21 | return output; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/080 Remove Duplicates from Sorted Array II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | int p1 = 2; 7 | int p2 = 2; 8 | while (p2 < nums.length) { 9 | if (!(nums[p2] == nums[p1 - 1] && nums[p2] == nums[p1 - 2])) { 10 | swap(nums, p1, p2); 11 | p1 += 1; 12 | } 13 | p2 += 1; 14 | } 15 | return p1; 16 | } 17 | 18 | private void swap(int[] nums, int i, int j) { 19 | int temp = nums[i]; 20 | nums[i] = nums[j]; 21 | nums[j] = temp; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/167 Two Sum II - Input array is sorted.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] twoSum(int[] numbers, int target) { 3 | int left = 1; 4 | int right = numbers.length; 5 | int[] solution = new int[2]; 6 | boolean found = false; 7 | while (!found) { 8 | int sum = numbers[left - 1] + numbers[right - 1]; 9 | if (sum < target) { 10 | left++; 11 | } else if (sum > target) { 12 | right--; 13 | } else { 14 | solution[0] = left; 15 | solution[1] = right; 16 | found = true; 17 | } 18 | } 19 | return solution; 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/163 Missing Ranges.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List findMissingRanges(int[] nums, int lower, int upper) { 3 | List ranges = new ArrayList<>(); 4 | int start = lower; 5 | for (int num : nums) { 6 | if (num > start) { 7 | add(ranges, start, num - 1); 8 | } 9 | start = num + 1; 10 | } 11 | if (start <= upper) { 12 | add(ranges, start, upper); 13 | } 14 | return ranges; 15 | } 16 | 17 | private void add(List ranges, int start, int end) { 18 | String s = (start == end) ? (start + "") : (start + "->" + end); 19 | ranges.add(s); 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/120 Triangle.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minimumTotal(List> triangle) { 3 | if (triangle == null || triangle.size() == 0) { 4 | return 0; 5 | } 6 | int[] dp = new int[triangle.size() + 2]; 7 | for (List list : triangle) { 8 | for (int i = list.size(); i >= 1; i--) { 9 | dp[i] = Math.min(dp[i], dp[i - 1]) + list.get(i - 1); 10 | } 11 | dp[0] = dp[1]; 12 | dp[list.size() + 1] = dp[list.size()]; 13 | } 14 | int sum = Integer.MAX_VALUE; 15 | for (int num : dp) { 16 | sum = Math.min(sum, num); 17 | } 18 | return sum; 19 | } 20 | } -------------------------------------------------------------------------------- /Medium/256 Paint House.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minCost(int[][] costs) { 3 | int[] prevSum = {0, 0, 0}; 4 | int[] curSum = {0, 0, 0}; 5 | if (costs == null || costs.length == 0) { 6 | return 0; 7 | } 8 | for (int[] cost : costs) { 9 | curSum[0] = Math.min(prevSum[1], prevSum[2]) + cost[0]; 10 | curSum[1] = Math.min(prevSum[0], prevSum[2]) + cost[1]; 11 | curSum[2] = Math.min(prevSum[0], prevSum[1]) + cost[2]; 12 | prevSum[0] = curSum[0]; 13 | prevSum[1] = curSum[1]; 14 | prevSum[2] = curSum[2]; 15 | } 16 | return Math.min(Math.min(curSum[0], curSum[1]), curSum[2]); 17 | } 18 | } -------------------------------------------------------------------------------- /Medium/259 3Sum Smaller.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int threeSumSmaller(int[] nums, int target) { 3 | Arrays.sort(nums); 4 | int count = 0; 5 | for (int i = 0; i < nums.length; i++) { 6 | int num1 = nums[i]; 7 | if (num1 * 3 >= target) { 8 | break; 9 | } 10 | int j = i + 1; 11 | int k = nums.length - 1; 12 | while (j < k) { 13 | if (nums[j] + nums[k] >= target - num1) { 14 | k -= 1; 15 | } else { 16 | count += k - j; 17 | j += 1; 18 | } 19 | } 20 | } 21 | return count; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/078 Subsets.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> subsets(int[] nums) { 3 | List> result = new ArrayList<>(); 4 | result.add(new ArrayList()); 5 | if (nums == null || nums.length == 0) { 6 | return result; 7 | } 8 | for (int num : nums) { 9 | int size = result.size(); 10 | for (int i = 0; i < size; i++) { 11 | List list = result.get(i); 12 | List newList = new ArrayList<>(); 13 | newList.addAll(list); 14 | newList.add(num); 15 | result.add(newList); 16 | } 17 | } 18 | return result; 19 | } 20 | } -------------------------------------------------------------------------------- /Medium/064 Minimum Path Sum.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minPathSum(int[][] grid) { 3 | int m = grid.length; 4 | int n = grid[0].length; 5 | int[][] sum = new int[m][n]; 6 | int temp = 0; 7 | for (int i = 0; i < m; i++) { 8 | temp += grid[i][0]; 9 | sum[i][0] = temp; 10 | } 11 | temp = 0; 12 | for (int i = 0; i < n; i++) { 13 | temp += grid[0][i]; 14 | sum[0][i] = temp; 15 | } 16 | for (int i = 1; i < m; i++) { 17 | for (int j = 1; j < n; j++) { 18 | sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j]; 19 | } 20 | } 21 | return sum[m - 1][n - 1]; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/328 Odd Even Linked List.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode oddEvenList(ListNode head) { 11 | if (head == null) { 12 | return head; 13 | } 14 | ListNode odd = head; 15 | ListNode even = head.next; 16 | ListNode evenHead = even; 17 | while (even != null && even.next!= null) { 18 | odd.next = even.next; 19 | even.next = even.next.next; 20 | odd = odd.next; 21 | even = even.next; 22 | } 23 | odd.next = evenHead; 24 | return head; 25 | } 26 | } -------------------------------------------------------------------------------- /Medium/129 Sum Root to Leaf Numbers.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int sumNumbers(TreeNode root) { 12 | return search(root, 0, 0); 13 | } 14 | 15 | private int search(TreeNode node, int path, int sum) { 16 | if (node == null) { 17 | return sum; 18 | } 19 | path = path * 10 + node.val; 20 | if (node.left == null && node.right == null) { 21 | sum += path; 22 | return sum; 23 | } 24 | return search(node.left, path, sum) + search(node.right, path, sum); 25 | } 26 | } -------------------------------------------------------------------------------- /Medium/144 Binary Tree Preorder Traversal.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List preorderTraversal(TreeNode root) { 12 | List list = new ArrayList<>(); 13 | Stack stack = new Stack<>(); 14 | stack.push(root); 15 | while (!stack.isEmpty()) { 16 | TreeNode cur = stack.pop(); 17 | if (cur != null) { 18 | stack.push(cur.right); 19 | stack.push(cur.left); 20 | list.add(cur.val); 21 | } 22 | } 23 | return list; 24 | } 25 | } -------------------------------------------------------------------------------- /Medium/323 Number of Connected Components in an Undirected Graph.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int countComponents(int n, int[][] edges) { 3 | int count = n; 4 | int[] idx = new int[n]; 5 | for (int i = 0; i < n ; i++) { 6 | idx[i] = i; 7 | } 8 | for (int[] edge : edges) { 9 | int a = edge[0]; 10 | int b = edge[1]; 11 | int fa = idx[a]; 12 | int fb = idx[b]; 13 | if (fa != fb) { 14 | for (int i = 0; i < n; i++) { 15 | if (idx[i] == fb) { 16 | idx[i] = fa; 17 | } 18 | } 19 | count -= 1; 20 | } 21 | } 22 | return count; 23 | } 24 | } -------------------------------------------------------------------------------- /Easy/374 Guess Number Higher or Lower.txt: -------------------------------------------------------------------------------- 1 | /* The guess API is defined in the parent class GuessGame. 2 | @param num, your guess 3 | @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 | int guess(int num); */ 5 | 6 | public class Solution extends GuessGame { 7 | public int guessNumber(int n) { 8 | int start = 1; 9 | int end = n; 10 | while (start < end) { 11 | int mid = (end - start) / 2 + start; 12 | int res = guess(mid); 13 | if (res == 0) { 14 | return mid; 15 | } 16 | if (res > 0) { 17 | start = mid + 1; 18 | } else { 19 | end = mid; 20 | } 21 | } 22 | return start; 23 | } 24 | } -------------------------------------------------------------------------------- /Medium/275 H-Index II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int hIndex(int[] citations) { 3 | if (citations == null || citations.length == 0) { 4 | return 0; 5 | } 6 | int start = 0; 7 | int end = citations.length - 1; 8 | while (start <= end) { 9 | int mid = (end - start) / 2 + start; 10 | int i = citations.length - mid; 11 | if (citations[mid] >= i && (mid == 0 || citations[mid - 1] <= i)) { 12 | return i; 13 | } else { 14 | if (citations[mid] >= i) { 15 | end = mid; 16 | } else { 17 | start = mid + 1; 18 | } 19 | } 20 | } 21 | return citations.length - start; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/063 Unique Paths II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 | if (obstacleGrid == null || obstacleGrid.length == 0 4 | || obstacleGrid[0][0] == 1 5 | || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] == 1) { 6 | return 0; 7 | } 8 | int[] dp = new int[obstacleGrid[0].length + 1]; 9 | dp[1] = 1; 10 | for (int[] row : obstacleGrid) { 11 | for (int i = 1; i <= row.length; i++) { 12 | if (row[i - 1] == 1) { 13 | dp[i] = 0; 14 | } else { 15 | dp[i] += dp[i - 1]; 16 | } 17 | } 18 | } 19 | return dp[obstacleGrid[0].length]; 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/035 Search Insert Position.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | return findIDX(nums, 0, nums.length - 1, target); 7 | } 8 | 9 | private int findIDX(int[] nums, int start, int end, int target) { 10 | if (start == end) { 11 | if (start == nums.length - 1 && nums[start] < target) { 12 | start += 1; 13 | } 14 | return start; 15 | } 16 | int mid = (end - start) / 2 + start; 17 | if (nums[mid] < target) { 18 | return findIDX(nums, mid + 1, end, target); 19 | } else { 20 | return findIDX(nums, start, mid, target); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/075 Sort Colors.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void sortColors(int[] nums) { 3 | if (nums == null || nums.length < 2) { 4 | return; 5 | } 6 | int zero = 0; 7 | int two = nums.length - 1; 8 | int i = zero; 9 | while (i <= two) { 10 | if (nums[i] == 0) { 11 | swap(nums, zero, i); 12 | zero += 1; 13 | i += 1; 14 | } else if (nums[i] == 2) { 15 | swap(nums, two, i); 16 | two -= 1; 17 | } else { 18 | i += 1; 19 | } 20 | } 21 | } 22 | 23 | private void swap(int[] nums, int i, int j) { 24 | int temp = nums[i]; 25 | nums[i] = nums[j]; 26 | nums[j] = temp; 27 | } 28 | } -------------------------------------------------------------------------------- /Medium/375 Guess Number Higher or Lower II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int getMoneyAmount(int n) { 3 | int[][] cost = new int[n + 1][n + 1]; 4 | return getCost(cost, 1, n); 5 | } 6 | 7 | private int getCost(int[][] cost, int start, int end) { 8 | if (start >= end) { 9 | return 0; 10 | } 11 | if (cost[start][end] != 0) { 12 | return cost[start][end]; 13 | } 14 | int totalCost = Integer.MAX_VALUE; 15 | for (int i = start; i <= end; i++) { 16 | int tempCost = i; 17 | tempCost += Math.max(getCost(cost, start, i - 1), getCost(cost, i + 1, end)); 18 | totalCost = Math.min(totalCost, tempCost); 19 | } 20 | cost[start][end] = totalCost; 21 | return totalCost; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/059 Spiral Matrix II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[][] generateMatrix(int n) { 3 | int[][] result = new int[n][n]; 4 | fill(result, 0, 1, n); 5 | return result; 6 | } 7 | 8 | private void fill(int[][] result, int k, int start, int n) { 9 | if (n < 1) { 10 | return; 11 | } 12 | if (n == 1) { 13 | result[k][k] = start; 14 | return; 15 | } 16 | n -= 1; 17 | for (int i = 0; i < n; i++) { 18 | result[k][k + i] = start; 19 | result[k + i][k + n] = start + n; 20 | result[k + n][k + n - i] = start + 2 * n; 21 | result[k + n - i][k] = start + 3 * n; 22 | start += 1; 23 | } 24 | start += 3 * n; 25 | fill(result, k + 1, start, n - 1); 26 | } 27 | } -------------------------------------------------------------------------------- /Medium/376 Wiggle Subsequence.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int wiggleMaxLength(int[] nums) { 3 | if (nums == null) { 4 | return 0; 5 | } 6 | if (nums.length < 2) { 7 | return nums.length; 8 | } 9 | int i = 1; 10 | while (i < nums.length && nums[i] == nums[i - 1]) { 11 | i += 1; 12 | } 13 | if (i == nums.length) { 14 | return 1; 15 | } 16 | int count = 2; 17 | boolean flag = (nums[i] > nums[i - 1]); 18 | i += 1; 19 | while (i < nums.length) { 20 | if (flag != (nums[i] > nums[i - 1]) && nums[i] != nums[i - 1]) { 21 | flag = (nums[i] > nums[i - 1]); 22 | count += 1; 23 | } 24 | i += 1; 25 | } 26 | return count; 27 | } 28 | } -------------------------------------------------------------------------------- /Medium/213 House Robber II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int rob(int[] nums) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | if (nums.length == 1) { 7 | return nums[0]; 8 | } 9 | int first1 = 0; 10 | int first2 = 0; 11 | int notFirst1 = 0; 12 | int notFirst2 = 0; 13 | for (int i = 1; i < nums.length; i++) { 14 | int temp = first2 + nums[i - 1]; 15 | first2 = Math.max(first1, first2); 16 | first1 = temp; 17 | temp = notFirst2 + nums[i]; 18 | notFirst2 = Math.max(notFirst1, notFirst2); 19 | notFirst1 = temp; 20 | } 21 | int sum1 = Math.max(first1, first2); 22 | int sum2 = Math.max(notFirst1, notFirst2); 23 | return Math.max(sum1, sum2); 24 | } 25 | } -------------------------------------------------------------------------------- /Medium/216 Combination Sum III.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> combinationSum3(int k, int n) { 3 | List> combinations = new ArrayList<>(); 4 | search(combinations, 0, k, n, new ArrayList<>()); 5 | return combinations; 6 | } 7 | 8 | private void search(List> combinations, int low, 9 | int k, int n, List cur) { 10 | if (n == 0 && k == 0) { 11 | combinations.add(cur); 12 | return; 13 | } 14 | if (n < low * k || n > 9 * k) { 15 | return; 16 | } 17 | for (int i = low + 1; i <= 9; i++) { 18 | List temp = new ArrayList<>(); 19 | temp.addAll(cur); 20 | temp.add(i); 21 | search(combinations, i, k - 1, n - i, temp); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Medium/046 Permutations.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> permute(int[] nums) { 3 | List> permutations = new ArrayList<>(); 4 | permutations.add(new ArrayList<>()); 5 | for (int i = 0; i < nums.length; i++) { 6 | int num = nums[i]; 7 | List> newList = new ArrayList<>(); 8 | for (int j = 0; j < permutations.size(); j++) { 9 | List cur = permutations.get(j); 10 | for (int k = 0; k <= i; k++) { 11 | List temp = new ArrayList<>(); 12 | temp.addAll(cur); 13 | temp.add(k, num); 14 | newList.add(temp); 15 | } 16 | } 17 | permutations = newList; 18 | } 19 | return permutations; 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /Medium/108 Convert Sorted Array to Binary Search Tree.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode sortedArrayToBST(int[] nums) { 12 | if (nums == null) { 13 | return null; 14 | } 15 | return buildBST(nums, 0, nums.length - 1); 16 | } 17 | 18 | private TreeNode buildBST(int[] nums, int start, int end) { 19 | if (start > end) { 20 | return null; 21 | } 22 | int mid = (end - start) / 2 + start; 23 | TreeNode root = new TreeNode(nums[mid]); 24 | root.left = buildBST(nums, start, mid - 1); 25 | root.right = buildBST(nums, mid + 1, end); 26 | return root; 27 | } 28 | } -------------------------------------------------------------------------------- /Easy/013 Roman to Integer.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int romanToInt(String s) { 3 | int ret = 0; 4 | for (int i = 1; i < s.length(); i++) { 5 | if (toNumber(s.charAt(i - 1)) < toNumber(s.charAt(i))) { 6 | ret -= toNumber(s.charAt(i - 1)); 7 | } else { 8 | ret += toNumber(s.charAt(i - 1)); 9 | } 10 | } 11 | ret += toNumber(s.charAt(s.length() - 1)); 12 | return ret; 13 | } 14 | 15 | private int toNumber(char ch) { 16 | switch (ch) { 17 | case 'I': return 1; 18 | case 'V': return 5; 19 | case 'X': return 10; 20 | case 'L': return 50; 21 | case 'C': return 100; 22 | case 'D': return 500; 23 | case 'M': return 1000; 24 | default : return 0; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Medium/094 Binary Tree Inorder Traversal.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List inorderTraversal(TreeNode root) { 12 | ArrayList list = new ArrayList(); 13 | 14 | Stack stack = new Stack(); 15 | TreeNode cur = root; 16 | 17 | while(!stack.empty() || cur != null){ 18 | if (cur != null) { 19 | stack.push(cur); 20 | cur = cur.left; 21 | } else { 22 | cur = stack.pop(); 23 | list.add(cur.val); 24 | cur = cur.right; 25 | } 26 | } 27 | 28 | return list; 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/230 Kth Smallest Element in a BST.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int kthSmallest(TreeNode root, int k) { 12 | Stack stack = new Stack(); 13 | TreeNode cur = root; 14 | int count = 0; 15 | while (!stack.isEmpty() || cur != null) { 16 | if (cur != null) { 17 | stack.push(cur); 18 | cur = cur.left; 19 | } else { 20 | cur = stack.pop(); 21 | count += 1; 22 | if (count == k) { 23 | return cur.val; 24 | } 25 | cur = cur.right; 26 | } 27 | } 28 | return 0; 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/298 Binary Tree Longest Consecutive Sequence.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | int upper = Integer.MAX_VALUE; 12 | 13 | public int longestConsecutive(TreeNode root) { 14 | return search(root, upper, 0); 15 | } 16 | 17 | private int search(TreeNode node, int value, int len) { 18 | if (node == null) { 19 | return len; 20 | } 21 | int newLen = 1; 22 | if (value != upper && node.val - value == 1) { 23 | newLen = len + 1; 24 | } 25 | int temp = Math.max(search(node.left, node.val, newLen), 26 | search(node.right, node.val, newLen)); 27 | return Math.max(temp, len); 28 | } 29 | } -------------------------------------------------------------------------------- /Medium/245 Shortest Word Distance III.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int shortestWordDistance(String[] words, String word1, String word2) { 3 | int posA = -1; 4 | int posB = -1; 5 | int minDistance = Integer.MAX_VALUE; 6 | 7 | for (int i = 0; i < words.length; i++) { 8 | String word = words[i]; 9 | 10 | if (word.equals(word1)) { 11 | posA = i; 12 | } else if (word.equals(word2)) { 13 | posB = i; 14 | } 15 | 16 | if (posA != -1 && posB != -1 && posA != posB) { 17 | minDistance = Math.min(minDistance, Math.abs(posA - posB)); 18 | } 19 | 20 | if (word1.equals(word2)) { 21 | posB = posA; 22 | } 23 | } 24 | 25 | return minDistance; 26 | } 27 | } -------------------------------------------------------------------------------- /Medium/264 Ugly Number II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int nthUglyNumber(int n) { 3 | int[] res = new int[n]; 4 | res[0] = 1; 5 | int[] prod = {2, 3, 5}; 6 | int[] primes = {2, 3, 5}; 7 | int[] idx = {0, 0, 0}; 8 | 9 | for (int i = 1; i < n; i++) { 10 | int k = 0; 11 | if (prod[1] <= prod[0] && prod[1] <= prod[2]) { 12 | k = 1; 13 | } 14 | if (prod[2] <= prod[0] && prod[2] <= prod[1]) { 15 | k = 2; 16 | } 17 | 18 | int cur = prod[k]; 19 | if (cur > res[i - 1]) { 20 | res[i] = cur; 21 | } else { 22 | i -= 1; 23 | } 24 | 25 | idx[k] += 1; 26 | prod[k] = res[idx[k]] * primes[k]; 27 | } 28 | return res[n - 1]; 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/077 Combinations.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> combine(int n, int k) { 3 | List> result = new ArrayList<>(); 4 | if (n < k || k < 1 || n < 1) { 5 | return result; 6 | } 7 | search(new ArrayList(), k, 1, n, result); 8 | return result; 9 | } 10 | 11 | private void search(List curList, int remain, 12 | int start, int n, List> result) { 13 | if (remain == 0) { 14 | List list = new ArrayList<>(); 15 | list.addAll(curList); 16 | result.add(list); 17 | return; 18 | } 19 | for (int i = start; i + remain < n + 2; i++) { 20 | curList.add(i); 21 | search(curList, remain - 1, i + 1, n, result); 22 | curList.remove(curList.size() - 1); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Medium/254 Factor Combinations.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> getFactors(int n) { 3 | List> result = new ArrayList<>(); 4 | if (n < 4) { 5 | return result; 6 | } 7 | search(result, 2, new ArrayList(), n); 8 | result.remove(result.size() - 1); 9 | return result; 10 | } 11 | 12 | private void search(List> result, 13 | int min, List comb, int remain) { 14 | for (int i = min; i <= Math.sqrt(remain); i++) { 15 | if (remain % i == 0) { 16 | comb.add(i); 17 | search(result, i, comb, remain / i); 18 | comb.remove(comb.size() - 1); 19 | } 20 | } 21 | comb.add(remain); 22 | result.add(new ArrayList (comb)); 23 | comb.remove(comb.size() - 1); 24 | } 25 | } -------------------------------------------------------------------------------- /Medium/285 Inorder Successor in BST.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 12 | if (p.right != null) { 13 | p = p.right; 14 | while (p.left != null) { 15 | p = p.left; 16 | } 17 | return p; 18 | } 19 | TreeNode successor = null; 20 | TreeNode node = root; 21 | while (node.val != p.val) { 22 | if (node.val < p.val) { 23 | node = node.right; 24 | } else { 25 | successor = node; 26 | node = node.left; 27 | } 28 | } 29 | return successor; 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /getList.py: -------------------------------------------------------------------------------- 1 | import os 2 | out = open('list.txt','w') 3 | readme = open('README.md','w') 4 | readme.write('# LeetCode\n') 5 | readme.write('LeetCode Solution Code by Tiancheng Gong\n') 6 | readme.write('\n') 7 | readme.write('Covered Questions\n') 8 | readme.write('\n') 9 | 10 | out.write('Medium:\n') 11 | readme.write('* Medium: ') 12 | medium = os.listdir(os.path.join(os.path.abspath('.'), 'Medium')) 13 | readme.write(str(len(medium)) + '\n') 14 | for name in medium: 15 | out.write(name[0: -4] + '\n') 16 | readme.write(' * ' + name[0: -4] + '\n') 17 | 18 | 19 | out.write('\n') 20 | readme.write('\n') 21 | 22 | out.write('Hard:\n') 23 | readme.write('* Hard: ') 24 | hard = os.listdir(os.path.join(os.path.abspath('.'), 'Hard')) 25 | readme.write(str(len(hard)) + '\n') 26 | for name in hard: 27 | out.write(name[0: -4] + '\n') 28 | readme.write(' * ' + name[0: -4] + '\n') 29 | 30 | out.close() 31 | readme.close() 32 | -------------------------------------------------------------------------------- /Medium/147 Insertion Sort List.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode insertionSortList(ListNode head) { 11 | if (head == null) { 12 | return head; 13 | } 14 | ListNode preHead = new ListNode(0); 15 | preHead.next = head; 16 | ListNode cur = head.next; 17 | head.next = null; 18 | while (cur != null) { 19 | ListNode next = cur.next; 20 | ListNode node = preHead; 21 | while (node.next != null && node.next.val < cur.val) { 22 | node = node.next; 23 | } 24 | cur.next = node.next; 25 | node.next = cur; 26 | cur = next; 27 | } 28 | return preHead.next; 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/300 Longest Increasing Subsequence.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLIS(int[] nums) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | int[] mins = new int[nums.length + 1]; 7 | mins[0] = Integer.MIN_VALUE; 8 | int maxLen = 0; 9 | for (int num : nums) { 10 | int idx = bs(mins, num, maxLen); 11 | mins[idx] = num; 12 | maxLen = Math.max(idx, maxLen); 13 | } 14 | return maxLen; 15 | } 16 | 17 | private int bs(int[] mins, int target, int end) { 18 | int start = 0; 19 | while (start < end) { 20 | int mid = end - (end - start) / 2; 21 | if (mins[mid] >= target) { 22 | end = mid - 1; 23 | } else { 24 | start = mid; 25 | } 26 | } 27 | return start + 1; 28 | } 29 | } -------------------------------------------------------------------------------- /Medium/318 Maximum Product of Word Lengths.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProduct(String[] words) { 3 | int product = 0; 4 | int[] hashArray = new int[words.length]; 5 | for (int i = 0; i < words.length; i++) { 6 | String s = words[i]; 7 | int hash = 0; 8 | for (int j = 0; j < s.length(); j++) { 9 | hash = hash | (1 << (s.charAt(j) - 97)); 10 | } 11 | hashArray[i] = hash; 12 | } 13 | for (int i = 0; i < hashArray.length; i++) { 14 | for (int j = 0; j < hashArray.length; j++) { 15 | if ((hashArray[i] & hashArray[j]) == 0) { 16 | int l1 = words[i].length(); 17 | int l2 = words[j].length(); 18 | product = Math.max(product, l1 * l2); 19 | } 20 | } 21 | } 22 | return product; 23 | } 24 | } -------------------------------------------------------------------------------- /Medium/090 Subsets II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> subsetsWithDup(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | Arrays.sort(nums); 5 | dfs(res, new ArrayList(), nums, 0); 6 | return res; 7 | } 8 | 9 | private void dfs(List> res, List temp, 10 | int[] nums, int idx) { 11 | 12 | List list = new ArrayList<>(); 13 | list.addAll(temp); 14 | res.add(list); 15 | 16 | if (idx == nums.length) { 17 | return; 18 | } 19 | int prev = nums[idx] - 1; 20 | for (int i = idx; i < nums.length; i++) { 21 | if (nums[i] != prev) { 22 | prev = nums[i]; 23 | temp.add(prev); 24 | dfs(res, temp, nums, i + 1); 25 | temp.remove(temp.size() - 1); 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Medium/116 Populating Next Right Pointers in Each Node.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * public class TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode left, right, next; 6 | * TreeLinkNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public void connect(TreeLinkNode root) { 11 | if (root == null) { 12 | return; 13 | } 14 | TreeLinkNode node = root; 15 | while (node.left != null) { 16 | TreeLinkNode left = node.left; 17 | left.next = node.right; 18 | TreeLinkNode temp = node.right; 19 | node = node.next; 20 | while (node!= null) { 21 | temp.next = node.left; 22 | node.left.next = node.right; 23 | temp = node.right; 24 | node = node.next; 25 | } 26 | node = left; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Medium/378 Kth Smallest Element in a Sorted Matrix.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int kthSmallest(int[][] matrix, int k) { 3 | int n = matrix.length; 4 | PriorityQueue pq = new PriorityQueue<>(new Comparator(){ 5 | public int compare(Integer i1, Integer i2) { 6 | int x1 = i1 / n; 7 | int y1 = i1 % n; 8 | int x2 = i2 / n; 9 | int y2 = i2 % n; 10 | return matrix[x1][y1] - matrix[x2][y2]; 11 | } 12 | }); 13 | for (int i = 0; i < n; i++) { 14 | pq.add(i * n); 15 | } 16 | for (int i = 1; i < k; i++) { 17 | int cur = pq.poll(); 18 | if (cur % n != n - 1) { 19 | pq.add(cur + 1); 20 | } 21 | } 22 | int kth = pq.poll(); 23 | return matrix[kth / n][kth % n]; 24 | } 25 | } -------------------------------------------------------------------------------- /Medium/251 Flatten 2D Vector.txt: -------------------------------------------------------------------------------- 1 | public class Vector2D implements Iterator { 2 | Iterator> iter1; 3 | Iterator iter2; 4 | 5 | public Vector2D(List> vec2d) { 6 | iter1 = vec2d.iterator(); 7 | iter2 = new ArrayList().iterator(); 8 | while (!iter2.hasNext() && iter1.hasNext()) { 9 | iter2 = iter1.next().iterator(); 10 | } 11 | } 12 | 13 | @Override 14 | public Integer next() { 15 | Integer i = iter2.next(); 16 | while (!iter2.hasNext() && iter1.hasNext()) { 17 | iter2 = iter1.next().iterator(); 18 | } 19 | return i; 20 | } 21 | 22 | @Override 23 | public boolean hasNext() { 24 | return iter2.hasNext(); 25 | } 26 | } 27 | 28 | /** 29 | * Your Vector2D object will be instantiated and called as such: 30 | * Vector2D i = new Vector2D(vec2d); 31 | * while (i.hasNext()) v[f()] = i.next(); 32 | */ -------------------------------------------------------------------------------- /Medium/331 Verify Preorder Serialization of a Binary Tree.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isValidSerialization(String preorder) { 3 | if (preorder == null || preorder.equals('#')) { 4 | return true; 5 | } 6 | String[] nodes = preorder.split(","); 7 | Stack stack = new Stack<>(); 8 | for (int i = 0; i < nodes.length; i++) { 9 | String node = nodes[i]; 10 | if (node.equals("#")) { 11 | while (!stack.isEmpty() && stack.peek() == 1) { 12 | stack.pop(); 13 | } 14 | if (stack.isEmpty()) { 15 | return i == nodes.length - 1; 16 | } else { 17 | stack.pop(); 18 | stack.push(1); 19 | } 20 | } else { 21 | stack.push(0); 22 | } 23 | } 24 | return stack.isEmpty(); 25 | } 26 | } -------------------------------------------------------------------------------- /Medium/081 Search in Rotated Sorted Array II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean search(int[] nums, int target) { 3 | if (nums == null) { 4 | return false; 5 | } 6 | int start = 0; 7 | int end = nums.length - 1; 8 | while (start <= end) { 9 | int mid = (end - start) / 2 + start; 10 | if (nums[mid] == target) 11 | return true; 12 | if (nums[start] < nums[mid]) { 13 | if (nums[start] <= target && nums[mid] > target) 14 | end = mid - 1; 15 | else 16 | start = mid + 1; 17 | } else if (nums[start] > nums[mid]) { 18 | if (nums[mid] < target && nums[end] >= target) 19 | start = mid + 1; 20 | else 21 | end = mid - 1; 22 | } else 23 | start++; 24 | } 25 | return false; 26 | } 27 | } -------------------------------------------------------------------------------- /Hard/033 Search in Rotated Sorted Array.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int search(int[] nums, int target) { 3 | if (nums == null) { 4 | return -1; 5 | } 6 | int start = 0; 7 | int end = nums.length - 1; 8 | while (start <= end) { 9 | int mid = (end - start) / 2 + start; 10 | if (nums[mid] == target) { 11 | return mid; 12 | } 13 | if (nums[start] <= nums[mid]) { 14 | if (nums[start] <= target && nums[mid] > target) { 15 | end = mid - 1; 16 | } else { 17 | start = mid + 1; 18 | } 19 | } else { 20 | if (nums[mid] < target && nums[end] >= target) { 21 | start = mid + 1; 22 | } else { 23 | end = mid - 1; 24 | } 25 | } 26 | } 27 | return -1; 28 | } 29 | } -------------------------------------------------------------------------------- /Medium/366 Find Leaves of Binary Tree.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | 12 | public List> findLeaves(TreeNode root) { 13 | List> leavesList = new ArrayList<>(); 14 | TreeNode cur = root; 15 | findDepth(cur, leavesList); 16 | return leavesList; 17 | } 18 | 19 | private int findDepth(TreeNode cur, List> leavesList) { 20 | if (cur == null) { 21 | return 0; 22 | } 23 | int level = Math.max(findDepth(cur.left, leavesList), findDepth(cur.right, leavesList)); 24 | if (leavesList.size() <= level) { 25 | leavesList.add(new ArrayList()); 26 | } 27 | leavesList.get(level).add(cur.val); 28 | return level + 1; 29 | } 30 | } -------------------------------------------------------------------------------- /Hard/123 Best Time to Buy and Sell Stock III.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | if (prices == null || prices.length == 0) { 4 | return 0; 5 | } 6 | 7 | int n = prices.length; 8 | int[] profit1 = new int[n]; 9 | int[] profit2 = new int[n]; 10 | int min = prices[0]; 11 | int max = prices[n - 1]; 12 | 13 | for (int i = 1; i < n; i++) { 14 | int j = n - 1 - i; 15 | min = Math.min(min, prices[i]); 16 | profit1[i] = Math.max(profit1[i - 1], prices[i] - min); 17 | max = Math.max(max, prices[j]); 18 | profit2[j] = Math.max(profit2[j + 1], max - prices[j]); 19 | } 20 | 21 | int profit = Math.max(profit1[n - 1], profit2[0]); 22 | for (int i = 0; i < n - 1; i++) { 23 | profit = Math.max(profit, profit1[i] + profit2[i + 1]); 24 | } 25 | return profit; 26 | } 27 | } -------------------------------------------------------------------------------- /Medium/142 Linked List Cycle II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode detectCycle(ListNode head) { 14 | if (head == null || head.next == null) { 15 | return null; 16 | } 17 | ListNode walker = head; 18 | ListNode runner = head.next; 19 | while (walker != runner) { 20 | if (runner.next == null || runner.next.next == null) { 21 | return null; 22 | } 23 | walker = walker.next; 24 | runner = runner.next.next; 25 | } 26 | walker = head; 27 | runner = runner.next; 28 | while (walker != runner) { 29 | walker = walker.next; 30 | runner = runner.next; 31 | } 32 | return walker; 33 | } 34 | } -------------------------------------------------------------------------------- /Hard/265 Paint House II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minCostII(int[][] costs) { 3 | if (costs == null || costs.length == 0) { 4 | return 0; 5 | } 6 | int min1 = 0; 7 | int min2 = 0; 8 | int idx = 0; 9 | for (int[] cost : costs) { 10 | int temp; 11 | int tempMin1 = Integer.MAX_VALUE; 12 | int tempMin2 = Integer.MAX_VALUE; 13 | int tempIDX = 0; 14 | for (int i = 0; i < cost.length; i++) { 15 | temp = ((i != idx) ? min1 : min2) + cost[i]; 16 | if (temp <= tempMin1) { 17 | tempIDX = i; 18 | tempMin2 = tempMin1; 19 | tempMin1 = temp; 20 | } else if (temp <= tempMin2) { 21 | tempMin2 = temp; 22 | } 23 | } 24 | min1 = tempMin1; 25 | min2 = tempMin2; 26 | idx = tempIDX; 27 | } 28 | return min1; 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/369 Plus One Linked List.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode plusOne(ListNode head) { 11 | ListNode newhead = new ListNode(1); 12 | newhead.next = head; 13 | Stack stack = new Stack<>(); 14 | ListNode cur = newhead; 15 | if (operate(head)) { 16 | return newhead; 17 | } else { 18 | return head; 19 | } 20 | } 21 | 22 | private boolean operate(ListNode cur) { 23 | if (cur.next == null) { 24 | cur.val = (cur.val + 1) % 10; 25 | return cur.val == 0; 26 | } else { 27 | if (!operate(cur.next)) { 28 | return false; 29 | } else { 30 | cur.val = (cur.val + 1) % 10; 31 | return cur.val == 0; 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Medium/247 Strobogrammatic Number II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List findStrobogrammatic(int n) { 3 | List result = new ArrayList<>(); 4 | if (n == 0) { 5 | return result; 6 | } 7 | if (n % 2 == 1) { 8 | result.add("0"); 9 | result.add("1"); 10 | result.add("8"); 11 | } else { 12 | result.add(""); 13 | } 14 | n /= 2; 15 | int[] nums1 = {0, 1, 6, 9, 8}; 16 | int[] nums2 = {0, 1, 9, 6, 8}; 17 | while (n > 0) { 18 | List temp = new ArrayList<>(); 19 | int start = (n == 1) ? 1 : 0; 20 | for (String s : result) { 21 | int i = start; 22 | while (i < nums1.length) { 23 | temp.add(nums1[i] + s + nums2[i]); 24 | i += 1; 25 | } 26 | } 27 | result = temp; 28 | n -= 1; 29 | } 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /Medium/382 Linked List Random Node.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | 10 | import java.util.Random; 11 | 12 | public class Solution { 13 | List list; 14 | /** @param head The linked list's head. 15 | Note that the head is guaranteed to be not null, so it contains at least one node. */ 16 | public Solution(ListNode head) { 17 | list = new ArrayList<>(); 18 | while (head != null) { 19 | list.add(head.val); 20 | head = head.next; 21 | } 22 | } 23 | 24 | /** Returns a random node's value. */ 25 | public int getRandom() { 26 | Random random = new Random(); 27 | return list.get(random.nextInt(list.size())); 28 | } 29 | } 30 | 31 | /** 32 | * Your Solution object will be instantiated and called as such: 33 | * Solution obj = new Solution(head); 34 | * int param_1 = obj.getRandom(); 35 | */ -------------------------------------------------------------------------------- /Medium/011 Container With Most Water.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxArea(int[] height) { 3 | int max = 0; 4 | if (height != null && height.length > 1) { 5 | int start = 0; 6 | int end = height.length - 1; 7 | int width = height.length - 1; 8 | while (start < end) { 9 | max = Math.max(Math.min(height[start], height[end]) * width, max); 10 | if (height[start] < height[end]) { 11 | int sign = height[start]; 12 | while (width > 0 && height[start] <= sign) { 13 | start += 1; 14 | width -= 1; 15 | } 16 | } else { 17 | int sign = height[end]; 18 | while (width > 0 && height[end] <= sign) { 19 | end -= 1; 20 | width -= 1; 21 | } 22 | } 23 | } 24 | } 25 | return max; 26 | } 27 | } -------------------------------------------------------------------------------- /Hard/312 Burst Balloons.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxCoins(int[] nums) { 3 | 4 | // re-define the array 5 | int[] newNums = new int[nums.length + 2]; 6 | newNums[0] = 1; 7 | newNums[newNums.length - 1] = 1; 8 | for (int i = 0; i < nums.length; i++) { 9 | newNums[i + 1] = nums[i]; 10 | } 11 | 12 | int[][] coins = new int[newNums.length][newNums.length]; 13 | for (int k = 1; k <= nums.length; k++) { 14 | for (int left = 0; left < newNums.length - 1 - k; left++) { 15 | int right = left + k + 1; 16 | for (int last = left + 1; last < right; last++) { 17 | int temp = coins[left][last] + coins[last][right] 18 | + newNums[left] * newNums[last] * newNums[right]; 19 | coins[left][right] = Math.max(coins[left][right], temp); 20 | } 21 | } 22 | } 23 | 24 | return coins[0][newNums.length - 1]; 25 | } 26 | } -------------------------------------------------------------------------------- /Hard/296 Best Meeting Point.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minTotalDistance(int[][] grid) { 3 | int count = 0; 4 | List posX = new ArrayList<>(); 5 | List posY = new ArrayList<>(); 6 | for (int i = 0; i < grid.length; i++) { 7 | for (int j = 0; j < grid[0].length; j++) { 8 | if (grid[i][j] == 1) { 9 | count++; 10 | posX.add(j); 11 | posY.add(i); 12 | } 13 | } 14 | } 15 | if (count == 0) { 16 | return 0; 17 | } else { 18 | int py = posY.get(count / 2); 19 | Collections.sort(posX); 20 | int px = posX.get(count / 2); 21 | int dis = 0; 22 | for (int i = 0; i < posX.size(); i++) { 23 | int x = posX.get(i); 24 | int y = posY.get(i); 25 | dis += Math.abs(px - x) + Math.abs(py - y); 26 | } 27 | return dis; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/039 Combination Sum.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> combinationSum(int[] candidates, int target) { 3 | List> result = new ArrayList<>(); 4 | if (candidates == null || candidates.length == 0) { 5 | return result; 6 | } 7 | Arrays.sort(candidates); 8 | search(result, candidates, target, new ArrayList(), 0); 9 | return result; 10 | } 11 | 12 | private void search(List> result, int[] candidates, int target, 13 | List temp, int start) { 14 | if (target == 0) { 15 | List newList = new ArrayList<>(); 16 | newList.addAll(temp); 17 | result.add(newList); 18 | return; 19 | } 20 | for (int i = start; i < candidates.length && candidates[i] <= target; i++) { 21 | temp.add(candidates[i]); 22 | search(result, candidates, target - candidates[i], temp, i); 23 | temp.remove(temp.size() - 1); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Medium/199 Binary Tree Right Side View.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List rightSideView(TreeNode root) { 12 | List result = new ArrayList<>(); 13 | if (root == null) { 14 | return result; 15 | } 16 | List level = new ArrayList<>(); 17 | level.add(root); 18 | while (level.size() > 0) { 19 | result.add(level.get(level.size() - 1).val); 20 | List temp = new ArrayList<>(); 21 | for (TreeNode node : level) { 22 | if (node.left != null) { 23 | temp.add(node.left); 24 | } 25 | if (node.right != null) { 26 | temp.add(node.right); 27 | } 28 | } 29 | level = temp; 30 | } 31 | return result; 32 | } 33 | } -------------------------------------------------------------------------------- /Medium/114 Flatten Binary Tree to Linked List.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public void flatten(TreeNode root) { 12 | if (root == null) { 13 | return; 14 | } 15 | flattenR(root); 16 | } 17 | 18 | private TreeNode flattenR(TreeNode node) { 19 | if (node.left == null && node.right == null) { 20 | return node; 21 | } 22 | if (node.left != null) { 23 | TreeNode left = flattenR(node.left); 24 | if (node.right != null) { 25 | TreeNode right = flattenR(node.right); 26 | left.right = node.right; 27 | left = right; 28 | } 29 | node.right = node.left; 30 | node.left = null; 31 | return left; 32 | } else { 33 | return flattenR(node.right); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Hard/145 Binary Tree Postorder Traversal.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List postorderTraversal(TreeNode root) { 12 | List result = new ArrayList<>(); 13 | List temp = new ArrayList<>(); 14 | if (root == null) { 15 | return result; 16 | } 17 | Stack stack = new Stack<>(); 18 | stack.push(root); 19 | while (!stack.isEmpty()) { 20 | TreeNode cur = stack.pop(); 21 | temp.add(cur.val); 22 | if (cur.left != null) { 23 | stack.push(cur.left); 24 | } 25 | if (cur.right != null) { 26 | stack.push(cur.right); 27 | } 28 | } 29 | for (int i = temp.size() - 1; i >= 0; i--) { 30 | result.add(temp.get(i)); 31 | } 32 | return result; 33 | } 34 | } -------------------------------------------------------------------------------- /Hard/340 Longest Substring with At Most K Distinct Characters.txt: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | public int lengthOfLongestSubstringKDistinct(String s, int k) { 5 | if (k <= 0) { 6 | return 0; 7 | } 8 | int length = 0; 9 | int start = 0; 10 | int end = 0; 11 | Hashtable lastTable = new Hashtable<>(); 12 | while (end < s.length()) { 13 | if (lastTable.size() <= k) { 14 | lastTable.put(s.charAt(end), end); 15 | length = Math.max(end - start, length); 16 | end += 1; 17 | if (end == s.length() && lastTable.size() <= k) { 18 | length = Math.max(end - start, length); 19 | } 20 | } else { 21 | while (start != lastTable.get(s.charAt(start))) { 22 | start += 1; 23 | } 24 | lastTable.remove(s.charAt(start)); 25 | start += 1; 26 | } 27 | } 28 | return length; 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/368 Largest Divisible Subset.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List largestDivisibleSubset(int[] nums) { 3 | List res = new ArrayList<>(); 4 | if (nums == null || nums.length == 0) { 5 | return res; 6 | } 7 | Arrays.sort(nums); 8 | int globalSize = 0; 9 | int idx = 0; 10 | int[][] count = new int[nums.length][2]; 11 | for (int i = 0; i < nums.length; i++) { 12 | count[i][0] = -1; 13 | count[i][1] = 1; 14 | for (int j = 0; j < i; j++) { 15 | if (nums[i] % nums[j] == 0 && count[j][1] + 1 > count[i][1]) { 16 | count[i][0] = j; 17 | count[i][1] = count[j][1] + 1; 18 | } 19 | } 20 | if (count[i][1] > globalSize) { 21 | globalSize = count[i][1]; 22 | idx = i; 23 | } 24 | } 25 | while (idx != -1) { 26 | res.add(nums[idx]); 27 | idx = count[idx][0]; 28 | } 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /Hard/159 Longest Substring with At Most Two Distinct Characters.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLongestSubstringTwoDistinct(String s) { 3 | int length = 0; 4 | int start = 0; 5 | int end = 0; 6 | int count = 0; 7 | int[] last = new int[2]; 8 | char[] chars = new char[2]; 9 | while (end < s.length()) { 10 | char c = s.charAt(end); 11 | int i = 0; 12 | if (count == 2) { 13 | if (chars[0] == c || chars[1] == c) { 14 | i = (chars[0] == c) ? 0 : 1; 15 | } else { 16 | i = (last[0] < last[1]) ? 0 : 1; 17 | start = last[i] + 1; 18 | } 19 | } else { 20 | if (chars[0] != c) { 21 | i = count; 22 | count += 1; 23 | } 24 | } 25 | chars[i] = c; 26 | last[i] = end; 27 | end += 1; 28 | length = Math.max(end - start, length); 29 | } 30 | return length; 31 | } 32 | } -------------------------------------------------------------------------------- /Medium/200 Number of Islands.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numIslands(char[][] grid) { 3 | if (grid == null || grid.length == 0) { 4 | return 0; 5 | } 6 | int count = 0; 7 | for (int i = 0; i < grid.length; i++) { 8 | for (int j = 0; j < grid[0].length; j++) { 9 | if (grid[i][j] == '1') { 10 | count += 1; 11 | eliminate(grid, i, j); 12 | } 13 | } 14 | } 15 | return count; 16 | } 17 | 18 | private void eliminate(char[][]grid, int i, int j) { 19 | grid[i][j] = '0'; 20 | if (i > 0 && grid[i - 1][j] == '1') { 21 | eliminate(grid, i - 1, j); 22 | } 23 | if (i < grid.length - 1 && grid[i + 1][j] == '1') { 24 | eliminate(grid, i + 1, j); 25 | } 26 | if (j > 0 && grid[i][j - 1] == '1') { 27 | eliminate(grid, i, j - 1); 28 | } 29 | if (j < grid[0].length - 1 && grid[i][j + 1] == '1') { 30 | eliminate(grid, i, j + 1); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Medium/395 Longest Substring with At Least K Repeating Characters.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestSubstring(String s, int k) { 3 | if (s == null || s.length() == 0) { 4 | return 0; 5 | } 6 | Map map = new HashMap<>(); 7 | for (int i = 0; i < s.length(); i++) { 8 | char c = s.charAt(i); 9 | map.putIfAbsent(c, 0); 10 | map.put(c, map.get(c) + 1); 11 | } 12 | 13 | Character filter = null; 14 | Set keys = map.keySet(); 15 | for (Character c : keys) { 16 | if (map.get(c) < k) { 17 | filter = c; 18 | } 19 | } 20 | 21 | int maxLen = 0; 22 | if (filter == null) { 23 | maxLen = s.length(); 24 | } else { 25 | String[] subStrings = s.split("" + filter); 26 | for (String sub : subStrings) { 27 | maxLen = Math.max(maxLen, longestSubstring(sub, k)); 28 | } 29 | } 30 | 31 | return maxLen; 32 | } 33 | } -------------------------------------------------------------------------------- /Hard/188 Best Time to Buy and Sell Stock IV.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int k, int[] prices) { 3 | if (prices == null || prices.length == 0) { 4 | return 0; 5 | } 6 | 7 | int n = prices.length; 8 | if (2 * k >= n) { 9 | return stockII(prices); 10 | } 11 | 12 | int[] local = new int[k + 1]; 13 | int[] global = new int[k + 1]; 14 | 15 | for (int i = 1; i < prices.length ; i++) { 16 | int diff = prices[i] - prices[i - 1]; 17 | 18 | for (int j = k; j > 0; j--) { 19 | local[j] = Math.max(global[j - 1], local[j] + diff); 20 | global[j] = Math.max(global[j], local[j]); 21 | } 22 | } 23 | 24 | return global[k]; 25 | } 26 | 27 | 28 | public int stockII(int[] prices) { 29 | int profit = 0; 30 | for (int i = 1; i < prices.length; i++) { 31 | int diff = prices[i] - prices[i - 1]; 32 | profit += diff > 0 ? diff : 0; 33 | } 34 | return profit; 35 | } 36 | } -------------------------------------------------------------------------------- /Hard/410 Split Array Largest Sum.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int splitArray(int[] nums, int m) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | long ub = 0; 7 | long lb = 0; 8 | for (int i : nums) { 9 | ub += i; 10 | lb = Math.max(lb, i); 11 | } 12 | lb = Math.max(lb, ub / m); 13 | while (lb < ub) { 14 | long mid = (ub - lb) / 2 + lb; 15 | if (isSplitable(nums, mid, m)) { 16 | ub = mid; 17 | } else { 18 | lb = mid + 1; 19 | } 20 | } 21 | return (int) lb; 22 | } 23 | 24 | private boolean isSplitable(int[] nums, long sum, int m) { 25 | int count = 1; 26 | int tempSum = 0; 27 | for (int i : nums) { 28 | tempSum += i; 29 | if (tempSum > sum) { 30 | count += 1; 31 | if (count > m) { 32 | return false; 33 | } 34 | tempSum = i; 35 | } 36 | } 37 | return true; 38 | } 39 | } -------------------------------------------------------------------------------- /Medium/281 Zigzag Iterator.txt: -------------------------------------------------------------------------------- 1 | public class ZigzagIterator { 2 | 3 | List> iteratorList; 4 | int size; 5 | int clock; 6 | 7 | public ZigzagIterator(List v1, List v2) { 8 | iteratorList = new ArrayList<>(); 9 | iteratorList.add(v1.iterator()); 10 | iteratorList.add(v2.iterator()); 11 | size = iteratorList.size(); 12 | clock = 0; 13 | } 14 | 15 | public int next() { 16 | if (!hasNext()) { 17 | return 0; 18 | } 19 | int val = iteratorList.get(clock).next(); 20 | clock = (clock + 1) % size; 21 | return val; 22 | } 23 | 24 | public boolean hasNext() { 25 | for (int i = 0; i < size; i++) { 26 | if (iteratorList.get(clock).hasNext()) { 27 | return true; 28 | } 29 | clock = (clock + 1) % size; 30 | } 31 | return false; 32 | } 33 | } 34 | 35 | /** 36 | * Your ZigzagIterator object will be instantiated and called as such: 37 | * ZigzagIterator i = new ZigzagIterator(v1, v2); 38 | * while (i.hasNext()) v[f()] = i.next(); 39 | */ -------------------------------------------------------------------------------- /Medium/253 Meeting Rooms II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * public class Interval { 4 | * int start; 5 | * int end; 6 | * Interval() { start = 0; end = 0; } 7 | * Interval(int s, int e) { start = s; end = e; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int minMeetingRooms(Interval[] intervals) { 12 | int len = intervals.length; 13 | int[] start = new int[len]; 14 | int[] end = new int[len]; 15 | for (int i = 0; i < len; i++) { 16 | start[i] = intervals[i].start; 17 | end[i] = intervals[i].end; 18 | } 19 | Arrays.sort(start); 20 | Arrays.sort(end); 21 | int i = 0; 22 | int j = 0; 23 | int temp = Integer.MIN_VALUE; 24 | int count = 0; 25 | int res = 0; 26 | while (j < len) { 27 | temp = end[j]; 28 | while (i < len && start[i] < temp) { 29 | i += 1; 30 | count += 1; 31 | } 32 | res = Math.max(count, res); 33 | count -= 1; 34 | j += 1; 35 | } 36 | return res; 37 | } 38 | } -------------------------------------------------------------------------------- /Medium/173 Binary Search Tree Iterator.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | 11 | public class BSTIterator { 12 | private Stack stack; 13 | 14 | public BSTIterator(TreeNode root) { 15 | stack = new Stack<>(); 16 | while (root != null) { 17 | stack.push(root); 18 | root = root.left; 19 | } 20 | } 21 | 22 | /** @return whether we have a next smallest number */ 23 | public boolean hasNext() { 24 | return !stack.isEmpty(); 25 | } 26 | 27 | /** @return the next smallest number */ 28 | public int next() { 29 | TreeNode next = stack.pop(); 30 | TreeNode node = next.right; 31 | while (node != null) { 32 | stack.push(node); 33 | node = node.left; 34 | } 35 | return next.val; 36 | } 37 | } 38 | 39 | /** 40 | * Your BSTIterator will be called like this: 41 | * BSTIterator i = new BSTIterator(root); 42 | * while (i.hasNext()) v[f()] = i.next(); 43 | */ -------------------------------------------------------------------------------- /Medium/113 Path Sum II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List> pathSum(TreeNode root, int sum) { 12 | List> result = new ArrayList<>(); 13 | List list = new ArrayList<>(); 14 | dfs(result, list, root, sum); 15 | return result; 16 | } 17 | 18 | public void dfs(List>result, List list, TreeNode root,int sum) { 19 | if (root == null) { 20 | return; 21 | } 22 | 23 | list.add(root.val); 24 | 25 | if (root.left == null && root.right == null) { 26 | if (root.val == sum) { 27 | result.add(new ArrayList(list)); 28 | } 29 | } else { 30 | dfs(result, list, root.left, sum - root.val); 31 | dfs(result, list, root.right, sum - root.val); 32 | } 33 | 34 | list.remove(list.size() - 1); 35 | 36 | } 37 | 38 | 39 | } -------------------------------------------------------------------------------- /Medium/261 Graph Valid Tree.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean validTree(int n, int[][] edges) { 3 | if (edges.length != n - 1) { 4 | return false; 5 | } 6 | int[] roots = new int[n]; 7 | int[] heights = new int[n]; 8 | for (int i = 0; i < n; i++) { 9 | roots[i] = i; 10 | heights[i] = 1; 11 | } 12 | for (int i = 0; i < edges.length; i++) { 13 | int[] edge = edges[i]; 14 | int r1 = findRoot(roots, edge[0]); 15 | int r2 = findRoot(roots, edge[1]); 16 | if (r1 == r2) { 17 | return false; 18 | } 19 | if (heights[edge[0]] < heights[edge[1]]) { 20 | roots[r1] = r2; 21 | } else { 22 | roots[r2] = r1; 23 | heights[r2] += 1; 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | private int findRoot(int[] roots, int i) { 30 | while (i != roots[i]) { 31 | int temp = roots[i]; 32 | roots[i] = roots[roots[i]]; 33 | i = temp; 34 | } 35 | return i; 36 | } 37 | } -------------------------------------------------------------------------------- /Medium/284 Peeking Iterator.txt: -------------------------------------------------------------------------------- 1 | // Java Iterator interface reference: 2 | // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html 3 | class PeekingIterator implements Iterator { 4 | Iterator iterator; 5 | Integer next; 6 | boolean hasNext; 7 | 8 | public PeekingIterator(Iterator iterator) { 9 | // initialize any member here. 10 | this.iterator = iterator; 11 | hasNext = iterator.hasNext(); 12 | if (hasNext) { 13 | next = iterator.next(); 14 | } else { 15 | next = null; 16 | } 17 | } 18 | 19 | // Returns the next element in the iteration without advancing the iterator. 20 | public Integer peek() { 21 | return next; 22 | } 23 | 24 | // hasNext() and next() should behave the same as in the Iterator interface. 25 | // Override them if needed. 26 | @Override 27 | public Integer next() { 28 | int res = next; 29 | hasNext = iterator.hasNext(); 30 | if (hasNext()) { 31 | next = iterator.next(); 32 | } else { 33 | next = null; 34 | } 35 | return res; 36 | } 37 | 38 | @Override 39 | public boolean hasNext() { 40 | return hasNext; 41 | } 42 | } -------------------------------------------------------------------------------- /Medium/016 3Sum Closest.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int threeSumClosest(int[] nums, int target) { 3 | Arrays.sort(nums); 4 | Set set = new HashSet<>(); 5 | int closet = nums[0] + nums[1] + nums[2]; 6 | int diff = Math.abs(closet - target); 7 | int i = 0; 8 | while (i < nums.length - 2 && nums[i] <= target / 3 && diff > 0) { 9 | int j = i + 1; 10 | int k = nums.length - 1; 11 | while (j < k && diff > 0) { 12 | int sum = nums[i] + nums[j] + nums[k]; 13 | if (Math.abs(sum - target) < diff) { 14 | closet = sum; 15 | diff = Math.abs(sum - target); 16 | } 17 | if (sum < target) { 18 | j += 1; 19 | } else { 20 | k -= 1; 21 | } 22 | } 23 | i++; 24 | } 25 | if (i < nums.length - 2) { 26 | int sum = nums[i] + nums[i + 1] + nums[i + 2]; 27 | if (Math.abs(sum - target) < diff) { 28 | closet = sum; 29 | } 30 | } 31 | return closet; 32 | } 33 | } -------------------------------------------------------------------------------- /Medium/215 Kth Largest Element in an Array.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findKthLargest(int[] nums, int k) { 3 | return kthSelect(nums, k, 0, nums.length - 1); 4 | } 5 | 6 | private int kthSelect(int[] nums, int k, int start, int end) { 7 | // randomize 8 | int rand = (int) ((end - start) * Math.random()) + start; 9 | int temp = nums[rand]; 10 | nums[rand] = nums[start]; 11 | nums[start] = temp; 12 | 13 | int pivot = temp; 14 | int pointer = start + 1; 15 | for (int i = start + 1; i <= end; i++) { 16 | if (nums[i] > pivot) { 17 | temp = nums[pointer]; 18 | nums[pointer] = nums[i]; 19 | nums[i] = temp; 20 | pointer += 1; 21 | } 22 | } 23 | temp = nums[pointer - 1]; 24 | nums[pointer - 1] = nums[start]; 25 | nums[start] = temp; 26 | 27 | if (pointer == k) { 28 | return nums[k - 1]; 29 | } else if (pointer > k) { 30 | end = pointer - 1; 31 | } else { 32 | start = pointer; 33 | } 34 | return kthSelect(nums, k, start, end); 35 | } 36 | } -------------------------------------------------------------------------------- /Medium/109 Convert Sorted List to Binary Search Tree.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | /** 10 | * Definition for a binary tree node. 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode(int x) { val = x; } 16 | * } 17 | */ 18 | public class Solution { 19 | public TreeNode sortedListToBST(ListNode head) { 20 | if (head == null) { 21 | return null; 22 | } 23 | ListNode walk = head; 24 | ListNode run = head; 25 | ListNode prev = null; 26 | while (run.next != null) { 27 | run = run.next; 28 | if (run.next != null) { 29 | run = run.next; 30 | prev = walk; 31 | walk = walk.next; 32 | } 33 | } 34 | TreeNode node = new TreeNode(walk.val); 35 | if (prev != null) { 36 | prev.next = null; 37 | node.left = sortedListToBST(head); 38 | } 39 | node.right = sortedListToBST(walk.next); 40 | return node; 41 | } 42 | } -------------------------------------------------------------------------------- /Medium/394 Decode String.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String decodeString(String s) { 3 | if (s == null) { 4 | return null; 5 | } 6 | 7 | Stack sbStack = new Stack<>(); 8 | Stack intStack = new Stack<>(); 9 | StringBuilder sb = new StringBuilder(); 10 | int repeat = 0; 11 | 12 | for (int i = 0; i < s.length(); i++) { 13 | char c = s.charAt(i); 14 | if (c == '[') { 15 | sbStack.push(sb); 16 | intStack.push(repeat); 17 | sb = new StringBuilder(); 18 | repeat = 0; 19 | } else if (c == ']') { 20 | StringBuilder temp = sb; 21 | sb = sbStack.pop(); 22 | repeat = intStack.pop(); 23 | while (repeat > 0) { 24 | sb.append(temp); 25 | repeat -= 1; 26 | } 27 | } else if (c >= '0' && c <= '9') { 28 | repeat *= 10; 29 | repeat += c - '0'; 30 | } else { 31 | sb.append(c); 32 | } 33 | } 34 | 35 | return sb.toString(); 36 | } 37 | } -------------------------------------------------------------------------------- /Medium/362 Design Hit Counter.txt: -------------------------------------------------------------------------------- 1 | public class HitCounter { 2 | private ArrayDeque memory; 3 | /** Initialize your data structure here. */ 4 | public HitCounter() { 5 | memory = new ArrayDeque<>(); 6 | } 7 | 8 | /** Record a hit. 9 | @param timestamp - The current timestamp (in seconds granularity). */ 10 | public void hit(int timestamp) { 11 | memory.add(timestamp); 12 | // int top = memory.poll(); 13 | // while (timestamp - top >= 300) { 14 | // top = memory.poll(); 15 | // } 16 | // memory.addFirst(top); 17 | } 18 | 19 | /** Return the number of hits in the past 5 minutes. 20 | @param timestamp - The current timestamp (in seconds granularity). */ 21 | public int getHits(int timestamp) { 22 | if (!memory.isEmpty()) { 23 | while (!memory.isEmpty() && (timestamp - memory.peek()) >= 300) { 24 | memory.poll(); 25 | } 26 | } 27 | return memory.size(); 28 | } 29 | } 30 | 31 | /** 32 | * Your HitCounter object will be instantiated and called as such: 33 | * HitCounter obj = new HitCounter(); 34 | * obj.hit(timestamp); 35 | * int param_2 = obj.getHits(timestamp); 36 | */ -------------------------------------------------------------------------------- /Medium/384 Shuffle an Array.txt: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class Solution { 4 | int[] original; 5 | 6 | public Solution(int[] nums) { 7 | original = nums; 8 | } 9 | 10 | /** Resets the array to its original configuration and return it. */ 11 | public int[] reset() { 12 | return original; 13 | } 14 | 15 | /** Returns a random shuffling of the array. */ 16 | public int[] shuffle() { 17 | 18 | int length = original.length; 19 | int[] shuffled = new int[length]; 20 | for (int i = 0; i < length; i++) { 21 | shuffled[i] = original[i]; 22 | } 23 | Random random = new Random(); 24 | for (int i = length; i > 0; i--) { 25 | int j = random.nextInt(i); 26 | swap(shuffled, i - 1, j); 27 | } 28 | return shuffled; 29 | } 30 | 31 | private void swap(int[] nums, int i, int j) { 32 | int temp = nums[j]; 33 | nums[j] = nums[i]; 34 | nums[i] = temp; 35 | } 36 | } 37 | 38 | /** 39 | * Your Solution object will be instantiated and called as such: 40 | * Solution obj = new Solution(nums); 41 | * int[] param_1 = obj.reset(); 42 | * int[] param_2 = obj.shuffle(); 43 | */ -------------------------------------------------------------------------------- /Medium/388 Longest Absolute File Path.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthLongestPath(String s) { 3 | if (s == null || s.length() == 0) { 4 | return 0; 5 | } 6 | String[] files = s.split("\n"); 7 | int maxLen = 0; 8 | int pathLen = 0; 9 | Stack dirLen = new Stack<>(); 10 | for (int i = 0; i < files.length; i++) { 11 | String curLine = files[i]; 12 | int curLvl = findLvl(curLine); 13 | int lvDiff = dirLen.size() - curLvl; 14 | while (lvDiff > 0) { 15 | pathLen -= dirLen.pop(); 16 | lvDiff -= 1; 17 | } 18 | int dotPos = curLine.indexOf('.'); 19 | if (dotPos > -1) { 20 | maxLen = Math.max(maxLen, pathLen + curLine.length() - curLvl); 21 | } else { 22 | pathLen += curLine.length() - curLvl + 1; 23 | dirLen.push(curLine.length() - curLvl + 1); 24 | } 25 | } 26 | return maxLen; 27 | } 28 | 29 | private int findLvl(String s) { 30 | int count = 0; 31 | while (s.charAt(count) == '\t') { 32 | count += 1; 33 | } 34 | return count; 35 | } 36 | } -------------------------------------------------------------------------------- /Medium/250 Count Univalue Subtrees.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int countUnivalSubtrees(TreeNode root) { 12 | int[] res = search(root); 13 | return res[2]; 14 | } 15 | 16 | private int[] search(TreeNode node) { 17 | // res[0] : null is 0, uni is 1, not uni is 2 18 | // res[1] : node.val 19 | // res[2] : how many uni subtrees of the node 20 | int[] res = new int[3]; 21 | if (node == null) { 22 | return res; 23 | } 24 | int[] left = search(node.left); 25 | int[] right = search(node.right); 26 | res[0] = 1; 27 | res[1] = node.val; 28 | if ((left[0] == 2 || right[0] == 2) 29 | || (left[0] == 1 && left[1] != res[1]) 30 | || (right[0] == 1 && right[1] != res[1]) 31 | || (left[0] == 1 && right[0] == 1 && left[1] != right[1])) { 32 | res[0] = 2; 33 | } 34 | res[2] = left[2] + right[2]; 35 | if (res[0] == 1) { 36 | res[2] += 1; 37 | } 38 | return res; 39 | } 40 | } -------------------------------------------------------------------------------- /Medium/393 UTF-8 Validation.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | int[] mask = {0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8}; 3 | 4 | public boolean validUtf8(int[] data) { 5 | if (data == null) { 6 | return true; 7 | } 8 | 9 | int counter = 0; 10 | boolean noError = true; 11 | 12 | for (int i = 0; i < data.length && noError; i++) { 13 | int numOfByte = findNumOfByte(data[i]); 14 | if (numOfByte > 4) { 15 | noError = false; 16 | } 17 | 18 | if ((counter > 0 && numOfByte != 1) 19 | || (counter == 0 && numOfByte == 1)) { 20 | noError = false; 21 | } else { 22 | if (counter > 0) { 23 | counter -= 1; 24 | } else { 25 | counter = (numOfByte > 0) ? numOfByte - 1 : 0; 26 | } 27 | } 28 | } 29 | 30 | return (noError && counter == 0); 31 | } 32 | 33 | private int findNumOfByte(int num) { 34 | for (int i = 0; i < mask.length; i++) { 35 | if ((mask[i] & num) != mask[i]) { 36 | return i - 1; 37 | } 38 | } 39 | return 5; 40 | } 41 | } -------------------------------------------------------------------------------- /Medium/086 Partition List.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode partition(ListNode head, int x) { 11 | ListNode cur = head; 12 | ListNode left = null; 13 | ListNode rightHead = null; 14 | ListNode right = null; 15 | while (cur != null) { 16 | ListNode next = cur.next; 17 | if (cur.val < x) { 18 | if (left == null) { 19 | head = cur; 20 | left = cur; 21 | } else { 22 | left.next = cur; 23 | left = cur; 24 | } 25 | } else { 26 | if (right == null) { 27 | right = cur; 28 | rightHead = cur; 29 | } else { 30 | right.next = cur; 31 | right = cur; 32 | } 33 | } 34 | cur.next = null; 35 | cur = next; 36 | } 37 | if (left == null) { 38 | return rightHead; 39 | } 40 | left.next = rightHead; 41 | return head; 42 | } 43 | } -------------------------------------------------------------------------------- /Medium/034 Search for a Range.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | int[] result = {-1, -1}; 4 | if (nums == null || nums.length == 0) { 5 | return result; 6 | } 7 | int start = 0; 8 | int end = nums.length - 1; 9 | result[0] = findLeft(nums, 0, end, target); 10 | if (result[0] != -1) { 11 | result[1] = findRight(nums, result[0], end, target); 12 | } 13 | return result; 14 | } 15 | 16 | private int findLeft(int[] nums, int start, int end, int target) { 17 | while (start != end) { 18 | int mid = (end - start) / 2 + start; 19 | if (nums[mid] >= target) { 20 | end = mid; 21 | } else { 22 | start = mid + 1; 23 | } 24 | } 25 | return (nums[start] == target) ? start : -1; 26 | } 27 | 28 | private int findRight(int[] nums, int start, int end, int target) { 29 | while (start != end) { 30 | int mid = (end - start) / 2 + start + 1; 31 | if (nums[mid] == target) { 32 | start = mid; 33 | } else { 34 | end = mid - 1; 35 | } 36 | } 37 | return start; 38 | } 39 | } -------------------------------------------------------------------------------- /Hard/287 Find the Duplicate Number.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findDuplicate(int[] nums) { 3 | int start = 1; 4 | int end = nums.length - 1; 5 | while (start < end) { 6 | int mid = (start + end) / 2; 7 | if (iteration(start, mid, nums)) { 8 | end = mid; 9 | } else { 10 | start = mid + 1; 11 | } 12 | } 13 | return start; 14 | } 15 | 16 | private boolean iteration(int start, int end, int[] nums) { 17 | int count = 0; 18 | for (int i : nums) { 19 | if ((i <= end) && (i >= start)) { 20 | count += 1; 21 | if (count > end - start + 1) { 22 | return true; 23 | } 24 | } 25 | } 26 | return false; 27 | } 28 | } 29 | 30 | public class Solution { 31 | public int findDuplicate(int[] nums) { 32 | int slow = nums[0]; 33 | int fast = nums[nums[0]]; 34 | while (slow != fast) { 35 | slow = nums[slow]; 36 | fast = nums[nums[fast]]; 37 | } 38 | fast = 0; 39 | while (slow != fast) { 40 | slow = nums[slow]; 41 | fast = nums[fast]; 42 | } 43 | return slow; 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Medium/074 Search a 2D Matrix.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | if (matrix == null || matrix.length < 1) { 4 | return false; 5 | } 6 | int row = searchRow(matrix, target, 0, matrix.length - 1); 7 | return searchCol(matrix[row], target, 0, matrix[row].length - 1); 8 | } 9 | 10 | private int searchRow(int[][] matrix, int target, int start, int end) { 11 | while (start < end) { 12 | int mid = (end - start) / 2 + start; 13 | if (matrix[mid][0] <= target && matrix[mid][matrix[0].length - 1] >= target) { 14 | return mid; 15 | } else if (matrix[mid][0] > target) { 16 | end = mid; 17 | } else { 18 | start = mid + 1; 19 | } 20 | } 21 | return start; 22 | } 23 | 24 | private boolean searchCol(int[] row, int target, int start, int end) { 25 | while (start < end) { 26 | int mid = (end - start) / 2 + start; 27 | if (row[mid] == target) { 28 | return true; 29 | } else if (row[mid] > target) { 30 | end = mid; 31 | } else { 32 | start = mid + 1; 33 | } 34 | } 35 | return row[start] == target; 36 | } 37 | } -------------------------------------------------------------------------------- /Medium/309 Best Time to Buy and Sell Stock with Cooldown.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | if (prices == null || prices.length == 0) { 4 | return 0; 5 | } 6 | int[] profits = new int[prices.length]; 7 | profits[0] = 0; 8 | int tempMax = 0; 9 | for (int i = 1; i < prices.length; i++) { 10 | tempMax = Math.max(tempMax, prices[i] - Math.min(prices[0], prices[1])); 11 | for (int j = i - 1; j > 1; j--) { 12 | tempMax = Math.max(tempMax, profits[j - 2] + prices[i] - prices[j]); 13 | } 14 | profits[i] = tempMax; 15 | } 16 | return tempMax; 17 | } 18 | } 19 | 20 | public class Solution { 21 | public int maxProfit(int[] prices) { 22 | if (prices == null || prices.length == 0) { 23 | return 0; 24 | } 25 | int[] hold = new int[prices.length + 1]; 26 | int[] sold = new int[prices.length + 1]; 27 | hold[0] = 0; 28 | sold[0] = 0; 29 | hold[1] = - prices[0]; 30 | sold[1] = 0; 31 | for (int i = 2; i <= prices.length; i++) { 32 | hold[i] = Math.max(sold[i - 2] - prices[i - 1], hold[i - 1]); 33 | sold[i] = Math.max(sold[i - 1], hold[i - 1] + prices[i - 1]); 34 | } 35 | return sold[prices.length]; 36 | } 37 | } -------------------------------------------------------------------------------- /Medium/333 Largest BST Subtree.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int largestBSTSubtree(TreeNode root) { 12 | return search(root)[0]; 13 | } 14 | 15 | private int[] search(TreeNode node) { 16 | // result[0]: size; result[1]: 0(BST), 1(not BST) 17 | // result[2]: lower bound; result[3]: upper bound 18 | int[] result = new int[4]; 19 | if (node == null) { 20 | return result; 21 | } 22 | 23 | int[] left = search(node.left); 24 | if (node.left == null) { 25 | left[2] = node.val; 26 | left[3] = node.val - 1; 27 | } 28 | int[] right = search(node.right); 29 | if (node.right == null) { 30 | right[2] = node.val + 1; 31 | right[3] = node.val; 32 | } 33 | if (left[1] == 0 && right[1] == 0 && left[3] < node.val && node.val < right[2]) { 34 | result[0] = left[0] + right[0] + 1; 35 | result[2] = left[2]; 36 | result[3] = right[3]; 37 | return result; 38 | } 39 | result[0] = Math.max(left[0], right[0]); 40 | result[1] = 1; 41 | return result; 42 | } 43 | } -------------------------------------------------------------------------------- /Medium/289 Game of Life.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void gameOfLife(int[][] board) { 3 | int[][] directions = {{1, 1}, {1, 0}, {1, -1}, {0, 1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; 4 | int m = board.length; 5 | int n = board[0].length; 6 | for (int i = 0; i < board.length; i++) { 7 | for (int j = 0; j < board[0].length; j++) { 8 | calculate(board, i, j, directions, m, n); 9 | } 10 | } 11 | for (int i = 0; i < board.length; i++) { 12 | for (int j = 0; j < board[0].length; j++) { 13 | update(board, i, j); 14 | } 15 | } 16 | } 17 | 18 | private void calculate(int[][] board, int i, int j, 19 | int[][] directions, int m, int n) { 20 | int count = 0; 21 | for (int[] dir : directions) { 22 | int x = i + dir[0]; 23 | int y = j + dir[1]; 24 | if (x >= 0 && x < m && y >= 0 && y < n) { 25 | if (board[x][y] % 10 == 1) { 26 | count += 1; 27 | } 28 | } 29 | } 30 | if ((board[i][j] == 1 && (count == 2 || count == 3)) 31 | || (board[i][j] == 0 && count == 3)) { 32 | board[i][j] += 10; 33 | } 34 | } 35 | 36 | private void update(int[][] board, int i, int j) { 37 | board[i][j] /= 10; 38 | } 39 | } -------------------------------------------------------------------------------- /Medium/294 Flip Game II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean canWin(String s) { 3 | 4 | // split the strings 5 | String[] ss = s.split("--*"); 6 | 7 | // abstract the length of substrings and find the maxLen 8 | int maxLen = 0; 9 | for (int i = 0; i < ss.length; i++) { 10 | if (maxLen < ss[i].length()) { 11 | maxLen = ss[i].length(); 12 | } 13 | } 14 | 15 | // GS number: 0 -> lose; win otherwise 16 | List gs = new ArrayList<>(); 17 | gs.add(0); // len = 0 18 | gs.add(0); // len = 1 19 | gs.add(1); // len = 2 20 | 21 | // update GS number 22 | for (int i = 3; i <= maxLen; i++) { 23 | buildGS(gs, i); 24 | } 25 | 26 | int result = 0; 27 | for (String cur : ss) { 28 | result ^= gs.get(cur.length()); 29 | } 30 | 31 | return result != 0; 32 | } 33 | 34 | private void buildGS(List gs, int len) { 35 | Set set = new HashSet<>(); 36 | for (int i = 0; i < len / 2; i++) { 37 | set.add(gs.get(i) ^ gs.get(len - i - 2)); 38 | } 39 | for (int i = 0; i < len; i++) { 40 | if (!set.contains(i)) { 41 | gs.add(i); 42 | return; 43 | } 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /Medium/105 Construct Binary Tree from Preorder and Inorder Traversal.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | int[] pre; 12 | int[] in; 13 | Map idxMap; 14 | 15 | public TreeNode buildTree(int[] preorder, int[] inorder) { 16 | pre = preorder; 17 | in = inorder; 18 | if (pre == null || pre == null) { 19 | return null; 20 | } 21 | // get the mapping relation of inorder[] 22 | idxMap = new HashMap<>(); 23 | int idx = 0; 24 | for (int i : in) { 25 | idxMap.put(i, idx); 26 | idx += 1; 27 | } 28 | return buildTree(0, pre.length - 1, 0, in.length - 1); 29 | } 30 | 31 | private TreeNode buildTree(int preStart, int preEnd, int inStart, int inEnd) { 32 | if (inStart > inEnd) { 33 | return null; 34 | } 35 | int target = pre[preStart]; 36 | int idx = idxMap.get(target); 37 | TreeNode parent = new TreeNode(target); 38 | parent.left = buildTree(preStart + 1, preStart + 1 + (idx - 1 - inStart), inStart, idx - 1); 39 | parent.right = buildTree(preEnd - (inEnd - idx - 1), preEnd, idx + 1, inEnd); 40 | return parent; 41 | } 42 | } -------------------------------------------------------------------------------- /Medium/348 Design Tic-Tac-Toe.txt: -------------------------------------------------------------------------------- 1 | public class TicTacToe { 2 | 3 | int[] count; 4 | int size = 0; 5 | 6 | /** Initialize your data structure here. */ 7 | public TicTacToe(int n) { 8 | count = new int[2 * n + 2]; 9 | size = n; 10 | } 11 | 12 | /** Player {player} makes a move at ({row}, {col}). 13 | @param row The row of the board. 14 | @param col The column of the board. 15 | @param player The player, can be either 1 or 2. 16 | @return The current winning condition, can be either: 17 | 0: No one wins. 18 | 1: Player 1 wins. 19 | 2: Player 2 wins. */ 20 | public int move(int row, int col, int player) { 21 | int sign = (player == 1) ? 1 : -1; 22 | count[row] += sign; 23 | count[size + col] += sign; 24 | if (row == col) { 25 | count[2 * size] += sign; 26 | } 27 | if (row + col == size - 1) { 28 | count[2 * size + 1] += sign; 29 | } 30 | if (Math.abs(count[row]) == size 31 | || Math.abs(count[size + col]) == size 32 | || Math.abs(count[2 * size]) == size 33 | || Math.abs(count[2 * size + 1]) == size) { 34 | return player; 35 | } 36 | return 0; 37 | } 38 | } 39 | 40 | /** 41 | * Your TicTacToe object will be instantiated and called as such: 42 | * TicTacToe obj = new TicTacToe(n); 43 | * int param_1 = obj.move(row,col,player); 44 | */ -------------------------------------------------------------------------------- /Medium/106 Construct Binary Tree from Inorder and Postorder Traversal.txt: -------------------------------------------------------------------------------- 1 | // Improved Solution: O(n) time complexity 5ms 2 | /** 3 | * Definition for a binary tree node. 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class Solution { 12 | int[] in; 13 | int[] post; 14 | Map idxMap; 15 | 16 | public TreeNode buildTree(int[] inorder, int[] postorder) { 17 | in = inorder; 18 | post = postorder; 19 | if (in == null || post == null) { 20 | return null; 21 | } 22 | // get the mapping relation of inorder[] 23 | idxMap = new HashMap<>(); 24 | int idx = 0; 25 | for (int i : in) { 26 | idxMap.put(i, idx); 27 | idx += 1; 28 | } 29 | return buildTree(0, in.length - 1, 0, post.length - 1); 30 | } 31 | 32 | private TreeNode buildTree(int inStart, int inEnd, int postStart, int postEnd) { 33 | if (inStart > inEnd) { 34 | return null; 35 | } 36 | int target = post[postEnd]; 37 | int idx = idxMap.get(target); 38 | TreeNode parent = new TreeNode(target); 39 | parent.left = buildTree(inStart, idx - 1, postStart, postStart + (idx - 1 - inStart)); 40 | parent.right = buildTree(idx + 1, inEnd, postEnd - 1 - (inEnd - idx - 1), postEnd - 1); 41 | return parent; 42 | } 43 | } -------------------------------------------------------------------------------- /Medium/373 Find K Pairs with Smallest Sums.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List kSmallestPairs(int[] nums1, int[] nums2, int k) { 3 | 4 | List list = new ArrayList<>(); 5 | if (nums1 == null || nums1.length == 0 6 | ||nums2 == null || nums2.length == 0) { 7 | return list; 8 | } 9 | 10 | PriorityQueue pq = new PriorityQueue<>(new Comparator() { 11 | public int compare(int[] pair1, int[] pair2) { 12 | return nums1[pair1[0]] + nums2[pair1[1]] 13 | - nums1[pair2[0]] - nums2[pair2[1]]; 14 | } 15 | }); 16 | 17 | int[] temp = new int[2]; 18 | pq.add(temp); 19 | int count = 0; 20 | 21 | while (k > 0 && !pq.isEmpty()) { 22 | temp = pq.poll(); 23 | int[] res = new int[2]; 24 | int i1 = temp[0]; 25 | int i2 = temp[1]; 26 | res[0] = nums1[i1]; 27 | res[1] = nums2[i2]; 28 | list.add(res); 29 | if (i1 + 1 < nums1.length) { 30 | temp[0] = i1 + 1; 31 | pq.add(temp); 32 | } 33 | if (i1 == 0 && i2 == count && count + 1 < nums2.length) { 34 | count += 1; 35 | int[] newArray = new int[2]; 36 | newArray[1] = count; 37 | pq.add(newArray); 38 | } 39 | k -= 1; 40 | } 41 | return list; 42 | } 43 | } -------------------------------------------------------------------------------- /Medium/092 Reverse Linked List II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode reverseBetween(ListNode head, int m, int n) { 11 | // add a dummy head before head to deal with edge cases 12 | ListNode dummyHead = new ListNode(0); 13 | dummyHead.next = head; 14 | 15 | // iterate the list until the mth element 16 | ListNode curNode = head; 17 | ListNode prevNode = dummyHead; 18 | int count = 1; 19 | while (count < m) { 20 | prevNode = curNode; 21 | curNode = curNode.next; 22 | count += 1; 23 | } 24 | 25 | /** 26 | * initate some pointers to locate node 27 | * mNode is the mth node after reversion 28 | * nNode is the nth node after reversion 29 | */ 30 | ListNode mNode = curNode; 31 | ListNode nNode = curNode; 32 | curNode = curNode.next; 33 | count += 1; 34 | 35 | // reassign the nodes 36 | while (count <= n) { 37 | nNode.next = curNode.next; 38 | curNode.next = mNode; 39 | mNode = curNode; 40 | curNode = nNode.next; 41 | count += 1; 42 | } 43 | 44 | // last modification and return 45 | prevNode.next = mNode; 46 | return dummyHead.next; 47 | } 48 | } -------------------------------------------------------------------------------- /Medium/241 Different Ways to Add Parentheses.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List diffWaysToCompute(String input) { 3 | HashMap> map = new HashMap<>(); 4 | return dp(input, map); 5 | } 6 | 7 | private List dp(String s, HashMap> map) { 8 | List result = new ArrayList(); 9 | for (int i = 0; i < s.length(); i++) { 10 | char c = s.charAt(i); 11 | if (c == '+' || c == '-' || c == '*') { 12 | String l = s.substring(0, i); 13 | String r = s.substring(i + 1); 14 | 15 | List left = map.containsKey(l) ? map.get(l) : dp(l, map); 16 | List right = map.containsKey(r) ? map.get(r) : dp(r, map); 17 | 18 | for (int numl : left) { 19 | for (int numr : right) { 20 | if (c == '+') { 21 | result.add(numl + numr); 22 | } else if (c == '-') { 23 | result.add(numl - numr); 24 | } else if (c == '*') { 25 | result.add(numl * numr); 26 | } 27 | } 28 | } 29 | } 30 | } 31 | if (result.size() == 0) { //when there is only an integer 32 | result.add(Integer.parseInt(s)); 33 | } 34 | map.put(s, result); 35 | return result; 36 | } 37 | } -------------------------------------------------------------------------------- /Medium/360 Sort Transformed Array.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] sortTransformedArray(int[] nums, int a, int b, int c) { 3 | int[] result = new int[nums.length]; 4 | double pivot = (a != 0) ? (- b + 0.0) / (2 * a) : nums[0]; 5 | boolean isLargest = a < 0 || (a == 0 && b < 0); 6 | int right = 0; 7 | double diff = Integer.MAX_VALUE; 8 | for (int i = 0; i < nums.length; i++) { 9 | if (diff > Math.abs(nums[i] - pivot)) { 10 | diff = Math.abs(nums[i] - pivot); 11 | right = i; 12 | } 13 | } 14 | int left = right - 1; 15 | int i = 0; 16 | while (right < nums.length && left >= 0) { 17 | int j = isLargest ? (nums.length - 1 - i) : i; 18 | if (Math.abs(nums[left] - pivot) < Math.abs(nums[right] - pivot)) { 19 | result[j] = calculate(nums[left], a, b, c); 20 | left -= 1; 21 | } else { 22 | result[j] = calculate(nums[right], a, b, c); 23 | right += 1; 24 | } 25 | i += 1; 26 | } 27 | while (i < nums.length) { 28 | int j = isLargest ? (nums.length - 1 - i) : i; 29 | result[j] = (left < 0) ? calculate(nums[right], a, b, c) : calculate(nums[left], a, b, c); 30 | left -= 1; 31 | right += 1; 32 | i += 1; 33 | } 34 | return result; 35 | } 36 | 37 | private int calculate(int n, int a, int b, int c) { 38 | return a * n * n + b * n + c; 39 | } 40 | } -------------------------------------------------------------------------------- /Hard/291 Word Pattern II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean wordPatternMatch(String pattern, String str) { 3 | HashMap map = new HashMap<>(); 4 | Set stringSet = new HashSet<>(); 5 | return search(map, stringSet, str, pattern, 0); 6 | } 7 | 8 | private boolean search(HashMap map, Set stringSet, 9 | String str, String pattern, int i) { 10 | if (i == pattern.length()) { 11 | if (str.length() == 0) { 12 | return true; 13 | } 14 | return false; 15 | } 16 | Character c = pattern.charAt(i); 17 | String value = map.get(c); 18 | if (value != null) { 19 | int len = value.length(); 20 | if (str.length() < len || !str.substring(0, len).equals(value)) { 21 | return false; 22 | } else { 23 | return search(map, stringSet, str.substring(len), pattern, i + 1); 24 | } 25 | } else { 26 | for (int j = 1; pattern.length() - i - 2 < str.length() - j; j++) { 27 | String s = str.substring(0, j); 28 | if (!stringSet.contains(s)) { 29 | map.put(c, s); 30 | stringSet.add(s); 31 | if (search(map, stringSet, str.substring(j), pattern, i + 1)) { 32 | return true; 33 | } 34 | map.remove(c); 35 | stringSet.remove(s); 36 | } 37 | } 38 | } 39 | return false; 40 | } 41 | } -------------------------------------------------------------------------------- /Medium/314 Binary Tree Vertical Order Traversal.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List> verticalOrder(TreeNode root) { 12 | List> res = new ArrayList<>(); 13 | if (root == null) { 14 | return res; 15 | } 16 | 17 | int min = 0; 18 | int max = 0; 19 | LinkedList nodes = new LinkedList<>(); 20 | LinkedList orders = new LinkedList<>(); 21 | HashMap> map = new HashMap<>(); 22 | nodes.add(root); 23 | orders.add(0); 24 | while (!nodes.isEmpty()) { 25 | TreeNode curNode = nodes.poll(); 26 | Integer order = orders.poll(); 27 | map.putIfAbsent(order, new ArrayList()); 28 | map.get(order).add(curNode.val); 29 | TreeNode left = curNode.left; 30 | if (left != null) { 31 | nodes.add(left); 32 | orders.add(order - 1); 33 | min = Math.min(min, order - 1); 34 | } 35 | TreeNode right = curNode.right; 36 | if (right != null) { 37 | nodes.add(right); 38 | orders.add(order + 1); 39 | max = Math.max(max, order + 1); 40 | } 41 | } 42 | for (int i = min; i <= max; i++) { 43 | res.add(map.get(i)); 44 | } 45 | return res; 46 | } 47 | } -------------------------------------------------------------------------------- /Medium/103 Binary Tree Zigzag Level Order Traversal.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List> zigzagLevelOrder(TreeNode root) { 12 | List> res = new ArrayList<>(); 13 | Stack level = new Stack<>(); 14 | boolean fromLeft = true; 15 | 16 | if (root != null) { 17 | level.push(root); 18 | } 19 | 20 | while (!level.isEmpty()) { 21 | Stack temp = new Stack<>(); 22 | List list = new ArrayList<>(); 23 | while (!level.isEmpty()) { 24 | TreeNode node = level.pop(); 25 | list.add(node.val); 26 | if (fromLeft) { 27 | if (node.left != null) { 28 | temp.push(node.left); 29 | } 30 | if (node.right != null) { 31 | temp.push(node.right); 32 | } 33 | } else { 34 | if (node.right != null) { 35 | temp.push(node.right); 36 | } 37 | if (node.left != null) { 38 | temp.push(node.left); 39 | } 40 | } 41 | } 42 | res.add(list); 43 | level = temp; 44 | fromLeft = !fromLeft; 45 | } 46 | 47 | return res; 48 | } 49 | } -------------------------------------------------------------------------------- /Hard/273 Integer to English Words.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String numberToWords(int num) { 3 | if (num == 0) { 4 | return "Zero"; 5 | } 6 | String[] one2nine = {"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "}; 7 | String[] teens = {"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "}; 8 | String[] tys = {"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "}; 9 | String hundred = "Hundred "; 10 | String[] units = {"", "Thousand ", "Million ", "Billion "}; 11 | String res = ""; 12 | int unitIdx = 0; 13 | while (num > 0) { 14 | int r = num % 1000; 15 | String temp = ""; 16 | if (r / 100 > 0) { 17 | temp = one2nine[r / 100] + hundred; 18 | } 19 | r = r % 100; 20 | if (r / 10 > 1) { 21 | temp += tys[r / 10 - 2]; 22 | temp += one2nine[r % 10]; 23 | } else { 24 | if (r > 9) { 25 | temp += teens[r - 10]; 26 | } else { 27 | temp += one2nine[r]; 28 | } 29 | } 30 | if (!temp.equals("")) { 31 | temp += units[unitIdx]; 32 | } 33 | res = temp + res; 34 | num = num / 1000; 35 | unitIdx += 1; 36 | } 37 | while (res.charAt(res.length() - 1) == ' ') { 38 | res = res.substring(0, res.length() - 1); 39 | } 40 | return res; 41 | } 42 | } -------------------------------------------------------------------------------- /Hard/380 Insert Delete GetRandom O(1).txt: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomizedSet { 4 | HashMap map; 5 | List nums; 6 | 7 | /** Initialize your data structure here. */ 8 | public RandomizedSet() { 9 | map = new HashMap<>(); 10 | nums = new ArrayList<>(); 11 | } 12 | 13 | /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ 14 | public boolean insert(int val) { 15 | if (map.containsKey(val)) { 16 | return false; 17 | } 18 | 19 | map.put(val, nums.size()); 20 | nums.add(val); 21 | return true; 22 | } 23 | 24 | /** Removes a value from the set. Returns true if the set contained the specified element. */ 25 | public boolean remove(int val) { 26 | if (map.isEmpty() || !map.containsKey(val)) { 27 | return false; 28 | } 29 | 30 | int idx = map.get(val); 31 | int lastNum = nums.get(nums.size() - 1); 32 | nums.set(idx, lastNum); 33 | map.put(lastNum, idx); 34 | map.remove(val); 35 | nums.remove(nums.size() - 1); 36 | return true; 37 | } 38 | 39 | /** Get a random element from the set. */ 40 | public int getRandom() { 41 | Random random = new Random(); 42 | return nums.get(random.nextInt(nums.size())); 43 | } 44 | } 45 | 46 | /** 47 | * Your RandomizedSet object will be instantiated and called as such: 48 | * RandomizedSet obj = new RandomizedSet(); 49 | * boolean param_1 = obj.insert(val); 50 | * boolean param_2 = obj.remove(val); 51 | * int param_3 = obj.getRandom(); 52 | */ -------------------------------------------------------------------------------- /Medium/379 Design Phone Directory.txt: -------------------------------------------------------------------------------- 1 | public class PhoneDirectory { 2 | int max; 3 | int cur; 4 | Stack released; 5 | boolean[] isUsed; 6 | 7 | /** Initialize your data structure here 8 | @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ 9 | public PhoneDirectory(int maxNumbers) { 10 | max = maxNumbers; 11 | released = new Stack<>(); 12 | isUsed = new boolean[max]; 13 | cur = 0; 14 | } 15 | 16 | /** Provide a number which is not assigned to anyone. 17 | @return - Return an available number. Return -1 if none is available. */ 18 | public int get() { 19 | if (!released.isEmpty()) { 20 | int num = released.pop(); 21 | isUsed[num] = true; 22 | return num; 23 | } else { 24 | if (cur < max) { 25 | isUsed[cur] = true; 26 | cur += 1; 27 | return cur - 1; 28 | } else { 29 | return -1; 30 | } 31 | } 32 | } 33 | 34 | /** Check if a number is available or not. */ 35 | public boolean check(int number) { 36 | return !isUsed[number]; 37 | } 38 | 39 | /** Recycle or release a number. */ 40 | public void release(int number) { 41 | if (isUsed[number]) { 42 | released.push(number); 43 | } 44 | isUsed[number] = false; 45 | } 46 | } 47 | 48 | /** 49 | * Your PhoneDirectory object will be instantiated and called as such: 50 | * PhoneDirectory obj = new PhoneDirectory(maxNumbers); 51 | * int param_1 = obj.get(); 52 | * boolean param_2 = obj.check(number); 53 | * obj.release(number); 54 | */ -------------------------------------------------------------------------------- /Medium/313 Super Ugly Number.txt: -------------------------------------------------------------------------------- 1 | // V1. O(nk) space, O(nk*log(nk)) time 2 | 3 | public class Solution { 4 | public int nthSuperUglyNumber(int n, int[] primes) { 5 | if (n == 1) { 6 | return 1; 7 | } 8 | PriorityQueue pq = new PriorityQueue<>(); 9 | pq.add(1); 10 | for (int prime : primes) { 11 | pq.add(prime); 12 | } 13 | int prev = 0; 14 | while (n > 0) { 15 | int cur = pq.poll(); 16 | if (cur != prev) { 17 | prev = cur; 18 | n -= 1; 19 | for (int prime : primes) { 20 | if (((long) prev) * prime < Integer.MAX_VALUE) { 21 | pq.add(prev * prime); 22 | } 23 | } 24 | } 25 | } 26 | return prev; 27 | } 28 | } 29 | 30 | // V3.5. O(n) space, O(n*log(k)) time 31 | 32 | public class Solution { 33 | public int nthSuperUglyNumber(int n, int[] primes) { 34 | int[] res = new int[n]; 35 | res[0] = 1; 36 | PriorityQueue pq = new PriorityQueue<>(new Comparator() { 37 | public int compare(int[] a, int[] b) { 38 | return a[0] - b[0]; 39 | } 40 | }); 41 | for (int prime : primes) { 42 | int[] temp = {prime, 0}; 43 | pq.add(temp); 44 | } 45 | for (int i = 1; i < n; i++) { 46 | int[] cur = pq.poll(); 47 | int prime = cur[0] / res[cur[1]]; 48 | if (cur[0] > res[i - 1]) { 49 | res[i] = cur[0]; 50 | } else { 51 | i -= 1; 52 | } 53 | cur[1] += 1; 54 | cur[0] = res[cur[1]] * prime; 55 | pq.add(cur); 56 | } 57 | return res[n - 1]; 58 | } 59 | } -------------------------------------------------------------------------------- /Medium/347 Top K Frequent Elements.txt: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | public List topKFrequent(int[] nums, int k) { 5 | // count the number frequency 6 | Map map = new HashMap<>(); 7 | for (int i = 0; i < nums.length; i++) { 8 | map.putIfAbsent(nums[i], 0); 9 | map.put(nums[i], map.get(nums[i]) + 1); 10 | } 11 | // move the map entry to a list 12 | List> list = new ArrayList<>(); 13 | for (Map.Entry entry : map.entrySet()) { 14 | list.add(entry); 15 | } 16 | // quicksort (k th select sort) 17 | quicksort(list, k, 0, list.size() - 1); 18 | List result = new ArrayList<>(); 19 | for (int i = 0; i < k; i++) { 20 | result.add(list.get(i).getKey()); 21 | } 22 | return result; 23 | } 24 | 25 | // quicksort kth select 26 | private void quicksort(List> list, int k, int start, int end) { 27 | int pivot = list.get(start).getValue(); 28 | int pointer = start + 1; 29 | for (int i = start + 1; i <= end; i++) { 30 | if (list.get(i).getValue() > pivot) { 31 | Map.Entry temp = list.get(i); 32 | list.set(i, list.get(pointer)); 33 | list.set(pointer, temp); 34 | pointer += 1; 35 | } 36 | } 37 | Map.Entry temp = list.get(pointer - 1); 38 | list.set(pointer - 1, list.get(start)); 39 | list.set(start, temp); 40 | 41 | if (pointer == k) { 42 | return; 43 | } else if (pointer > k) { 44 | end = pointer; 45 | } else { 46 | start = pointer; 47 | } 48 | quicksort(list, k, start, end); 49 | } 50 | } -------------------------------------------------------------------------------- /Medium/361 Bomb Enemy.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxKilledEnemies(char[][] grid) { 3 | if (grid == null || grid.length == 0) { 4 | return 0; 5 | } 6 | 7 | int[][] enemyCount = new int[grid.length][2]; 8 | for (int i = 0; i < enemyCount.length; i++) { 9 | enemyCount[i][0] = -1; 10 | } 11 | 12 | int max = 0; 13 | for (int j = 0; j < grid[0].length; j++) { 14 | int colEnemy = countColEnemy(grid, j, 0); 15 | for (int i = 0; i < grid.length; i++) { 16 | if (grid[i][j] == '0') { 17 | if (j > enemyCount[i][0]) { 18 | update(enemyCount, grid, i, j); 19 | } 20 | max = Math.max(colEnemy + enemyCount[i][1], max); 21 | } 22 | if (grid[i][j] == 'W') { 23 | colEnemy = countColEnemy(grid, j, i + 1); 24 | } 25 | } 26 | } 27 | return max; 28 | } 29 | 30 | private void update(int[][] enemyCount, char[][] grid, int i, int j) { 31 | int count = 0; 32 | int k = enemyCount[i][0] + 1; 33 | while (k < grid[0].length && (grid[i][k] != 'W' || k < j)) { 34 | if (grid[i][k] == 'E') { 35 | count += 1; 36 | } 37 | if (grid[i][k] == 'W') { 38 | count = 0; 39 | } 40 | k += 1; 41 | } 42 | enemyCount[i][0] = k; 43 | enemyCount[i][1] = count; 44 | } 45 | 46 | private int countColEnemy(char[][] grid, int j, int start) { 47 | int count = 0; 48 | int i = start; 49 | while (i < grid.length && grid[i][j] != 'W') { 50 | if (grid[i][j] == 'E') { 51 | count += 1; 52 | } 53 | i += 1; 54 | } 55 | return count; 56 | } 57 | } -------------------------------------------------------------------------------- /Medium/286 Walls and Gates.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void wallsAndGates(int[][] rooms) { 3 | int INF = 2147483647; 4 | int x = rooms.length; 5 | if (x == 0) { 6 | return; 7 | } 8 | int y = rooms[0].length; 9 | List rows = new ArrayList<>(); 10 | List cols = new ArrayList<>(); 11 | for (int i = 0; i < x; i++) { 12 | for (int j = 0; j < y; j++) { 13 | if (rooms[i][j] == 0) { 14 | rows.add(i); 15 | cols.add(j); 16 | } 17 | } 18 | } 19 | int dis = 1; 20 | while (!rows.isEmpty()) { 21 | List tempRows = new ArrayList<>(); 22 | List tempCols = new ArrayList<>(); 23 | for (int k = 0; k < rows.size(); k++) { 24 | int i = rows.get(k); 25 | int j = cols.get(k); 26 | if (i > 0 && rooms[i - 1][j] == INF) { 27 | rooms[i - 1][j] = dis; 28 | tempRows.add(i - 1); 29 | tempCols.add(j); 30 | } 31 | if (i < x - 1 && rooms[i + 1][j] == INF) { 32 | rooms[i + 1][j] = dis; 33 | tempRows.add(i + 1); 34 | tempCols.add(j); 35 | } 36 | if (j > 0 && rooms[i][j - 1] == INF) { 37 | rooms[i][j - 1] = dis; 38 | tempRows.add(i); 39 | tempCols.add(j - 1); 40 | } 41 | if (j < y - 1 && rooms[i][j + 1] == INF) { 42 | rooms[i][j + 1] = dis; 43 | tempRows.add(i); 44 | tempCols.add(j + 1); 45 | } 46 | } 47 | rows = tempRows; 48 | cols = tempCols; 49 | dis += 1; 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Hard/329 Longest Increasing Path in a Matrix.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestIncreasingPath(int[][] matrix) { 3 | if (matrix == null || matrix.length == 0) { 4 | return 0; 5 | } 6 | int m = matrix.length; 7 | int n = matrix[0].length; 8 | int[][] pathLen = new int[m][n]; 9 | int max = 0; 10 | for (int i = 0; i < m; i++) { 11 | for (int j = 0; j < n; j++) { 12 | if (pathLen[i][j] == 0) { 13 | search(matrix, i, j, pathLen); 14 | } 15 | max = Math.max(max, pathLen[i][j]); 16 | } 17 | } 18 | return max; 19 | } 20 | 21 | private void search(int[][] matrix, int i, int j, int[][] pathLen) { 22 | int cur = matrix[i][j]; 23 | if (i > 0 && matrix[i - 1][j] > cur) { 24 | if (pathLen[i - 1][j] == 0) { 25 | search(matrix, i - 1, j, pathLen); 26 | } 27 | pathLen[i][j] = Math.max(pathLen[i][j], pathLen[i - 1][j] + 1); 28 | } 29 | if (i < matrix.length - 1 && matrix[i + 1][j] > cur) { 30 | if (pathLen[i + 1][j] == 0) { 31 | search(matrix, i + 1, j, pathLen); 32 | } 33 | pathLen[i][j] = Math.max(pathLen[i][j], pathLen[i + 1][j] + 1); 34 | } 35 | if (j > 0 && matrix[i][j - 1] > cur) { 36 | if (pathLen[i][j - 1] == 0) { 37 | search(matrix, i, j - 1, pathLen); 38 | } 39 | pathLen[i][j] = Math.max(pathLen[i][j], pathLen[i][j - 1] + 1); 40 | } 41 | if (j < matrix[0].length - 1 && matrix[i][j + 1] > cur) { 42 | if (pathLen[i][j + 1] == 0) { 43 | search(matrix, i, j + 1, pathLen); 44 | } 45 | pathLen[i][j] = Math.max(pathLen[i][j], pathLen[i][j + 1] + 1); 46 | } 47 | pathLen[i][j] = Math.max(pathLen[i][j], 1); 48 | } 49 | } -------------------------------------------------------------------------------- /Hard/146 LRU Cache.txt: -------------------------------------------------------------------------------- 1 | public class LRUCache { 2 | Node head = null; 3 | Node tail = null; 4 | int size = 0; 5 | int capacity; 6 | Map map; 7 | 8 | public LRUCache(int capacity) { 9 | this.capacity = capacity; 10 | map = new HashMap(); 11 | } 12 | 13 | public int get(int key) { 14 | Node n = map.get(key); 15 | if (n != null) { 16 | if (n != head) { 17 | remove(n); 18 | pushToFront(n); 19 | } 20 | return n.value; 21 | } 22 | return -1; 23 | } 24 | 25 | public void set(int key, int value) { 26 | Node newNode = new Node(key, value); 27 | if (map.get(key) == null) { 28 | if (size == capacity) { 29 | map.remove(tail.key); 30 | remove(tail); 31 | } 32 | } else { 33 | remove(map.get(key)); 34 | } 35 | map.put(key, newNode); 36 | pushToFront(newNode); 37 | } 38 | 39 | private void remove(Node n) { 40 | if (n != head) { 41 | n.prev.next = n.next; 42 | } else { 43 | head = n.next; 44 | } 45 | if (n != tail) { 46 | n.next.prev = n.prev; 47 | } else { 48 | tail = n.prev; 49 | } 50 | size--; 51 | } 52 | 53 | private void pushToFront(Node n) { 54 | n.next = head; 55 | if (head != null) { 56 | head.prev = n; 57 | } 58 | if (tail == null) { 59 | tail = n; 60 | } 61 | head = n; 62 | size++; 63 | } 64 | 65 | private class Node { 66 | Node prev = null; 67 | Node next = null; 68 | int key; 69 | int value; 70 | 71 | public Node(int key, int value) { 72 | this.key = key; 73 | this.value = value; 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /Medium/421 Maximum XOR of Two Numbers in an Array.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int findMaximumXOR(int[] nums) { 3 | int result = 0; 4 | int max = 1; 5 | int count = 0; 6 | for (int num : nums) { 7 | while (max < num) { 8 | max = (max << 1) + 1; 9 | count += 1; 10 | } 11 | } 12 | Trie root = new Trie(); 13 | for (int num : nums) { 14 | int mask = 1 << count; 15 | Trie node1 = root; 16 | Trie node2 = root; 17 | int temp = 0; 18 | while (mask > 0) { 19 | if (node1.one == null) { 20 | node1.one = new Trie(); 21 | node1.zero = new Trie(); 22 | } 23 | if (node2.one == null) { 24 | node2.one = new Trie(); 25 | node2.zero = new Trie(); 26 | } 27 | if ((num & mask) > 0) { 28 | node1.one.val = true; 29 | node1 = node1.one; 30 | if (node2.zero.val) { 31 | node2 = node2.zero; 32 | temp += mask; 33 | } else { 34 | node2 = node2.one; 35 | } 36 | } else { 37 | node1.zero.val = true; 38 | node1 = node1.zero; 39 | if (node2.one.val) { 40 | node2 = node2.one; 41 | temp += mask; 42 | } else { 43 | node2 = node2.zero; 44 | } 45 | } 46 | mask = mask >> 1; 47 | } 48 | result = Math.max(result, temp); 49 | } 50 | return result; 51 | } 52 | 53 | class Trie { 54 | boolean val; 55 | Trie one, zero; 56 | } 57 | } -------------------------------------------------------------------------------- /Medium/156 Binary Tree Upside Down.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode upsideDownBinaryTree(TreeNode root) { 12 | if (root == null) { 13 | return null; 14 | } 15 | TreeNode cur = root; 16 | TreeNode prev = null; 17 | TreeNode right = null; 18 | while (cur != null) { 19 | TreeNode temp = cur.left; 20 | cur.left = right; 21 | right = cur.right; 22 | cur.right = prev; 23 | prev = cur; 24 | cur = temp; 25 | } 26 | return prev; 27 | } 28 | } 29 | 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 | public class Solution { 40 | public TreeNode upsideDownBinaryTree(TreeNode root) { 41 | if (root == null) { 42 | return null; 43 | } 44 | Stack stack = new Stack<>(); 45 | TreeNode cur = root; 46 | while (cur != null) { 47 | stack.push(cur); 48 | stack.push(cur.right); 49 | cur = cur.left; 50 | } 51 | stack.pop(); 52 | TreeNode newHead = stack.pop(); 53 | cur = newHead; 54 | while (!stack.isEmpty()) { 55 | cur.left = stack.pop(); 56 | if (cur.left != null) { 57 | cur.left.left = null; 58 | cur.left.right = null; 59 | } 60 | cur.right = stack.pop(); 61 | if (cur.right != null) { 62 | cur.right.left = null; 63 | cur.right.right = null; 64 | } 65 | cur = cur.right; 66 | } 67 | return newHead; 68 | } 69 | } -------------------------------------------------------------------------------- /Hard/305 Number of Islands II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List numIslands2(int m, int n, int[][] positions) { 3 | List result = new ArrayList<>(); 4 | if (positions == null || positions.length == 0 || m <= 0 || n <= 0) { 5 | return result; 6 | } 7 | int[] height = new int[m * n]; 8 | int[] id = new int[m * n]; 9 | for (int i = 0; i < id.length; i++) { 10 | id[i] = i; 11 | } 12 | int count = 0; 13 | for (int[] position : positions) { 14 | int x = position[0]; 15 | int y = position[1]; 16 | int cur = n * x + y; 17 | count += 1; 18 | height[cur] = 1; 19 | if (x > 0) { 20 | count += unionFind(height, id, cur, cur - n); 21 | } 22 | if (x < m - 1) { 23 | count += unionFind(height, id, cur, cur + n); 24 | } 25 | if (y > 0) { 26 | count += unionFind(height, id, cur, cur - 1); 27 | } 28 | if (y < n - 1) { 29 | count += unionFind(height, id, cur, cur + 1); 30 | } 31 | result.add(count); 32 | } 33 | return result; 34 | } 35 | 36 | private int unionFind(int[] height, int[] id, int pos1, int pos2) { 37 | int root1 = findRoot(pos1, id); 38 | int root2 = findRoot(pos2, id); 39 | if (height[root2] != 0 && root1 != root2) { 40 | if (height[root2] == height[root1]) { 41 | id[root1] = root2; 42 | height[root2] += 1; 43 | } else { 44 | int min = (height[root1] < height[root2]) ? root1 : root2; 45 | int max = (height[root1] > height[root2]) ? root1 : root2; 46 | id[min] = max; 47 | } 48 | return -1; 49 | } 50 | return 0; 51 | } 52 | 53 | private int findRoot(int pos, int[] id) { 54 | while (id[pos] != pos) { 55 | pos = id[pos]; 56 | } 57 | return pos; 58 | } 59 | } -------------------------------------------------------------------------------- /Medium/073 Set Matrix Zeroes.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void setZeroes(int[][] matrix) { 3 | if (matrix == null || matrix.length == 0) { 4 | return; 5 | } 6 | int head = -1; 7 | int prev = -1; 8 | boolean firstColHasZero = false; 9 | 10 | // check first column 11 | for (int i = 0; i < matrix.length; i++) { 12 | if (matrix[i][0] == 0) { 13 | firstColHasZero = true; 14 | break; 15 | } 16 | } 17 | 18 | // build the linkedlist 19 | for (int i = 0; i < matrix.length; i++) { 20 | for (int j = 0; j < matrix[0].length; j++) { 21 | if (matrix[i][j] == 0) { 22 | if (head == -1) { 23 | head = i; 24 | } else { 25 | matrix[prev][0] = i; 26 | } 27 | prev = i; 28 | break; 29 | } 30 | } 31 | } 32 | 33 | // check whether the matrix has at least a zero 34 | if (head == -1) { 35 | return; 36 | // set tail 37 | } else { 38 | matrix[prev][0] = -1; 39 | } 40 | 41 | // set columns zeros if zero exists except the first one 42 | for (int j = 1; j < matrix[0].length; j++) { 43 | for (int i = 0; i < matrix.length; i++) { 44 | if (matrix[i][j] == 0) { 45 | for (int ii = 0; ii < matrix.length; ii++) { 46 | matrix[ii][j] = 0; 47 | } 48 | break; 49 | } 50 | } 51 | } 52 | 53 | // set rows zeros 54 | while (head != -1) { 55 | int next = matrix[head][0]; 56 | Arrays.fill(matrix[head], 0); 57 | head = next; 58 | } 59 | 60 | // set the first column zeros if necessary 61 | if (firstColHasZero) { 62 | for (int i = 0; i < matrix.length; i++) { 63 | matrix[i][0] = 0; 64 | } 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /Hard/297 Serialize and Deserialize Binary Tree.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Codec { 11 | 12 | // Encodes a tree to a single string. 13 | public String serialize(TreeNode root) { 14 | StringBuilder sb = new StringBuilder(); 15 | LinkedList list = new LinkedList<>(); 16 | list.add(root); 17 | while (!list.isEmpty()) { 18 | TreeNode node = list.poll(); 19 | if (node == null) { 20 | sb.append("null,"); 21 | } else { 22 | sb.append(node.val + ","); 23 | list.add(node.left); 24 | list.add(node.right); 25 | } 26 | } 27 | sb.deleteCharAt(sb.length() - 1); 28 | return sb.toString(); 29 | } 30 | 31 | // Decodes your encoded data to tree. 32 | public TreeNode deserialize(String data) { 33 | String[] strings = data.split(","); 34 | TreeNode head; 35 | LinkedList list = new LinkedList<>(); 36 | if (!strings[0].equals("null")) { 37 | head = new TreeNode(Integer.parseInt(strings[0])); 38 | list.add(head); 39 | } else { 40 | head = null; 41 | } 42 | int i = 1; 43 | while (!list.isEmpty()) { 44 | TreeNode node = list.poll(); 45 | if (!strings[i].equals("null")) { 46 | TreeNode leftNode = new TreeNode(Integer.parseInt(strings[i])); 47 | node.left = leftNode; 48 | list.add(leftNode); 49 | } 50 | i += 1; 51 | if (!strings[i].equals("null")) { 52 | TreeNode rightNode = new TreeNode(Integer.parseInt(strings[i])); 53 | node.right = rightNode; 54 | list.add(rightNode); 55 | } 56 | i += 1; 57 | } 58 | return head; 59 | } 60 | } 61 | 62 | // Your Codec object will be instantiated and called as such: 63 | // Codec codec = new Codec(); 64 | // codec.deserialize(codec.serialize(root)); -------------------------------------------------------------------------------- /Medium/166 Fraction to Recurring Decimal.txt: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | public String fractionToDecimal(int numerator, int denominator) { 5 | 6 | // check case: numerator = 0 7 | if (numerator == 0) { 8 | return "0"; 9 | } 10 | 11 | // add signs 12 | StringBuilder sb = new StringBuilder(); 13 | if (numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0) { 14 | sb.append('-'); 15 | } else { 16 | sb.append('+'); 17 | } 18 | 19 | // long type for -2147483648 s.o.b. 20 | long n = Math.abs((long)numerator); 21 | long d = Math.abs((long)denominator); 22 | 23 | Hashtable remainTable = new Hashtable<>(); 24 | long remain = n; 25 | boolean afterDot = false; 26 | int count = 0; 27 | while (remain != 0) { 28 | if (remain < d) { 29 | if (!afterDot) { 30 | sb.append("."); 31 | afterDot = true; 32 | } 33 | if (afterDot) { 34 | if (remainTable.containsKey(remain)) { 35 | count -= remainTable.get(remain); 36 | break; 37 | } else { 38 | remainTable.put(remain, count); 39 | count += 1; 40 | } 41 | } 42 | remain *= 10; 43 | } 44 | sb.append(remain / d); 45 | remain %= d; 46 | } 47 | 48 | // add recursion part 49 | if (count > 0 && afterDot && remain != 0) { 50 | sb.insert(sb.length() - count, '('); 51 | sb.append(')'); 52 | } 53 | 54 | // remove 0s at the most significant positions 55 | while (sb.charAt(1) == '0') { 56 | sb.deleteCharAt(1); 57 | } 58 | 59 | // add 0 before dot 60 | if (sb.charAt(1) == '.') { 61 | sb.insert(1, '0'); 62 | } 63 | 64 | // remove "+" sign 65 | if (sb.charAt(0) == '+') { 66 | sb.deleteCharAt(0); 67 | } 68 | 69 | return sb.toString(); 70 | } 71 | } -------------------------------------------------------------------------------- /Medium/311 Sparse Matrix Multiplication.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[][] multiply(int[][] A, int[][] B) { 3 | int m = A.length; 4 | int n = A[0].length; 5 | int p = B[0].length; 6 | int[][] result = new int[m][p]; 7 | for (int i = 0; i < m; i++) { 8 | for (int j = 0; j < n; j++) { 9 | int cur = A[i][j]; 10 | if (cur != 0) { 11 | for (int k = 0; k < p; k++) { 12 | result[i][k] += B[j][k] * cur; 13 | } 14 | } 15 | } 16 | } 17 | return result; 18 | } 19 | } 20 | 21 | 22 | public class Solution { 23 | public int[][] multiply(int[][] A, int[][] B) { 24 | ArrayList> positionListA = new ArrayList<>(); 25 | ArrayList> positionListB = new ArrayList<>(); 26 | for (int i = 0; i < A.length; i++) { 27 | Set set = new HashSet<>(); 28 | for (int j = 0; j < A[i].length; j++) { 29 | if (A[i][j] != 0) { 30 | set.add(j); 31 | } 32 | } 33 | positionListA.add(set); 34 | } 35 | for (int j = 0; j < B[0].length; j++) { 36 | Set set = new HashSet<>(); 37 | for (int i = 0; i < B.length; i++) { 38 | if (B[i][j] != 0) { 39 | set.add(i); 40 | } 41 | } 42 | positionListB.add(set); 43 | } 44 | int[][] result = new int[A.length][B[0].length]; 45 | for (int i = 0; i < result.length; i++) { 46 | for (int j = 0; j < result[0].length; j++) { 47 | Set setA = positionListA.get(i); 48 | Set setB = positionListB.get(j); 49 | Set smaller = (setA.size() < setB.size()) ? setA: setB; 50 | Set bigger = (setA.size() < setB.size()) ? setB: setA; 51 | int sum = 0; 52 | for (int k : smaller) { 53 | sum += (bigger.contains(k)) ? A[i][k] * B[k][j] : 0; 54 | } 55 | result[i][j] = sum; 56 | } 57 | } 58 | return result; 59 | } 60 | } -------------------------------------------------------------------------------- /Medium/341 Flatten Nested List Iterator.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * // This is the interface that allows for creating nested lists. 3 | * // You should not implement it, or speculate about its implementation 4 | * public interface NestedInteger { 5 | * 6 | * // @return true if this NestedInteger holds a single integer, rather than a nested list. 7 | * public boolean isInteger(); 8 | * 9 | * // @return the single integer that this NestedInteger holds, if it holds a single integer 10 | * // Return null if this NestedInteger holds a nested list 11 | * public Integer getInteger(); 12 | * 13 | * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 | * // Return null if this NestedInteger holds a single integer 15 | * public List getList(); 16 | * } 17 | */ 18 | public class NestedIterator implements Iterator { 19 | Iterator iterator; 20 | NestedIterator subIter; 21 | int nextInt = 0; 22 | boolean isInt; 23 | 24 | public NestedIterator(List nestedList) { 25 | this.iterator = nestedList.iterator(); 26 | subIter = null; 27 | isInt = true; 28 | } 29 | 30 | @Override 31 | public Integer next() { 32 | return isInt ? nextInt : subIter.next(); 33 | } 34 | 35 | @Override 36 | public boolean hasNext() { 37 | if (!isInt && subIter.hasNext()) { 38 | return true; 39 | } else { 40 | while (iterator.hasNext()) { 41 | NestedInteger next = iterator.next(); 42 | if (next.isInteger()) { 43 | nextInt = next.getInteger(); 44 | isInt = true; 45 | return true; 46 | } else { 47 | subIter = new NestedIterator(next.getList()); 48 | if (subIter.hasNext()) { 49 | isInt = false; 50 | return true; 51 | } 52 | } 53 | } 54 | return false; 55 | } 56 | } 57 | } 58 | 59 | /** 60 | * Your NestedIterator object will be instantiated and called as such: 61 | * NestedIterator i = new NestedIterator(nestedList); 62 | * while (i.hasNext()) v[f()] = i.next(); 63 | */ -------------------------------------------------------------------------------- /Medium/364 Nested List Weight Sum II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * // This is the interface that allows for creating nested lists. 3 | * // You should not implement it, or speculate about its implementation 4 | * public interface NestedInteger { 5 | * 6 | * // @return true if this NestedInteger holds a single integer, rather than a nested list. 7 | * public boolean isInteger(); 8 | * 9 | * // @return the single integer that this NestedInteger holds, if it holds a single integer 10 | * // Return null if this NestedInteger holds a nested list 11 | * public Integer getInteger(); 12 | * 13 | * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 | * // Return null if this NestedInteger holds a single integer 15 | * public List getList(); 16 | * } 17 | */ 18 | public class Solution { 19 | public int depthSumInverse(List nestedList) { 20 | if (nestedList == null || nestedList.isEmpty()) { 21 | return 0; 22 | } 23 | int level = getLv(nestedList); 24 | int sum = getSum(nestedList, level); 25 | return sum; 26 | } 27 | 28 | private int getLv(List nestedList) { 29 | if (nestedList == null || nestedList.isEmpty()) { 30 | return 0; 31 | } 32 | int level = 0; 33 | boolean hasInt = false; 34 | for (NestedInteger ni : nestedList) { 35 | if (!ni.isInteger()) { 36 | int curLv = getLv(ni.getList()); 37 | if (curLv > level) { 38 | level = curLv; 39 | } 40 | } else { 41 | hasInt = true; 42 | } 43 | } 44 | return (level > 0 || hasInt) ? level + 1 : 0; 45 | } 46 | 47 | private int getSum(List nestedList, int level) { 48 | if (level == 0 || nestedList == null || nestedList.isEmpty()) { 49 | return 0; 50 | } 51 | int sum = 0; 52 | for (NestedInteger ni : nestedList) { 53 | if (ni.isInteger()) { 54 | sum += ni.getInteger() * level; 55 | } else { 56 | sum += getSum(ni.getList(), level - 1); 57 | } 58 | } 59 | return sum; 60 | } 61 | } -------------------------------------------------------------------------------- /Hard/381 Insert Delete GetRandom O(1) - Duplicates allowed.txt: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomizedCollection { 4 | 5 | HashMap> map; 6 | List nums; 7 | int size; 8 | 9 | /** Initialize your data structure here. */ 10 | public RandomizedCollection() { 11 | map = new HashMap<>(); 12 | nums = new ArrayList<>(); 13 | size = 0; 14 | } 15 | 16 | /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ 17 | public boolean insert(int val) { 18 | boolean res = true; 19 | if (map.containsKey(val)) { 20 | res = false; 21 | } else { 22 | map.put(val, new HashSet<>()); 23 | } 24 | map.get(val).add(size); 25 | nums.add(val); 26 | size += 1; 27 | return res; 28 | } 29 | 30 | /** Removes a value from the collection. Returns true if the collection contained the specified element. */ 31 | public boolean remove(int val) { 32 | if (map.isEmpty() || !map.containsKey(val)) { 33 | return false; 34 | } 35 | 36 | size -= 1; 37 | int lastNum = nums.get(size); 38 | Set idxSet = map.get(val); 39 | if (lastNum != val) { 40 | int idx = idxSet.iterator().next(); 41 | Set lastNumIdxSet = map.get(lastNum); 42 | lastNumIdxSet.remove(size); 43 | lastNumIdxSet.add(idx); 44 | nums.set(idx, lastNum); 45 | } 46 | 47 | if (idxSet.size() == 1) { 48 | map.remove(val); 49 | } else { 50 | idxSet.remove(size); 51 | } 52 | 53 | nums.remove(size); 54 | return true; 55 | 56 | } 57 | 58 | /** Get a random element from the collection. */ 59 | public int getRandom() { 60 | Random random = new Random(); 61 | return nums.get(random.nextInt(size)); 62 | } 63 | } 64 | 65 | /** 66 | * Your RandomizedCollection object will be instantiated and called as such: 67 | * RandomizedCollection obj = new RandomizedCollection(); 68 | * boolean param_1 = obj.insert(val); 69 | * boolean param_2 = obj.remove(val); 70 | * int param_3 = obj.getRandom(); 71 | */ -------------------------------------------------------------------------------- /Hard/269 Alien Dictionary.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | boolean[][] graph; 3 | boolean[] usedLetters; 4 | int[] indegree; 5 | 6 | 7 | public String alienOrder(String[] words) { 8 | if (words == null || words.length == 0) { 9 | return ""; 10 | } 11 | graph = new boolean[26][26]; 12 | usedLetters = new boolean[26]; 13 | indegree = new int[26]; 14 | String prev = words[0]; 15 | for (String cur : words) { 16 | update(prev, cur); 17 | prev = cur; 18 | } 19 | return tpSort(); 20 | } 21 | 22 | private String tpSort() { 23 | StringBuilder order = new StringBuilder(); 24 | Deque queue = new ArrayDeque<>(); 25 | for (int i = 0; i < 26; i++) { 26 | if (usedLetters[i] && indegree[i] == 0) { 27 | queue.add(i); 28 | usedLetters[i] = false; 29 | } 30 | } 31 | while (!queue.isEmpty()) { 32 | int node = queue.poll(); 33 | order.append((char)(node + 'a')); 34 | for (int i = 0; i < 26; i++) { 35 | if (graph[node][i]) { 36 | int next = i; 37 | indegree[next] -= 1; 38 | if (indegree[next] == 0) { 39 | queue.add(next); 40 | usedLetters[next] = false; 41 | } 42 | } 43 | } 44 | } 45 | for (int i : indegree) { 46 | if (i != 0) { 47 | return ""; 48 | } 49 | } 50 | return order.toString(); 51 | } 52 | 53 | private void update(String prev, String cur) { 54 | boolean edgeFound = false; 55 | for (int i = 0; i < cur.length(); i++) { 56 | char curChar = cur.charAt(i); 57 | usedLetters[curChar - 'a'] = true; 58 | if (!edgeFound && i < prev.length()) { 59 | char prevChar = prev.charAt(i); 60 | edgeFound = (curChar != prevChar); 61 | if (edgeFound && !graph[prevChar - 'a'][curChar - 'a']) { 62 | graph[prevChar - 'a'][curChar - 'a'] = true; 63 | indegree[curChar - 'a'] += 1; 64 | } 65 | } 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Medium/353 Design Snake Game.txt: -------------------------------------------------------------------------------- 1 | public class SnakeGame { 2 | Set grid; 3 | int width, height; 4 | LinkedList snake; 5 | int head; 6 | int[][] food; 7 | int foodIdx; 8 | int score; 9 | 10 | /** Initialize your data structure here. 11 | @param width - screen width 12 | @param height - screen height 13 | @param food - A list of food positions 14 | E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ 15 | public SnakeGame(int width, int height, int[][] food) { 16 | this.width = width; 17 | this.height = height; 18 | grid = new HashSet<>(); 19 | snake = new LinkedList<>(); 20 | snake.add(0); 21 | head = 0; 22 | grid.add(0); 23 | this.food = food; 24 | foodIdx = 0; 25 | score = 0; 26 | } 27 | 28 | /** Moves the snake. 29 | @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 30 | @return The game's score after the move. Return -1 if game over. 31 | Game over when snake crosses the screen boundary or bites its body. */ 32 | public int move(String direction) { 33 | char dir = direction.charAt(0); 34 | int nextX = head / width; 35 | int nextY = head % width; 36 | nextX += (dir == 'U') ? -1 : 0; 37 | nextX += (dir == 'D') ? 1 : 0; 38 | nextY += (dir == 'L') ? -1 : 0; 39 | nextY += (dir == 'R') ? 1 : 0; 40 | if (isGameOver(nextX, nextY)) { 41 | return -1; 42 | } 43 | int next = nextX * width + nextY; 44 | if (foodIdx < food.length && food[foodIdx][0] * width + food[foodIdx][1] == next) { 45 | score += 1; 46 | foodIdx += 1; 47 | } else { 48 | grid.remove(snake.poll()); 49 | } 50 | grid.add(next); 51 | snake.add(next); 52 | head = next; 53 | return score; 54 | } 55 | 56 | private boolean isGameOver(int nextX, int nextY) { 57 | if (nextX < 0 || nextX >= height || nextY < 0 || nextY >= width) { 58 | return true; 59 | } 60 | int tail = snake.peek(); 61 | int next = nextX * width + nextY; 62 | if (grid.contains(next) && next != tail) { 63 | return true; 64 | } 65 | return false; 66 | } 67 | } 68 | 69 | /** 70 | * Your SnakeGame object will be instantiated and called as such: 71 | * SnakeGame obj = new SnakeGame(width, height, food); 72 | * int param_1 = obj.move(direction); 73 | */ -------------------------------------------------------------------------------- /Medium/337 House Robber III.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | import java.util.*; 11 | 12 | public class Solution { 13 | public int rob(TreeNode root) { 14 | HashMap robMap = new HashMap<>(); 15 | HashMap notRobMap = new HashMap<>(); 16 | return Math.max(robThis(root, robMap, notRobMap), 17 | notRobThis(root, robMap, notRobMap)); 18 | } 19 | 20 | private int robThis(TreeNode root, HashMap robMap, 21 | HashMap notRobMap) { 22 | if (robMap.containsKey(root)) { 23 | return robMap.get(root); 24 | } 25 | if (root == null) { 26 | return 0; 27 | } 28 | if (root.left == null && root.right == null) { 29 | return root.val; 30 | } 31 | int value = root.val + notRobThis(root.left, robMap, notRobMap) 32 | + notRobThis(root.right, robMap, notRobMap); 33 | robMap.put(root, value); 34 | return value; 35 | 36 | } 37 | 38 | private int notRobThis(TreeNode root, HashMap robMap, 39 | HashMap notRobMap) { 40 | if (notRobMap.containsKey(root)) { 41 | return notRobMap.get(root); 42 | } 43 | int value = 0; 44 | if (root != null) { 45 | value = Math.max(robThis(root.left, robMap, notRobMap), notRobThis(root.left, robMap, notRobMap)) 46 | + Math.max(robThis(root.right, robMap, notRobMap), notRobThis(root.right, robMap, notRobMap)); 47 | } 48 | notRobMap.put(root, value); 49 | return value; 50 | } 51 | } 52 | 53 | 54 | /** 55 | * Definition for a binary tree node. 56 | * public class TreeNode { 57 | * int val; 58 | * TreeNode left; 59 | * TreeNode right; 60 | * TreeNode(int x) { val = x; } 61 | * } 62 | */ 63 | 64 | public class Solution { 65 | public int rob(TreeNode root) { 66 | int[] vals = DProb(root); 67 | return Math.max(vals[0], vals[1]); 68 | } 69 | 70 | private int[] DProb(TreeNode root) { 71 | // vals[0]: not rob current root 72 | // vals[1]: rob current root 73 | int[] vals = new int[2]; 74 | 75 | if (root == null) { 76 | return vals; 77 | } 78 | int[] left = DProb(root.left); 79 | int[] right = DProb(root.right); 80 | 81 | vals[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); 82 | vals[1] = root.val + left[0] + right[0]; 83 | 84 | return vals; 85 | } 86 | } -------------------------------------------------------------------------------- /Medium/320 Generalized Abbreviation.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List generateAbbreviations(String word) { 3 | List abbrevList = new ArrayList<>(); 4 | if (word.length() == 0) { 5 | abbrevList.add(""); 6 | } else if (word.length() == 1) { 7 | abbrevList.add(word); 8 | abbrevList.add("1"); 9 | } else { 10 | String lastPattern = "[0-9]+$"; 11 | String firstPattern = "^[0-9]+"; 12 | String left = word.substring(0, word.length() / 2); 13 | String right = word.substring(word.length() / 2, word.length()); 14 | List leftList = generateAbbreviations(left); 15 | List rightList = generateAbbreviations(right); 16 | for (String l : leftList) { 17 | for (String r : rightList) { 18 | String ls = l.replaceAll(lastPattern, ""); 19 | String rs = r.replaceAll(firstPattern, ""); 20 | if (ls.length() != l.length() && rs.length() != r.length()) { 21 | int ln = Integer.parseInt(l.substring(ls.length())); 22 | int rn = Integer.parseInt(r.substring(0, r.length() - rs.length())); 23 | int i = ln + rn; 24 | abbrevList.add(ls + i + rs); 25 | } else { 26 | abbrevList.add(l + r); 27 | } 28 | } 29 | } 30 | } 31 | return abbrevList; 32 | } 33 | } 34 | 35 | public class Solution { 36 | public List generateAbbreviations(String word) { 37 | List abbrevList = new ArrayList<>(); 38 | if (word.length() == 0) { 39 | abbrevList.add(""); 40 | } else { 41 | String curString = ""; 42 | int start = 0; 43 | int end = word.length(); 44 | int count = 0; 45 | dfs(curString, start, end, count, abbrevList, word); 46 | } 47 | return abbrevList; 48 | } 49 | 50 | private void dfs(String curString, int start, int end, 51 | int count, List abbrevList, String original) { 52 | if (start < end) { 53 | dfs(curString, start + 1, end, count + 1, abbrevList, original); 54 | String newString = ""; 55 | if (count > 0) { 56 | newString += count; 57 | count = 0; 58 | } 59 | newString = curString + newString + original.charAt(start); 60 | dfs(newString, start + 1, end, count, abbrevList, original); 61 | } else { 62 | if (count > 0) { 63 | curString += count; 64 | } 65 | abbrevList.add(curString); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Medium/095 Unique Binary Search Trees II.txt: -------------------------------------------------------------------------------- 1 | Solution 1 (Original Solution): Recursion 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public List generateTrees(int n) { 14 | if (n == 0) { 15 | return new ArrayList(); 16 | } else { 17 | return generate(1, n); 18 | } 19 | } 20 | 21 | private List generate(int start, int end){ 22 | List result = new ArrayList(); 23 | 24 | if (start > end) { 25 | result.add(null); 26 | return result; 27 | } 28 | 29 | for (int root = start; root <= end; root++) { 30 | List left = generate(start, root - 1); 31 | List right = generate(root + 1, end); 32 | for (TreeNode leftNode: left) { 33 | for (TreeNode rightNode: right) { 34 | TreeNode rootNode = new TreeNode(root); 35 | rootNode.left = leftNode; 36 | rootNode.right = rightNode; 37 | result.add(rootNode); 38 | } 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | } 45 | 46 | Solution 2 (Improved Solution): Recursion + DP(Map) 47 | 48 | /** 49 | * Definition for a binary tree node. 50 | * public class TreeNode { 51 | * int val; 52 | * TreeNode left; 53 | * TreeNode right; 54 | * TreeNode(int x) { val = x; } 55 | * } 56 | */ 57 | public class Solution { 58 | Map> map; 59 | int hash; 60 | 61 | public List generateTrees(int n) { 62 | if (n == 0) { 63 | return new ArrayList(); 64 | } else { 65 | map = new HashMap<>(); 66 | hash = n; 67 | return generate(1, n); 68 | } 69 | } 70 | 71 | private List generate(int start, int end) { 72 | List result = new ArrayList(); 73 | 74 | if (start > end) { 75 | result.add(null); 76 | return result; 77 | } 78 | 79 | for (int root = start; root <= end; root++) { 80 | int leftKey = start * hash + (root - 1); 81 | int rightKey = (root + 1) * hash + end; 82 | if (!map.containsKey(leftKey)) { 83 | map.put(leftKey, generate(start, root - 1)); 84 | } 85 | if (!map.containsKey(rightKey)) { 86 | map.put(rightKey, generate(root + 1, end)); 87 | } 88 | List leftList = map.get(leftKey); 89 | List rightList = map.get(rightKey); 90 | for (TreeNode leftNode: leftList) { 91 | for (TreeNode rightNode: rightList) { 92 | TreeNode rootNode = new TreeNode(root); 93 | rootNode.left = leftNode; 94 | rootNode.right = rightNode; 95 | result.add(rootNode); 96 | } 97 | } 98 | } 99 | 100 | return result; 101 | } 102 | } -------------------------------------------------------------------------------- /Medium/244 Shortest Word Distance II.txt: -------------------------------------------------------------------------------- 1 | // 27 ms O(mn) 2 | 3 | public class WordDistance { 4 | HashMap> map; 5 | 6 | public WordDistance(String[] words) { 7 | map = new HashMap<>(); 8 | for (int i = 0; i < words.length; i++) { 9 | String word = words[i]; 10 | map.putIfAbsent(word, new ArrayList()); 11 | map.get(word).add(i); 12 | } 13 | } 14 | 15 | public int shortest(String word1, String word2) { 16 | List list1 = map.get(word1); 17 | List list2 = map.get(word2); 18 | int min = Integer.MAX_VALUE; 19 | for (int num1 : list1) { 20 | for (int num2 : list2) { 21 | int temp = Math.abs(num1 - num2); 22 | min = temp < min ? temp : min; 23 | } 24 | } 25 | return min; 26 | } 27 | } 28 | 29 | // 16 ms O(m + n) 30 | 31 | public class WordDistance { 32 | HashMap> map; 33 | 34 | public WordDistance(String[] words) { 35 | map = new HashMap<>(); 36 | for (int i = 0; i < words.length; i++) { 37 | String word = words[i]; 38 | map.putIfAbsent(word, new ArrayList()); 39 | map.get(word).add(i); 40 | } 41 | } 42 | 43 | public int shortest(String word1, String word2) { 44 | List list1 = map.get(word1); 45 | List list2 = map.get(word2); 46 | int min = findMin(list1, list2); 47 | return min; 48 | } 49 | 50 | private int findMin(List list1, List list2) { 51 | if (list1.get(0) < list2.get(0)) { 52 | return findMin(list2, list1); 53 | } 54 | int min = Integer.MAX_VALUE; 55 | int j = 1; 56 | for (int i = 0; i < list1.size(); i++) { 57 | int a = list1.get(i); 58 | while (j < list2.size() && a > list2.get(j)) { 59 | j++; 60 | } 61 | int temp = a - list2.get(j - 1); 62 | if (j < list2.size()) { 63 | temp = (temp < list2.get(j) - a) ? temp : list2.get(j) - a; 64 | } 65 | min = min < temp ? min : temp; 66 | } 67 | return min; 68 | } 69 | } 70 | 71 | // elegant 72 | public class WordDistance { 73 | 74 | HashMap> map = null; 75 | 76 | public WordDistance(String[] words) { 77 | map = new HashMap>(); 78 | for (int i = 0; i < words.length; i++) { 79 | if (!map.containsKey(words[i])) { 80 | map.put(words[i], new ArrayList()); 81 | } 82 | map.get(words[i]).add(i); 83 | } 84 | } 85 | 86 | public int shortest(String word1, String word2) { 87 | List list1 = map.get(word1); 88 | List list2 = map.get(word2); 89 | int i = 0, j = 0; 90 | int min = Integer.MAX_VALUE; 91 | while (i < list1.size() && j < list2.size()) { 92 | min = Math.min(min, Math.abs(list1.get(i) - list2.get(j))); 93 | if (list1.get(i) < list2.get(j)) { 94 | i++; 95 | } else { 96 | j++; 97 | } 98 | } 99 | return min; 100 | } 101 | } -------------------------------------------------------------------------------- /list.txt: -------------------------------------------------------------------------------- 1 | Medium: 2 | 011 Container With Most Water 3 | 012 Integer to Roman 4 | 016 3Sum Closest 5 | 022 Generate Parentheses 6 | 034 Search for a Range 7 | 035 Search Insert Position 8 | 039 Combination Sum 9 | 046 Permutations 10 | 048 Rotate Image 11 | 053 Maximum Subarray 12 | 059 Spiral Matrix II 13 | 062 Unique Paths 14 | 063 Unique Paths II 15 | 064 Minimum Path Sum 16 | 073 Set Matrix Zeroes 17 | 074 Search a 2D Matrix 18 | 075 Sort Colors 19 | 077 Combinations 20 | 078 Subsets 21 | 080 Remove Duplicates from Sorted Array II 22 | 081 Search in Rotated Sorted Array II 23 | 086 Partition List 24 | 089 Gray Code 25 | 090 Subsets II 26 | 092 Reverse Linked List II 27 | 094 Binary Tree Inorder Traversal 28 | 095 Unique Binary Search Trees II 29 | 096 Unique Binary Search Trees 30 | 103 Binary Tree Zigzag Level Order Traversal 31 | 105 Construct Binary Tree from Preorder and Inorder Traversal 32 | 106 Construct Binary Tree from Inorder and Postorder Traversal 33 | 108 Convert Sorted Array to Binary Search Tree 34 | 109 Convert Sorted List to Binary Search Tree 35 | 113 Path Sum II 36 | 114 Flatten Binary Tree to Linked List 37 | 116 Populating Next Right Pointers in Each Node 38 | 120 Triangle 39 | 122 Best Time to Buy and Sell Stock II 40 | 129 Sum Root to Leaf Numbers 41 | 136 Single Number 42 | 137 Single Number II 43 | 142 Linked List Cycle II 44 | 144 Binary Tree Preorder Traversal 45 | 147 Insertion Sort List 46 | 153 Find Minimum in Rotated Sorted Array 47 | 156 Binary Tree Upside Down 48 | 162 Find Peak Element 49 | 163 Missing Ranges 50 | 166 Fraction to Recurring Decimal 51 | 167 Two Sum II - Input array is sorted 52 | 173 Binary Search Tree Iterator 53 | 199 Binary Tree Right Side View 54 | 200 Number of Islands 55 | 201 Bitwise AND of Numbers Range 56 | 213 House Robber II 57 | 215 Kth Largest Element in an Array 58 | 216 Combination Sum III 59 | 230 Kth Smallest Element in a BST 60 | 238 Product of Array Except Self 61 | 240 Search a 2D Matrix II 62 | 241 Different Ways to Add Parentheses 63 | 244 Shortest Word Distance II 64 | 245 Shortest Word Distance III 65 | 247 Strobogrammatic Number II 66 | 250 Count Univalue Subtrees 67 | 251 Flatten 2D Vector 68 | 253 Meeting Rooms II 69 | 254 Factor Combinations 70 | 256 Paint House 71 | 259 3Sum Smaller 72 | 260 Single Number III 73 | 261 Graph Valid Tree 74 | 264 Ugly Number II 75 | 268 Missing Number 76 | 274 H-Index 77 | 275 H-Index II 78 | 277 Find the Celebrity 79 | 279 Perfect Squares 80 | 280 Wiggle Sort 81 | 281 Zigzag Iterator 82 | 284 Peeking Iterator 83 | 285 Inorder Successor in BST 84 | 286 Walls and Gates 85 | 289 Game of Life 86 | 294 Flip Game II 87 | 298 Binary Tree Longest Consecutive Sequence 88 | 300 Longest Increasing Subsequence 89 | 309 Best Time to Buy and Sell Stock with Cooldown 90 | 311 Sparse Matrix Multiplication 91 | 313 Super Ugly Number 92 | 314 Binary Tree Vertical Order Traversal 93 | 318 Maximum Product of Word Lengths 94 | 319 Bulb Switcher 95 | 320 Generalized Abbreviation 96 | 323 Number of Connected Components in an Undirected Graph 97 | 328 Odd Even Linked List 98 | 331 Verify Preorder Serialization of a Binary Tree 99 | 333 Largest BST Subtree 100 | 334 Increasing Triplet Subsequence 101 | 337 House Robber III 102 | 338 Counting Bits 103 | 341 Flatten Nested List Iterator 104 | 343 Integer Break 105 | 347 Top K Frequent Elements 106 | 348 Design Tic-Tac-Toe 107 | 353 Design Snake Game 108 | 357 Count Numbers with Unique Digits 109 | 360 Sort Transformed Array 110 | 361 Bomb Enemy 111 | 362 Design Hit Counter 112 | 364 Nested List Weight Sum II 113 | 365 Water and Jug Problem 114 | 366 Find Leaves of Binary Tree 115 | 367 Valid Perfect Square 116 | 368 Largest Divisible Subset 117 | 369 Plus One Linked List 118 | 370 Range Addition 119 | 372 Super Pow 120 | 373 Find K Pairs with Smallest Sums 121 | 375 Guess Number Higher or Lower II 122 | 376 Wiggle Subsequence 123 | 377 Combination Sum IV 124 | 378 Kth Smallest Element in a Sorted Matrix 125 | 379 Design Phone Directory 126 | 382 Linked List Random Node 127 | 384 Shuffle an Array 128 | 386 Lexicographical Numbers 129 | 388 Longest Absolute File Path 130 | 392 Is Subsequence 131 | 393 UTF-8 Validation 132 | 394 Decode String 133 | 395 Longest Substring with At Least K Repeating Characters 134 | 398 Random Pick Index 135 | 421 Maximum XOR of Two Numbers in an Array 136 | 137 | Hard: 138 | 033 Search in Rotated Sorted Array 139 | 051 N-Queens Complete 140 | 051 N-Queens 141 | 052 N-Queens 142 | 123 Best Time to Buy and Sell Stock III 143 | 145 Binary Tree Postorder Traversal 144 | 146 LRU Cache 145 | 159 Longest Substring with At Most Two Distinct Characters 146 | 188 Best Time to Buy and Sell Stock IV 147 | 265 Paint House II 148 | 269 Alien Dictionary 149 | 273 Integer to English Words 150 | 287 Find the Duplicate Number 151 | 291 Word Pattern II 152 | 296 Best Meeting Point 153 | 297 Serialize and Deserialize Binary Tree 154 | 305 Number of Islands II 155 | 312 Burst Balloons 156 | 329 Longest Increasing Path in a Matrix 157 | 340 Longest Substring with At Most K Distinct Characters 158 | 380 Insert Delete GetRandom O(1) 159 | 381 Insert Delete GetRandom O(1) - Duplicates allowed 160 | 410 Split Array Largest Sum 161 | -------------------------------------------------------------------------------- /Hard/052 N-Queens.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | int count = 0; 3 | 4 | public int totalNQueens(int n) { 5 | 6 | // chosen positions for Queens 7 | List chosenRows = new ArrayList<>(); 8 | List chosenCols = new ArrayList<>(); 9 | 10 | // the original possible positions for searching 11 | List> positions = initializePos(n); 12 | 13 | // rowCounter counts the number of posible positions on each row 14 | // rowCounter = [n, n, ..., n] (before searching) 15 | int[] rowCounter = initializeCounter(n); 16 | 17 | search(positions, rowCounter, chosenRows, chosenCols); 18 | 19 | return count; 20 | } 21 | 22 | 23 | // search 24 | private void search(List> positions, int[] rowCounter, 25 | List chosenRows, List chosenCols) { 26 | int minRow = findMin(rowCounter); 27 | int numOfPositions = rowCounter[minRow]; 28 | 29 | // dead end 30 | if (numOfPositions == 0) { 31 | return; 32 | } 33 | 34 | // N Quees are settled 35 | if (numOfPositions == Integer.MAX_VALUE) { 36 | count++; 37 | return; 38 | } 39 | 40 | // need further seaching 41 | rowCounter[minRow] = Integer.MAX_VALUE; 42 | Set colSet = positions.get(minRow); 43 | positions.set(minRow, new HashSet<>()); 44 | chosenRows.add(minRow); 45 | 46 | List>> positionsList = new ArrayList<>(); 47 | PriorityQueue> deletedPosPQ = new PriorityQueue<>(new Comparator>() { 48 | public int compare(List l1, List l2) { 49 | return l1.size() - l2.size(); 50 | } 51 | }); 52 | int count = 0; 53 | for (Integer col : colSet) { 54 | List deletedPos = new ArrayList<>(); 55 | positionsList.add(checkConflict(positions, minRow, col, deletedPos)); 56 | deletedPos.add(count); 57 | count++; 58 | deletedPosPQ.add(deletedPos); 59 | } 60 | while (!deletedPosPQ.isEmpty()) { 61 | List deletedPos = deletedPosPQ.poll(); 62 | List> newPositions = positionsList.get(deletedPos.get(deletedPos.size() - 1)); 63 | 64 | // update chosenRow 65 | chosenCols.add(deletedPos.get(0)); 66 | 67 | // update rowCounter 68 | for (int i = 1; i < deletedPos.size() - 1; i++) { 69 | rowCounter[deletedPos.get(i)] -= 1; 70 | } 71 | 72 | // recursively call search 73 | search(newPositions, rowCounter, chosenRows, chosenCols); 74 | 75 | // restore rowCounter 76 | for (int i = 1; i < deletedPos.size() - 1; i++) { 77 | rowCounter[deletedPos.get(i)] += 1; 78 | } 79 | 80 | // restore chosenRow 81 | chosenCols.remove(chosenCols.size() - 1); 82 | } 83 | 84 | // restore other variables 85 | rowCounter[minRow] = numOfPositions; 86 | // chosenCols.remove(chosenCols.size() - 1); 87 | chosenRows.remove(chosenRows.size() - 1); 88 | positions.set(minRow, colSet); 89 | } 90 | 91 | // find the row with min number of possible positions 92 | private int findMin(int[] rowCounter) { 93 | int idx = 0; 94 | int temp = rowCounter[0]; 95 | for (int i = 1; i < rowCounter.length; i++) { 96 | if (rowCounter[i] < temp) { 97 | temp = rowCounter[i]; 98 | idx = i; 99 | } 100 | } 101 | return idx; 102 | } 103 | 104 | 105 | 106 | // check the conflict when Queen is settled at selected position, return 107 | // the deleted positions 108 | private List> checkConflict(List> positions, 109 | int row, int col, List deletedPos) { 110 | List> newPositions = new ArrayList<>(); 111 | 112 | // the first element of deletedPos is the col (chosen col) 113 | deletedPos.add(col); 114 | for (int i = 0; i < positions.size(); i++) { 115 | Set rowPos = positions.get(i); 116 | Set newRowPos = new HashSet<>(); 117 | if (rowPos.size() > 0) { 118 | for (Integer cur_col : rowPos) { 119 | if (cur_col == col || Math.abs(cur_col - col) == Math.abs(i - row)) { 120 | deletedPos.add(i); 121 | } else { 122 | newRowPos.add(cur_col); 123 | } 124 | } 125 | } 126 | newPositions.add(newRowPos); 127 | } 128 | return newPositions; 129 | } 130 | 131 | // initialize the original possible positions 132 | private List> initializePos(int n) { 133 | List> pos = new ArrayList<>(); 134 | for (int i = 0; i < n; i++) { 135 | Set row = new HashSet<>(); 136 | for (int j = 0; j < n; j++) { 137 | row.add(j); 138 | } 139 | pos.add(row); 140 | } 141 | return pos; 142 | } 143 | 144 | // initialize rowCounter 145 | private int[] initializeCounter(int n) { 146 | int[] counter = new int[n]; 147 | for (int i = 0; i < n; i++) { 148 | counter[i] = n; 149 | } 150 | return counter; 151 | } 152 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | LeetCode Solution Code by Tiancheng Gong 3 | 4 | Covered Questions 5 | 6 | * Medium: 134 7 | * 011 Container With Most Water 8 | * 012 Integer to Roman 9 | * 016 3Sum Closest 10 | * 022 Generate Parentheses 11 | * 034 Search for a Range 12 | * 035 Search Insert Position 13 | * 039 Combination Sum 14 | * 046 Permutations 15 | * 048 Rotate Image 16 | * 053 Maximum Subarray 17 | * 059 Spiral Matrix II 18 | * 062 Unique Paths 19 | * 063 Unique Paths II 20 | * 064 Minimum Path Sum 21 | * 073 Set Matrix Zeroes 22 | * 074 Search a 2D Matrix 23 | * 075 Sort Colors 24 | * 077 Combinations 25 | * 078 Subsets 26 | * 080 Remove Duplicates from Sorted Array II 27 | * 081 Search in Rotated Sorted Array II 28 | * 086 Partition List 29 | * 089 Gray Code 30 | * 090 Subsets II 31 | * 092 Reverse Linked List II 32 | * 094 Binary Tree Inorder Traversal 33 | * 095 Unique Binary Search Trees II 34 | * 096 Unique Binary Search Trees 35 | * 103 Binary Tree Zigzag Level Order Traversal 36 | * 105 Construct Binary Tree from Preorder and Inorder Traversal 37 | * 106 Construct Binary Tree from Inorder and Postorder Traversal 38 | * 108 Convert Sorted Array to Binary Search Tree 39 | * 109 Convert Sorted List to Binary Search Tree 40 | * 113 Path Sum II 41 | * 114 Flatten Binary Tree to Linked List 42 | * 116 Populating Next Right Pointers in Each Node 43 | * 120 Triangle 44 | * 122 Best Time to Buy and Sell Stock II 45 | * 129 Sum Root to Leaf Numbers 46 | * 136 Single Number 47 | * 137 Single Number II 48 | * 142 Linked List Cycle II 49 | * 144 Binary Tree Preorder Traversal 50 | * 147 Insertion Sort List 51 | * 153 Find Minimum in Rotated Sorted Array 52 | * 156 Binary Tree Upside Down 53 | * 162 Find Peak Element 54 | * 163 Missing Ranges 55 | * 166 Fraction to Recurring Decimal 56 | * 167 Two Sum II - Input array is sorted 57 | * 173 Binary Search Tree Iterator 58 | * 199 Binary Tree Right Side View 59 | * 200 Number of Islands 60 | * 201 Bitwise AND of Numbers Range 61 | * 213 House Robber II 62 | * 215 Kth Largest Element in an Array 63 | * 216 Combination Sum III 64 | * 230 Kth Smallest Element in a BST 65 | * 238 Product of Array Except Self 66 | * 240 Search a 2D Matrix II 67 | * 241 Different Ways to Add Parentheses 68 | * 244 Shortest Word Distance II 69 | * 245 Shortest Word Distance III 70 | * 247 Strobogrammatic Number II 71 | * 250 Count Univalue Subtrees 72 | * 251 Flatten 2D Vector 73 | * 253 Meeting Rooms II 74 | * 254 Factor Combinations 75 | * 256 Paint House 76 | * 259 3Sum Smaller 77 | * 260 Single Number III 78 | * 261 Graph Valid Tree 79 | * 264 Ugly Number II 80 | * 268 Missing Number 81 | * 274 H-Index 82 | * 275 H-Index II 83 | * 277 Find the Celebrity 84 | * 279 Perfect Squares 85 | * 280 Wiggle Sort 86 | * 281 Zigzag Iterator 87 | * 284 Peeking Iterator 88 | * 285 Inorder Successor in BST 89 | * 286 Walls and Gates 90 | * 289 Game of Life 91 | * 294 Flip Game II 92 | * 298 Binary Tree Longest Consecutive Sequence 93 | * 300 Longest Increasing Subsequence 94 | * 309 Best Time to Buy and Sell Stock with Cooldown 95 | * 311 Sparse Matrix Multiplication 96 | * 313 Super Ugly Number 97 | * 314 Binary Tree Vertical Order Traversal 98 | * 318 Maximum Product of Word Lengths 99 | * 319 Bulb Switcher 100 | * 320 Generalized Abbreviation 101 | * 323 Number of Connected Components in an Undirected Graph 102 | * 328 Odd Even Linked List 103 | * 331 Verify Preorder Serialization of a Binary Tree 104 | * 333 Largest BST Subtree 105 | * 334 Increasing Triplet Subsequence 106 | * 337 House Robber III 107 | * 338 Counting Bits 108 | * 341 Flatten Nested List Iterator 109 | * 343 Integer Break 110 | * 347 Top K Frequent Elements 111 | * 348 Design Tic-Tac-Toe 112 | * 353 Design Snake Game 113 | * 357 Count Numbers with Unique Digits 114 | * 360 Sort Transformed Array 115 | * 361 Bomb Enemy 116 | * 362 Design Hit Counter 117 | * 364 Nested List Weight Sum II 118 | * 365 Water and Jug Problem 119 | * 366 Find Leaves of Binary Tree 120 | * 367 Valid Perfect Square 121 | * 368 Largest Divisible Subset 122 | * 369 Plus One Linked List 123 | * 370 Range Addition 124 | * 372 Super Pow 125 | * 373 Find K Pairs with Smallest Sums 126 | * 375 Guess Number Higher or Lower II 127 | * 376 Wiggle Subsequence 128 | * 377 Combination Sum IV 129 | * 378 Kth Smallest Element in a Sorted Matrix 130 | * 379 Design Phone Directory 131 | * 382 Linked List Random Node 132 | * 384 Shuffle an Array 133 | * 386 Lexicographical Numbers 134 | * 388 Longest Absolute File Path 135 | * 392 Is Subsequence 136 | * 393 UTF-8 Validation 137 | * 394 Decode String 138 | * 395 Longest Substring with At Least K Repeating Characters 139 | * 398 Random Pick Index 140 | * 421 Maximum XOR of Two Numbers in an Array 141 | 142 | * Hard: 23 143 | * 033 Search in Rotated Sorted Array 144 | * 051 N-Queens Complete 145 | * 051 N-Queens 146 | * 052 N-Queens 147 | * 123 Best Time to Buy and Sell Stock III 148 | * 145 Binary Tree Postorder Traversal 149 | * 146 LRU Cache 150 | * 159 Longest Substring with At Most Two Distinct Characters 151 | * 188 Best Time to Buy and Sell Stock IV 152 | * 265 Paint House II 153 | * 269 Alien Dictionary 154 | * 273 Integer to English Words 155 | * 287 Find the Duplicate Number 156 | * 291 Word Pattern II 157 | * 296 Best Meeting Point 158 | * 297 Serialize and Deserialize Binary Tree 159 | * 305 Number of Islands II 160 | * 312 Burst Balloons 161 | * 329 Longest Increasing Path in a Matrix 162 | * 340 Longest Substring with At Most K Distinct Characters 163 | * 380 Insert Delete GetRandom O(1) 164 | * 381 Insert Delete GetRandom O(1) - Duplicates allowed 165 | * 410 Split Array Largest Sum 166 | -------------------------------------------------------------------------------- /Hard/051 N-Queens.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public List> solveNQueens(int n) { 4 | 5 | // the list of the grids 6 | List> result = new ArrayList<>(); 7 | 8 | // chosen positions for Queens 9 | List chosenRows = new ArrayList<>(); 10 | List chosenCols = new ArrayList<>(); 11 | 12 | // the original possible positions for searching 13 | List> positions = initializePos(n); 14 | 15 | // rowCounter counts the number of posible positions on each row 16 | // rowCounter = [n, n, ..., n] (before searching) 17 | int[] rowCounter = initializeCounter(n); 18 | 19 | // sb = "........" n dots 20 | StringBuilder dotsSB = initializeSB(n); 21 | 22 | search(positions, rowCounter, chosenRows, chosenCols, result, dotsSB); 23 | 24 | return result; 25 | } 26 | 27 | 28 | // search 29 | private void search(List> positions, int[] rowCounter, 30 | List chosenRows, List chosenCols, 31 | List> result, StringBuilder dotsSB) { 32 | int minRow = findMin(rowCounter); 33 | int numOfPositions = rowCounter[minRow]; 34 | 35 | // dead end 36 | if (numOfPositions == 0) { 37 | return; 38 | } 39 | 40 | // N Quees are settled 41 | if (numOfPositions == Integer.MAX_VALUE) { 42 | addGrid(result, dotsSB, chosenRows, chosenCols); 43 | return; 44 | } 45 | 46 | // need further seaching 47 | rowCounter[minRow] = Integer.MAX_VALUE; 48 | Set colSet = positions.get(minRow); 49 | positions.set(minRow, new HashSet<>()); 50 | chosenRows.add(minRow); 51 | 52 | for (Integer col : colSet) { 53 | //update chosenCol 54 | chosenCols.add(col); 55 | 56 | // get deleted positions 57 | List deletedPos = checkConflict(positions, minRow, col); 58 | 59 | // update rowCounter 60 | for (int i = 0; i < deletedPos.size(); i += 2) { 61 | rowCounter[deletedPos.get(i)] -= 1; 62 | } 63 | 64 | // recursively call search 65 | search(positions, rowCounter, chosenRows, chosenCols, result, dotsSB); 66 | 67 | // restore deletedPos 68 | for (int i = 0; i < deletedPos.size(); i += 2) { 69 | positions.get(deletedPos.get(i)).add(deletedPos.get(i + 1)); 70 | } 71 | 72 | // restore rowCounter 73 | for (int i = 0; i < deletedPos.size(); i += 2) { 74 | rowCounter[deletedPos.get(i)] += 1; 75 | } 76 | 77 | // restore chosenCol 78 | chosenCols.remove(chosenCols.size() - 1); 79 | } 80 | 81 | 82 | // restore other variables 83 | rowCounter[minRow] = numOfPositions; 84 | chosenRows.remove(chosenRows.size() - 1); 85 | positions.set(minRow, colSet); 86 | } 87 | 88 | // find the row with min number of possible positions 89 | private int findMin(int[] rowCounter) { 90 | int idx = 0; 91 | int temp = rowCounter[0]; 92 | for (int i = 1; i < rowCounter.length; i++) { 93 | if (rowCounter[i] < temp) { 94 | temp = rowCounter[i]; 95 | idx = i; 96 | } 97 | } 98 | return idx; 99 | } 100 | 101 | 102 | // add new N-Queens grid to the result 103 | private void addGrid(List> result, StringBuilder dotsSB, 104 | List chosenRows, List chosenCols) { 105 | List grid = new ArrayList<>(); 106 | for (int i = 0; i < chosenRows.size(); i++) { 107 | grid.add(null); 108 | } 109 | for (int i = 0; i < chosenRows.size(); i++) { 110 | dotsSB.replace(chosenCols.get(i), chosenCols.get(i) + 1, "Q"); 111 | String temp = dotsSB.toString(); 112 | grid.set(chosenRows.get(i), temp); 113 | dotsSB.replace(chosenCols.get(i), chosenCols.get(i) + 1, "."); 114 | } 115 | result.add(grid); 116 | } 117 | 118 | // check the conflict when Queen is settled at selected position, return 119 | // the deleted positions 120 | private List checkConflict(List> positions, 121 | int row, int col) { 122 | 123 | List deletedPos = new ArrayList<>(); 124 | 125 | for (int i = 0; i < positions.size(); i++) { 126 | Set rowPos = positions.get(i); 127 | if (rowPos.size() > 0) { 128 | List tempList = new ArrayList<>(); 129 | for (Integer cur_col : rowPos) { 130 | if (cur_col == col || Math.abs(cur_col - col) == Math.abs(i - row)) { 131 | deletedPos.add(i); 132 | deletedPos.add(cur_col); 133 | tempList.add(cur_col); 134 | } 135 | } 136 | rowPos.removeAll(tempList); 137 | } 138 | } 139 | return deletedPos; 140 | } 141 | 142 | // initialize the original possible positions 143 | private List> initializePos(int n) { 144 | List> pos = new ArrayList<>(); 145 | for (int i = 0; i < n; i++) { 146 | Set row = new HashSet<>(); 147 | for (int j = 0; j < n; j++) { 148 | row.add(j); 149 | } 150 | pos.add(row); 151 | } 152 | return pos; 153 | } 154 | 155 | // initialize rowCounter 156 | private int[] initializeCounter(int n) { 157 | int[] counter = new int[n]; 158 | for (int i = 0; i < n; i++) { 159 | counter[i] = n; 160 | } 161 | return counter; 162 | } 163 | 164 | // initialize stringbuilder 165 | private StringBuilder initializeSB(int n) { 166 | StringBuilder sb = new StringBuilder(); 167 | for (int i = 0; i < n; i++) { 168 | sb.append('.'); 169 | } 170 | return sb; 171 | } 172 | } --------------------------------------------------------------------------------