├── 1 └── Two Sum │ └── Solution.kt ├── 3 └── Longest Substring Without Repeating Characters │ └── Solution.kt ├── 9 └── Palindrome Number │ └── Solution.kt ├── 11 └── Container With Most Water │ └── Solution.kt ├── 13 └── Roman to Integer │ └── Solution.kt ├── 15 └── 3Sum │ └── Solution.kt ├── 19 └── Remove Nth Node From End of List │ └── Solution.java ├── 21 └── Merge Two Sorted Lists │ └── Solution.java ├── 33 └── Search in Rotated Sorted Array │ └── Solution.kt ├── 34 └── Find First and Last Position of Element in Sorted Array │ └── Solution.kt ├── 35 └── Search Insert Position │ └── Solution.kt ├── 46 └── Permutations │ └── Solution.kt ├── 53 └── Maximum Subarray │ └── Solution.kt ├── 70 └── Climbing Stairs │ └── Solution.kt ├── 74 └── Search a 2D Matrix │ └── Solution.kt ├── 77 └── Combinations │ └── Solution.kt ├── 82 └── Remove Duplicates from Sorted List II │ └── Solution.java ├── 88 └── Merge Sorted Array │ └── Solution.kt ├── 116 └── Populating Next Right Pointers in Each Node │ └── Solution.java ├── 117 └── Populating Next Right Pointers in Each Node II │ └── Solution.java ├── 120 └── Triangle │ └── Solution.kt ├── 121 └── Solution.cpp ├── 130 └── Surrounded Regions │ └── Solution.kt ├── 136 └── Single Number │ └── main.kt ├── 153 └── Find Minimum in Rotated Sorted Array │ └── Solution.kt ├── 162 └── Find Peak Element │ └── Solution.kt ├── 167 └── Two Sum II - Input Array Is Sorted │ ├── Solution.java │ └── Solution.kt ├── 190 └── Reverse Bits │ └── Solution.java ├── 191 └── Number of 1 Bits │ └── Solution.java ├── 198 └── House Robber │ └── Solution.kt ├── 200 └── Number of Islands │ └── Solution.kt ├── 206 └── Reverse Linked List │ └── Solution.kt ├── 209 └── Minimum Size Subarray Sum │ └── Solution.kt ├── 217 └── Contains Duplicate │ └── Solution.kt ├── 231 └── Power of Two │ └── Solution.kt ├── 278 └── First Bad Version │ ├── solution.cpp │ └── solution.kt ├── 283 └── Move Zeroes │ ├── Solution.java │ └── Solution.kt ├── 344 └── Reverse String │ └── Solution.kt ├── 350 └── Solution.cpp ├── 438 └── Find All Anagrams in a String │ └── Solution.kt ├── 542 └── 01 Matrix │ └── Solution.java ├── 547 └── Number of Provinces │ └── Solution.java ├── 557 └── Reverse Words in a String III │ └── Solution.java ├── 567 └── Permutation in String │ ├── Solution.cpp │ └── Solution.kt ├── 572 └── Subtree of Another Tree │ └── Solution.kt ├── 617 └── Merge Two Binary Trees │ └── Solution.java ├── 704 └── Binary Search │ ├── Solution.java │ ├── solution.cpp │ └── solution.kt ├── 713 └── Subarray Product Less Than K │ └── Solution.java ├── 733 └── Flood Fill │ ├── Solution.java │ └── Solution.kt ├── 784 └── Letter Case Permutation │ └── Solution.kt ├── 797 └── All Paths From Source to Target │ └── Solution.java ├── 844 └── Backspace String Compare │ └── Solution.java ├── 876 └── Middle of the Linked List │ └── Solution.java ├── 994 └── Rotting Oranges │ └── Solution.java ├── 1091 └── Shortest Path in Binary Matrix │ └── Solution.kt ├── .idea ├── .gitignore ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── libraries │ └── KotlinJavaRuntime.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── 0196-delete-duplicate-emails ├── 0196-delete-duplicate-emails.sql ├── NOTES.md └── README.md ├── 1-Two Sum └── 1-Two Sum.java ├── 104-maximum-depth-of-binary-tree ├── 104-maximum-depth-of-binary-tree.java ├── NOTES.md └── README.md ├── 118-Pascal's Triangle └── 118-Pascal's Triangle.java ├── 121-Best Time to Buy and Sell Stock └── 121-Best Time to Buy and Sell Stock.java ├── 14-longest-common-prefix ├── 14-longest-common-prefix.kt ├── NOTES.md └── README.md ├── 175-combine-two-tables ├── 175-combine-two-tables.sql ├── NOTES.md └── README.md ├── 181-employees-earning-more-than-their-managers └── 181-employees-earning-more-than-their-managers.sql ├── 182-duplicate-emails ├── 182-duplicate-emails.sql └── README.md ├── 183-customers-who-never-order ├── 183-customers-who-never-order.sql ├── NOTES.md └── README.md ├── 189. Rotate Array └── solution.cpp ├── 2-add-two-numbers ├── 2-add-two-numbers.cpp ├── NOTES.md └── README.md ├── 20-valid-parentheses ├── 20-valid-parentheses.java └── NOTES.md ├── 217-Contains Duplicate └── 217-Contains Duplicate.java ├── 24-swap-nodes-in-pairs ├── 24-swap-nodes-in-pairs.cpp └── NOTES.md ├── 26-remove-duplicates-from-sorted-array ├── 26-remove-duplicates-from-sorted-array.kt ├── NOTES.md └── README.md ├── 27-remove-element ├── 27-remove-element.kt ├── NOTES.md └── README.md ├── 28-implement-strstr ├── 28-implement-strstr.java ├── NOTES.md └── README.md ├── 29-divide-two-integers ├── 29-divide-two-integers.java └── NOTES.md ├── 350-Intersection of Two Arrays II └── 350-Intersection of Two Arrays II.java ├── 462-minimum-moves-to-equal-array-elements-ii ├── 462-minimum-moves-to-equal-array-elements-ii.java └── NOTES.md ├── 53-Maximum-Subarray └── 53-Maximum-Subarray.java ├── 566-Reshape the Matrix └── 566-Reshape the Matrix.java ├── 58-length-of-last-word ├── 58-length-of-last-word.java ├── NOTES.md └── README.md ├── 66-plus-one ├── 66-plus-one.cpp ├── NOTES.md └── README.md ├── 67-add-binary ├── 67-add-binary.cpp ├── NOTES.md └── README.md ├── 695. Max Area of Island └── Solution.cpp ├── 7-reverse-integer ├── 7-reverse-integer.java ├── NOTES.md └── README.md ├── 83-remove-duplicates-from-sorted-list ├── 83-remove-duplicates-from-sorted-list.java ├── NOTES.md └── README.md ├── 977. Squares of a Sorted Array └── solution.cpp ├── LeetCode.iml └── out └── production └── LeetCode ├── 278 └── First Bad Version │ └── solution.cpp ├── 567 └── Permutation in String │ └── Solution.cpp ├── 704 └── Binary Search │ └── solution.cpp ├── 189. Rotate Array └── solution.cpp ├── 695. Max Area of Island └── Solution.cpp └── 977. Squares of a Sorted Array └── solution.cpp /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/libraries/KotlinJavaRuntime.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /0196-delete-duplicate-emails/0196-delete-duplicate-emails.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Please write a DELETE statement and DO NOT write a SELECT statement. 3 | Write your PL/SQL query statement below 4 | */ 5 | 6 | 7 | DELETE FROM Person WHERE Id NOT IN 8 | (SELECT Id FROM (SELECT MIN(Id) Id FROM Person GROUP BY Email) p); -------------------------------------------------------------------------------- /0196-delete-duplicate-emails/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /0196-delete-duplicate-emails/README.md: -------------------------------------------------------------------------------- 1 |

196. Delete Duplicate Emails

Easy


SQL Schema

Table: Person

2 | 3 |
+-------------+---------+
 4 | | Column Name | Type    |
 5 | +-------------+---------+
 6 | | id          | int     |
 7 | | email       | varchar |
 8 | +-------------+---------+
 9 | id is the primary key column for this table.
10 | Each row of this table contains an email. The emails will not contain uppercase letters.
11 | 
12 | 13 |

 

14 | 15 |

Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest id. Note that you are supposed to write a DELETE statement and not a SELECT one.

16 | 17 |

After running your script, the answer shown is the Person table. The driver will first compile and run your piece of code and then show the Person table. The final order of the Person table does not matter.

18 | 19 |

The query result format is in the following example.

20 | 21 |

 

22 |

Example 1:

23 | 24 |
Input: 
25 | Person table:
26 | +----+------------------+
27 | | id | email            |
28 | +----+------------------+
29 | | 1  | john@example.com |
30 | | 2  | bob@example.com  |
31 | | 3  | john@example.com |
32 | +----+------------------+
33 | Output: 
34 | +----+------------------+
35 | | id | email            |
36 | +----+------------------+
37 | | 1  | john@example.com |
38 | | 2  | bob@example.com  |
39 | +----+------------------+
40 | Explanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1.
41 | 
42 |
-------------------------------------------------------------------------------- /1-Two Sum/1-Two Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | Map complement = new HashMap<>(); 4 | for (int i = 0; i < nums.length; i++) { 5 | int temp = target - nums[i]; 6 | 7 | if (complement.containsKey(temp)) 8 | return new int[] {complement.get(temp), i}; 9 | 10 | complement.put(nums[i],i); 11 | } 12 | return null; 13 | } 14 | } -------------------------------------------------------------------------------- /1/ Two Sum/Solution.kt: -------------------------------------------------------------------------------- 1 | package `1`.` Two Sum` 2 | 3 | class Solution { 4 | fun twoSum(nums: IntArray, target: Int): IntArray { 5 | val numMap = HashMap() 6 | for (n in nums.withIndex()) { 7 | val comp = target - n.value 8 | if (numMap.containsKey(comp)) 9 | return intArrayOf(numMap[comp]!!, n.index) 10 | numMap.put(n.value, n.index) 11 | } 12 | return intArrayOf() 13 | } 14 | } -------------------------------------------------------------------------------- /104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public int maxDepth(TreeNode root) { 18 | if(root == null) return 0; 19 | 20 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 21 | } 22 | } -------------------------------------------------------------------------------- /104-maximum-depth-of-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /104-maximum-depth-of-binary-tree/README.md: -------------------------------------------------------------------------------- 1 |

104. Maximum Depth of Binary Tree

Easy


Given the root of a binary tree, return its maximum depth.

2 | 3 |

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: root = [3,9,20,null,null,15,7]
 9 | Output: 3
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: root = [1,null,2]
15 | Output: 2
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • The number of nodes in the tree is in the range [0, 104].
  • 23 |
  • -100 <= Node.val <= 100
  • 24 |
25 |
-------------------------------------------------------------------------------- /1091/ Shortest Path in Binary Matrix/Solution.kt: -------------------------------------------------------------------------------- 1 | package `1091`.` Shortest Path in Binary Matrix` 2 | 3 | import java.util.* 4 | 5 | class Solution { 6 | fun shortestPathBinaryMatrix(grid: Array): Int { 7 | val queue: Queue = LinkedList() 8 | val visited = Array(grid.size) { BooleanArray(grid[0].size) } 9 | 10 | if (grid[0][0] == 1) { 11 | return -1 12 | } 13 | queue.add(intArrayOf(0, 0)) 14 | visited[0][0] = true 15 | 16 | var level = 1 17 | while (queue.isNotEmpty()) { 18 | for (size in queue.indices) { 19 | val current = queue.poll() 20 | if (current[0] == grid.size - 1 && current[1] == grid[0].size - 1) { 21 | return level 22 | } 23 | for (index in 0..7) { 24 | val nextX = current[0] + deltaX[index] 25 | val nextY = current[1] + deltaY[index] 26 | if (inBound(grid, nextX, nextY) && !visited[nextX][nextY] && grid[nextX][nextY] == 0) { 27 | queue.offer(intArrayOf(nextX, nextY)) 28 | visited[nextX][nextY] = true 29 | } 30 | } 31 | } 32 | ++level 33 | } 34 | return -1 35 | } 36 | 37 | private val deltaX = intArrayOf(0, 0, -1, 1, 1, 1, -1, -1) 38 | private val deltaY = intArrayOf(-1, 1, 0, 0, -1, 1, -1, 1) 39 | private fun inBound( 40 | grid: Array, 41 | x: Int, 42 | y: Int 43 | ) = x >= 0 && y >= 0 && x < grid.size && y < grid[0].size 44 | } -------------------------------------------------------------------------------- /11/ Container With Most Water/Solution.kt: -------------------------------------------------------------------------------- 1 | package `11`.` Container With Most Water` 2 | 3 | class Solution { 4 | fun maxArea(height: IntArray): Int { 5 | var left = 0 6 | var right = height.size - 1 7 | var maxa = 0 8 | while (left < right) { 9 | maxa = Math.max(maxa, Math.min(height[left], height[right]) * (right - left)) 10 | if (height[left] > height[right]) { 11 | right-- 12 | } else { 13 | left++ 14 | } 15 | } 16 | return maxa 17 | } 18 | } -------------------------------------------------------------------------------- /116/ Populating Next Right Pointers in Each Node/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public Node connect(Node root) { 3 | dfs(root, null); 4 | return root; 5 | } 6 | 7 | void dfs(Node node, Node next) { 8 | if (node == null) return; 9 | if (node.left != null) { 10 | node.left.next = node.right; 11 | } 12 | if (node.right != null) { 13 | if (next != null) node.right.next = next.left; 14 | } 15 | dfs(node.left, node.right); 16 | dfs(node.right, next == null ? next : next.left); 17 | } 18 | } -------------------------------------------------------------------------------- /117/ Populating Next Right Pointers in Each Node II/Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | class Solution { 5 | Map map = new HashMap<>(); 6 | 7 | public Node connect(Node root) { 8 | hepler(root, 0); 9 | return root; 10 | } 11 | 12 | void hepler(Node node, int deepth) { 13 | if (node == null) return; 14 | if (map.containsKey(deepth)) { 15 | map.get(deepth).next = node; 16 | } 17 | map.put(deepth, node); 18 | hepler(node.left, deepth + 1); 19 | hepler(node.right, deepth + 1); 20 | } 21 | } 22 | 23 | 24 | class Node { 25 | public int val; 26 | public Node left; 27 | public Node right; 28 | public Node next; 29 | 30 | public Node() { 31 | } 32 | 33 | public Node(int _val) { 34 | val = _val; 35 | } 36 | 37 | public Node(int _val, Node _left, Node _right, Node _next) { 38 | val = _val; 39 | left = _left; 40 | right = _right; 41 | next = _next; 42 | } 43 | } -------------------------------------------------------------------------------- /118-Pascal's Triangle/118-Pascal's Triangle.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> generate(int numRows) { 3 | List> result = new ArrayList<>(); 4 | for (int i = 0; i < numRows; i++) { 5 | List resulti = new ArrayList<>(); 6 | for (int j = 0; j <= i; j++) { 7 | if (j == 0) { 8 | resulti.add(1); 9 | } else if (j == i) { 10 | resulti.add(1); 11 | } else { 12 | resulti.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j)); 13 | } 14 | } 15 | result.add(resulti); 16 | } 17 | return result; 18 | } 19 | } -------------------------------------------------------------------------------- /120/ Triangle/Solution.kt: -------------------------------------------------------------------------------- 1 | package `120`.` Triangle` 2 | 3 | class Solution { 4 | fun minimumTotal(triangle: List>): Int { 5 | val tri = triangle as List> 6 | (tri.lastIndex - 1 downTo 0).forEach { i -> 7 | (0 until tri[i].size).forEach { j -> 8 | tri[i][j] += minOf(tri[i + 1][j], tri[i + 1][j + 1]) 9 | } 10 | } 11 | 12 | return tri[0][0] 13 | } 14 | } -------------------------------------------------------------------------------- /121-Best Time to Buy and Sell Stock/121-Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | if (prices == null || prices.length < 2) 4 | return 0; 5 | 6 | int answer = 0; 7 | int min = prices[0]; 8 | for (int i = 0; i < prices.length; i++) { 9 | if (min < prices[i]) 10 | answer = Math.max(answer, prices[i] - min); 11 | min = Math.min(min, prices[i]); 12 | } 13 | return answer; 14 | } 15 | } -------------------------------------------------------------------------------- /121/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector &prices) { 4 | int max = 0, begin = 0, end = 0, delta = 0; 5 | 6 | for (int i = 0; i < prices.size(); i++) { 7 | end = i; 8 | delta = prices[end] - prices[begin]; 9 | 10 | if (delta <= 0) { 11 | begin = i; 12 | } 13 | if (delta > max) { 14 | max = delta; 15 | } 16 | } 17 | return max; 18 | } 19 | }; -------------------------------------------------------------------------------- /13/ Roman to Integer/Solution.kt: -------------------------------------------------------------------------------- 1 | package `13`.` Roman to Integer` 2 | 3 | class Solution { 4 | private val Rm2I = mapOf( 5 | 'I' to 1, 'V' to 5, 6 | 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000 7 | ) 8 | 9 | fun romanToInt(s: String): Int { 10 | var res = 0 11 | var i = 0 12 | while (i < s.length) { 13 | if (i == s.length - 1) { 14 | res += Rm2I[s[i]]!! 15 | break 16 | } 17 | if (Rm2I[s[i]]!! < Rm2I[s[i + 1]]!!) { 18 | res += Rm2I[s[i + 1]]!! - Rm2I[s[i]]!! 19 | i += 2 20 | } else { 21 | res += Rm2I[s[i]]!! 22 | i++ 23 | } 24 | } 25 | return res 26 | } 27 | } -------------------------------------------------------------------------------- /130/ Surrounded Regions/Solution.kt: -------------------------------------------------------------------------------- 1 | package `130`.` Surrounded Regions` 2 | 3 | 4 | class Solution { 5 | fun solve(board: Array): Unit { 6 | if (board.isEmpty()) return 7 | val row = board.size 8 | val col = board[0].size 9 | for (i in (0 until row)) { 10 | check(board, i, 0) 11 | check(board, i, col - 1) 12 | } 13 | 14 | for (i in (1 until col - 1)) { 15 | check(board, 0, i) 16 | check(board, row - 1, i) 17 | } 18 | 19 | for (i in 0 until row) { 20 | for (j in 0 until col) { 21 | if (board[i][j] == '#') board[i][j] = 'O' 22 | else board[i][j] = 'X' 23 | } 24 | } 25 | 26 | } 27 | 28 | private val direct = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) 29 | private fun check(board: Array, i: Int, j: Int) { 30 | if (board[i][j] == 'O') { 31 | board[i][j] = '#' 32 | for (d in direct) { 33 | val x = i + d[0] 34 | val y = j + d[1] 35 | if (x in 0..board.lastIndex && y in 0..board[0].lastIndex) 36 | check(board, x, y) 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /136/ Single Number/main.kt: -------------------------------------------------------------------------------- 1 | package `136`.` Single Number` 2 | 3 | class Solution { 4 | fun singleNumber(nums: IntArray): Int { 5 | var res = 0 6 | (0 until nums.size).forEach { 7 | res = res xor nums[it] 8 | } 9 | return res 10 | } 11 | } -------------------------------------------------------------------------------- /14-longest-common-prefix/14-longest-common-prefix.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun longestCommonPrefix(strs: Array): String { 3 | if (strs.size == 0) return "" 4 | var len = 0 5 | var res = "" 6 | for (j in 0 until strs[0].length) { 7 | val c = strs[0][j] 8 | for (i in 1 until strs.size) { 9 | if (j >= strs[i].length || strs[i][j] != c) { 10 | return res 11 | } 12 | } 13 | res += c 14 | } 15 | return res 16 | } 17 | } -------------------------------------------------------------------------------- /14-longest-common-prefix/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /14-longest-common-prefix/README.md: -------------------------------------------------------------------------------- 1 |

14. Longest Common Prefix

Easy


Write a function to find the longest common prefix string amongst an array of strings.

2 | 3 |

If there is no common prefix, return an empty string "".

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: strs = ["flower","flow","flight"]
 9 | Output: "fl"
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: strs = ["dog","racecar","car"]
15 | Output: ""
16 | Explanation: There is no common prefix among the input strings.
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • 1 <= strs.length <= 200
  • 24 |
  • 0 <= strs[i].length <= 200
  • 25 |
  • strs[i] consists of only lowercase English letters.
  • 26 |
27 |
-------------------------------------------------------------------------------- /15/ 3Sum/Solution.kt: -------------------------------------------------------------------------------- 1 | package `15`.` 3Sum` 2 | 3 | class Solution { 4 | fun threeSum(nums: IntArray): List> { 5 | nums.sort() 6 | val res = mutableListOf>() 7 | var x: Int 8 | var y: Int 9 | for (i in 0 until nums.size - 2) { 10 | if (i > 0 && nums[i] == nums[i - 1]) continue 11 | x = i + 1 12 | y = nums.size - 1 13 | 14 | while (x < y) { 15 | val temp = nums[x] + nums[y] + nums[i] 16 | if (temp == 0) { 17 | res.add(listOf(nums[i], nums[x], nums[y])) 18 | 19 | while (x < y && nums[x] == nums[x + 1]) x++ 20 | while (x < y && nums[y] == nums[y - 1]) y-- 21 | x++ 22 | y-- 23 | } else if (temp > 0) { 24 | y-- 25 | } else { 26 | x++ 27 | } 28 | } 29 | } 30 | return res 31 | } 32 | } -------------------------------------------------------------------------------- /153/ Find Minimum in Rotated Sorted Array/Solution.kt: -------------------------------------------------------------------------------- 1 | package `153`.` Find Minimum in Rotated Sorted Array` 2 | 3 | class Solution { 4 | fun findMin(nums: IntArray): Int { 5 | var left = 0 6 | var right = nums.size - 1 7 | 8 | while (left + 1 < right) { 9 | val mid = left + (right - left) / 2 10 | when { 11 | nums[mid] >= nums[0] -> { 12 | if (nums[mid] < nums[right]) { 13 | return nums[0] 14 | } else { 15 | left = mid 16 | } 17 | } 18 | 19 | nums[mid] <= nums[right] -> { 20 | right = mid 21 | } 22 | } 23 | } 24 | return minOf(nums[left], nums[right]) 25 | } 26 | } -------------------------------------------------------------------------------- /162/ Find Peak Element/Solution.kt: -------------------------------------------------------------------------------- 1 | package `162`.` Find Peak Element` 2 | 3 | class Solution { 4 | fun findPeakElement(nums: IntArray): Int { 5 | var left = 0 6 | var right = nums.size - 1 7 | 8 | while (left + 1 < right) { 9 | val mid = left + (right - left) / 2 10 | when { 11 | nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1] -> return mid 12 | nums[mid - 1] < nums[mid] -> left = mid 13 | else -> right = mid 14 | } 15 | } 16 | 17 | return when { 18 | nums[left] > nums[right] -> left 19 | else -> right 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /167/ Two Sum II - Input Array Is Sorted/Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | class Solution { 5 | public int[] twoSum(int[] numbers, int target) { 6 | Map store = new HashMap<>(); 7 | for (int i = 0; i < numbers.length; i++) { 8 | int num = numbers[i]; 9 | if (store.containsKey(target - num)) { 10 | return new int[]{store.get(target - num) + 1, i + 1}; 11 | } 12 | store.put(num, i); 13 | } 14 | return new int[]{}; 15 | } 16 | } -------------------------------------------------------------------------------- /167/ Two Sum II - Input Array Is Sorted/Solution.kt: -------------------------------------------------------------------------------- 1 | package `167`.` Two Sum II - Input Array Is Sorted` 2 | 3 | class Solution { 4 | fun twoSum(numbers: IntArray, target: Int): IntArray { 5 | 6 | numbers.forEachIndexed { i, num -> 7 | val v = numbers.binarySearch(target - num, i + 1) 8 | if (v > 0) { 9 | return intArrayOf(i + 1, v + 1) 10 | } 11 | } 12 | return intArrayOf() 13 | } 14 | } -------------------------------------------------------------------------------- /175-combine-two-tables/175-combine-two-tables.sql: -------------------------------------------------------------------------------- 1 | /* Write your PL/SQL query statement below */ 2 | SELECT p.FirstName, p.LastName, addr.City, addr.State 3 | FROM Person p 4 | LEFT JOIN Address addr 5 | ON p.PersonId = addr.PersonId; -------------------------------------------------------------------------------- /175-combine-two-tables/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /175-combine-two-tables/README.md: -------------------------------------------------------------------------------- 1 |

175. Combine Two Tables

Easy


Table: Person

2 | 3 |
+-------------+---------+
 4 | | Column Name | Type    |
 5 | +-------------+---------+
 6 | | personId    | int     |
 7 | | lastName    | varchar |
 8 | | firstName   | varchar |
 9 | +-------------+---------+
10 | personId is the primary key column for this table.
11 | This table contains information about the ID of some persons and their first and last names.
12 | 
13 | 14 |

 

15 | 16 |

Table: Address

17 | 18 |
+-------------+---------+
19 | | Column Name | Type    |
20 | +-------------+---------+
21 | | addressId   | int     |
22 | | personId    | int     |
23 | | city        | varchar |
24 | | state       | varchar |
25 | +-------------+---------+
26 | addressId is the primary key column for this table.
27 | Each row of this table contains information about the city and state of one person with ID = PersonId.
28 | 
29 | 30 |

 

31 | 32 |

Write an SQL query to report the first name, last name, city, and state of each person in the Person table. If the address of a personId is not present in the Address table, report null instead.

33 | 34 |

Return the result table in any order.

35 | 36 |

The query result format is in the following example.

37 | 38 |

 

39 |

Example 1:

40 | 41 |
Input: 
42 | Person table:
43 | +----------+----------+-----------+
44 | | personId | lastName | firstName |
45 | +----------+----------+-----------+
46 | | 1        | Wang     | Allen     |
47 | | 2        | Alice    | Bob       |
48 | +----------+----------+-----------+
49 | Address table:
50 | +-----------+----------+---------------+------------+
51 | | addressId | personId | city          | state      |
52 | +-----------+----------+---------------+------------+
53 | | 1         | 2        | New York City | New York   |
54 | | 2         | 3        | Leetcode      | California |
55 | +-----------+----------+---------------+------------+
56 | Output: 
57 | +-----------+----------+---------------+----------+
58 | | firstName | lastName | city          | state    |
59 | +-----------+----------+---------------+----------+
60 | | Allen     | Wang     | Null          | Null     |
61 | | Bob       | Alice    | New York City | New York |
62 | +-----------+----------+---------------+----------+
63 | Explanation: 
64 | There is no address in the address table for the personId = 1 so we return null in their city and state.
65 | addressId = 1 contains information about the address of personId = 2.
66 | 
67 |
-------------------------------------------------------------------------------- /181-employees-earning-more-than-their-managers/181-employees-earning-more-than-their-managers.sql: -------------------------------------------------------------------------------- 1 | /* Write your PL/SQL query statement below */ 2 | 3 | select e.name as Employee 4 | from Employee e, Employee m 5 | where e.Salary > m.Salary 6 | and e.ManagerId = m.Id -------------------------------------------------------------------------------- /182-duplicate-emails/182-duplicate-emails.sql: -------------------------------------------------------------------------------- 1 | /* Write your PL/SQL query statement below */ 2 | select email as Email from Person GROUP BY Email having count(id) > 1 -------------------------------------------------------------------------------- /182-duplicate-emails/README.md: -------------------------------------------------------------------------------- 1 |

182. Duplicate Emails

Easy


Table: Person

2 | 3 |
+-------------+---------+
 4 | | Column Name | Type    |
 5 | +-------------+---------+
 6 | | id          | int     |
 7 | | email       | varchar |
 8 | +-------------+---------+
 9 | id is the primary key column for this table.
10 | Each row of this table contains an email. The emails will not contain uppercase letters.
11 | 
12 | 13 |

 

14 | 15 |

Write an SQL query to report all the duplicate emails.

16 | 17 |

Return the result table in any order.

18 | 19 |

The query result format is in the following example.

20 | 21 |

 

22 |

Example 1:

23 | 24 |
Input: 
25 | Person table:
26 | +----+---------+
27 | | id | email   |
28 | +----+---------+
29 | | 1  | a@b.com |
30 | | 2  | c@d.com |
31 | | 3  | a@b.com |
32 | +----+---------+
33 | Output: 
34 | +---------+
35 | | Email   |
36 | +---------+
37 | | a@b.com |
38 | +---------+
39 | Explanation: a@b.com is repeated two times.
40 | 
41 |
-------------------------------------------------------------------------------- /183-customers-who-never-order/183-customers-who-never-order.sql: -------------------------------------------------------------------------------- 1 | /* Write your PL/SQL query statement below */ 2 | 3 | SELECT Name AS Customers FROM Customers 4 | LEFT JOIN Orders ON Customers.Id = Orders.CustomerId 5 | WHERE Orders.CustomerId IS NULL; -------------------------------------------------------------------------------- /183-customers-who-never-order/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /183-customers-who-never-order/README.md: -------------------------------------------------------------------------------- 1 |

183. Customers Who Never Order

Easy


Table: Customers

2 | 3 |
+-------------+---------+
 4 | | Column Name | Type    |
 5 | +-------------+---------+
 6 | | id          | int     |
 7 | | name        | varchar |
 8 | +-------------+---------+
 9 | id is the primary key column for this table.
10 | Each row of this table indicates the ID and name of a customer.
11 | 
12 | 13 |

 

14 | 15 |

Table: Orders

16 | 17 |
+-------------+------+
18 | | Column Name | Type |
19 | +-------------+------+
20 | | id          | int  |
21 | | customerId  | int  |
22 | +-------------+------+
23 | id is the primary key column for this table.
24 | customerId is a foreign key of the ID from the Customers table.
25 | Each row of this table indicates the ID of an order and the ID of the customer who ordered it.
26 | 
27 | 28 |

 

29 | 30 |

Write an SQL query to report all customers who never order anything.

31 | 32 |

Return the result table in any order.

33 | 34 |

The query result format is in the following example.

35 | 36 |

 

37 |

Example 1:

38 | 39 |
Input: 
40 | Customers table:
41 | +----+-------+
42 | | id | name  |
43 | +----+-------+
44 | | 1  | Joe   |
45 | | 2  | Henry |
46 | | 3  | Sam   |
47 | | 4  | Max   |
48 | +----+-------+
49 | Orders table:
50 | +----+------------+
51 | | id | customerId |
52 | +----+------------+
53 | | 1  | 3          |
54 | | 2  | 1          |
55 | +----+------------+
56 | Output: 
57 | +-----------+
58 | | Customers |
59 | +-----------+
60 | | Henry     |
61 | | Max       |
62 | +-----------+
63 | 
64 |
-------------------------------------------------------------------------------- /189. Rotate Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector &nums, int k) { 4 | int sz = nums.size(); 5 | int step = k % sz; 6 | for (int i = 0; i < (sz - step) / 2; ++i) { 7 | swap(nums[i], nums[sz - step - 1 - i]); 8 | } 9 | for (int i = 0; i < step / 2; ++i) { 10 | swap(nums[sz - step + i], nums[sz - 1 - i]); 11 | } 12 | for (int i = 0; i < sz / 2; ++i) { 13 | swap(nums[i], nums[sz - 1 - i]); 14 | } 15 | } 16 | }; -------------------------------------------------------------------------------- /19/ Remove Nth Node From End of List/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode removeNthFromEnd(ListNode head, int n) { 3 | 4 | ListNode front = head; 5 | for (int i = 0; i < n; ++i) { 6 | front = front.next; 7 | } 8 | 9 | if (front == null) { 10 | ListNode res = head.next; 11 | head.next = null; 12 | return res; 13 | } 14 | 15 | ListNode back = head; 16 | while (front.next != null) { 17 | front = front.next; 18 | back = back.next; 19 | } 20 | 21 | 22 | ListNode removal = back.next; 23 | back.next = removal.next; 24 | removal.next = null; 25 | return head; 26 | } 27 | } -------------------------------------------------------------------------------- /190/ Reverse Bits/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // you need treat n as an unsigned value 3 | public int reverseBits(int n) { 4 | int res = 0; 5 | int t = 31; 6 | while (t >= 0) { 7 | int i = n & 1; 8 | res += i << t; 9 | n = n >> 1; 10 | t--; 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /191/ Number of 1 Bits/Solution.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | // you need to treat n as an unsigned value 4 | public int hammingWeight(int n) { 5 | int res = 0; 6 | int t; 7 | while ((t = n & (-n)) != 0) { 8 | res++; 9 | n -= t; 10 | } 11 | return res; 12 | } 13 | } -------------------------------------------------------------------------------- /198/ House Robber/Solution.kt: -------------------------------------------------------------------------------- 1 | package `198`.` House Robber` 2 | 3 | class Solution { 4 | var memo: MutableList = MutableList(0) { -1 } 5 | fun rob(nums: IntArray): Int { 6 | memo.addAll(MutableList(nums.size) { -1 }) 7 | return tryRob(nums, 0) 8 | } 9 | 10 | private fun tryRob(nums: IntArray, index: Int): Int { 11 | if (index >= nums.size) 12 | return 0 13 | if (memo[index] != -1) 14 | return memo[index] 15 | 16 | var res = 0 17 | (index until nums.size).forEach { 18 | res = maxOf(res, nums[it] + tryRob(nums, it + 2)) 19 | } 20 | memo[index] = res 21 | return res 22 | } 23 | } -------------------------------------------------------------------------------- /2-add-two-numbers/2-add-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 14 | int carry = 0; 15 | ListNode* dummy = new ListNode(0); 16 | ListNode* l = dummy; 17 | while (l1 || l2) { 18 | int sum = carry; 19 | if (l1) { 20 | sum += l1->val; 21 | l1 = l1->next; 22 | } 23 | if (l2) { 24 | sum += l2->val; 25 | l2 = l2->next; 26 | } 27 | 28 | if (sum > 9) { 29 | carry = 1; 30 | sum = sum % 10; 31 | } 32 | else { 33 | carry = 0; 34 | } 35 | 36 | l->next = new ListNode(sum); 37 | l = l->next; 38 | } 39 | 40 | if (carry) { 41 | l->next = new ListNode(carry); 42 | } 43 | 44 | return dummy->next; 45 | } 46 | }; -------------------------------------------------------------------------------- /2-add-two-numbers/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /2-add-two-numbers/README.md: -------------------------------------------------------------------------------- 1 |

2. Add Two Numbers

Medium


You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

2 | 3 |

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: l1 = [2,4,3], l2 = [5,6,4]
 9 | Output: [7,0,8]
10 | Explanation: 342 + 465 = 807.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: l1 = [0], l2 = [0]
16 | Output: [0]
17 | 
18 | 19 |

Example 3:

20 | 21 |
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
22 | Output: [8,9,9,9,0,0,0,1]
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • The number of nodes in each linked list is in the range [1, 100].
  • 30 |
  • 0 <= Node.val <= 9
  • 31 |
  • It is guaranteed that the list represents a number that does not have leading zeros.
  • 32 |
33 |
-------------------------------------------------------------------------------- /20-valid-parentheses/20-valid-parentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValid(String s) { 3 | Deque stack = new ArrayDeque<>(); 4 | 5 | for (int i = 0; i < s.length(); i++) { 6 | if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { 7 | stack.push(s.charAt(i)); 8 | } 9 | else { 10 | if(!stack.isEmpty()) { 11 | char c = stack.pop(); 12 | if((c=='(' && s.charAt(i) == ')') || (c=='[' && s.charAt(i) == ']') || 13 | (c=='{' && s.charAt(i) == '}')) continue; 14 | } 15 | return false; 16 | } 17 | } 18 | return stack.isEmpty(); 19 | } 20 | } -------------------------------------------------------------------------------- /20-valid-parentheses/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /200/ Number of Islands/Solution.kt: -------------------------------------------------------------------------------- 1 | package `200`.` Number of Islands` 2 | 3 | class Solution { 4 | 5 | private val direct = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) 6 | private var rows = 0 7 | private var cols = 0 8 | private var visited = Array(rows, { BooleanArray(cols) }) 9 | 10 | 11 | fun numIslands(grid: Array): Int { 12 | rows = grid.size 13 | if (rows == 0) return 0 14 | cols = grid[0].size 15 | visited = Array(rows, { BooleanArray(cols) }) 16 | 17 | var res = 0 18 | 19 | (0 until rows).forEach { i -> 20 | (0 until cols).forEach { j -> 21 | if (grid[i][j] == '1' && !visited[i][j]) { 22 | res++ 23 | dfs(grid, i, j) 24 | } 25 | } 26 | } 27 | 28 | return res 29 | 30 | } 31 | 32 | 33 | private fun dfs(grid: Array, x: Int, y: Int) { 34 | visited[x][y] = true 35 | 36 | (0 until 4).forEach { i -> 37 | val newX = x + direct[i][0] 38 | val newY = y + direct[i][1] 39 | if (inArea(newX, newY) && grid[newX][newY] == '1' && visited[newX][newY]) { 40 | dfs(grid, newX, newY) 41 | } 42 | } 43 | } 44 | 45 | private fun inArea(x: Int, y: Int): Boolean { 46 | return x in (0 until rows) && y in (0 until cols) 47 | } 48 | } -------------------------------------------------------------------------------- /206/ Reverse Linked List/Solution.kt: -------------------------------------------------------------------------------- 1 | package `206`.` Reverse Linked List` 2 | 3 | class Solution { 4 | fun reverseList(head: ListNode?): ListNode? { 5 | var p = head 6 | var q = head?.next 7 | var h = head 8 | h?.next = null 9 | while (q != null) { 10 | p = q 11 | q = q.next 12 | p.next = h 13 | h = p 14 | } 15 | return h 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /209/ Minimum Size Subarray Sum/Solution.kt: -------------------------------------------------------------------------------- 1 | package `209`.` Minimum Size Subarray Sum` 2 | 3 | class Solution { 4 | fun minSubArrayLen(s: Int, nums: IntArray): Int { 5 | var l = 0 6 | var r = -1 7 | var sum = 0 8 | var res = nums.size + 1 9 | 10 | while (l < nums.size) { 11 | if (r + 1 < nums.size && sum < s) sum += nums[++r] 12 | else sum -= nums[l++] 13 | 14 | if (sum >= s) res = minOf(r - l + 1, res) 15 | } 16 | return if (res != nums.size + 1) res else 0 17 | } 18 | } -------------------------------------------------------------------------------- /21/ Merge Two Sorted Lists/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 3 | ListNode fakeHead = new ListNode(); 4 | ListNode writer = fakeHead; 5 | 6 | while (l1 != null && l2 != null) { 7 | if (l1.val < l2.val) { 8 | writer.next = l1; 9 | l1 = l1.next; 10 | } else { 11 | writer.next = l2; 12 | l2 = l2.next; 13 | } 14 | writer = writer.next; 15 | } 16 | if (l1 != null) { 17 | writer.next = l1; 18 | } 19 | if (l2 != null) { 20 | writer.next = l2; 21 | } 22 | 23 | ListNode res = fakeHead.next; 24 | fakeHead.next = null; 25 | return res; 26 | 27 | } 28 | } -------------------------------------------------------------------------------- /217-Contains Duplicate/217-Contains Duplicate.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean containsDuplicate(int[] nums) { 3 | Set set = new HashSet<>(); 4 | for(int i=0; i < nums.length; i++) { 5 | set.add(nums[i]); 6 | } 7 | return nums.length != set.size(); 8 | } 9 | } -------------------------------------------------------------------------------- /217/ Contains Duplicate/Solution.kt: -------------------------------------------------------------------------------- 1 | package `217`.` Contains Duplicate` 2 | 3 | class Solution { 4 | fun containsDuplicate(nums: IntArray): Boolean { 5 | return nums.toHashSet().size < nums.size 6 | } 7 | } -------------------------------------------------------------------------------- /231/ Power of Two/Solution.kt: -------------------------------------------------------------------------------- 1 | package `231`.` Power of Two` 2 | 3 | class Solution { 4 | fun isPowerOfTwo(n: Int): Boolean { 5 | return n > 0 && (n and n - 1 == 0) 6 | } 7 | } -------------------------------------------------------------------------------- /24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* swapPairs(ListNode* head) { 14 | if(!head || !head->next) 15 | return head; 16 | 17 | ListNode* next = head->next; 18 | head->next = swapPairs(head->next->next); 19 | next->next = head; 20 | 21 | return next; 22 | } 23 | }; -------------------------------------------------------------------------------- /24-swap-nodes-in-pairs/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /26-remove-duplicates-from-sorted-array/26-remove-duplicates-from-sorted-array.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun removeDuplicates(nums: IntArray): Int { 3 | var cnt = if (nums.size > 0) 1 else 0 4 | 5 | for (i in 1 until nums.size) { 6 | if(nums[i] == nums[i-1]) continue 7 | nums[cnt] = nums[i] 8 | cnt++ 9 | } 10 | return cnt 11 | } 12 | } -------------------------------------------------------------------------------- /26-remove-duplicates-from-sorted-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /26-remove-duplicates-from-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

26. Remove Duplicates from Sorted Array

Easy


Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

2 | 3 |

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

4 | 5 |

Return k after placing the final result in the first k slots of nums.

6 | 7 |

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

8 | 9 |

Custom Judge:

10 | 11 |

The judge will test your solution with the following code:

12 | 13 |
int[] nums = [...]; // Input array
14 | int[] expectedNums = [...]; // The expected answer with correct length
15 | 
16 | int k = removeDuplicates(nums); // Calls your implementation
17 | 
18 | assert k == expectedNums.length;
19 | for (int i = 0; i < k; i++) {
20 |     assert nums[i] == expectedNums[i];
21 | }
22 | 
23 | 24 |

If all assertions pass, then your solution will be accepted.

25 | 26 |

 

27 |

Example 1:

28 | 29 |
Input: nums = [1,1,2]
30 | Output: 2, nums = [1,2,_]
31 | Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
32 | It does not matter what you leave beyond the returned k (hence they are underscores).
33 | 
34 | 35 |

Example 2:

36 | 37 |
Input: nums = [0,0,1,1,1,2,2,3,3,4]
38 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
39 | Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
40 | It does not matter what you leave beyond the returned k (hence they are underscores).
41 | 
42 | 43 |

 

44 |

Constraints:

45 | 46 |
    47 |
  • 1 <= nums.length <= 3 * 104
  • 48 |
  • -100 <= nums[i] <= 100
  • 49 |
  • nums is sorted in non-decreasing order.
  • 50 |
51 |
-------------------------------------------------------------------------------- /27-remove-element/27-remove-element.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun removeElement(nums: IntArray, `val`: Int): Int { 3 | var res =0 4 | for (i in 0 until nums.size) { 5 | if(nums[i] != `val`) { 6 | nums[res++] = nums[i] 7 | } 8 | } 9 | return res 10 | } 11 | } -------------------------------------------------------------------------------- /27-remove-element/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /27-remove-element/README.md: -------------------------------------------------------------------------------- 1 |

27. Remove Element

Easy


Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

2 | 3 |

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

4 | 5 |

Return k after placing the final result in the first k slots of nums.

6 | 7 |

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

8 | 9 |

Custom Judge:

10 | 11 |

The judge will test your solution with the following code:

12 | 13 |
int[] nums = [...]; // Input array
14 | int val = ...; // Value to remove
15 | int[] expectedNums = [...]; // The expected answer with correct length.
16 |                             // It is sorted with no values equaling val.
17 | 
18 | int k = removeElement(nums, val); // Calls your implementation
19 | 
20 | assert k == expectedNums.length;
21 | sort(nums, 0, k); // Sort the first k elements of nums
22 | for (int i = 0; i < actualLength; i++) {
23 |     assert nums[i] == expectedNums[i];
24 | }
25 | 
26 | 27 |

If all assertions pass, then your solution will be accepted.

28 | 29 |

 

30 |

Example 1:

31 | 32 |
Input: nums = [3,2,2,3], val = 3
33 | Output: 2, nums = [2,2,_,_]
34 | Explanation: Your function should return k = 2, with the first two elements of nums being 2.
35 | It does not matter what you leave beyond the returned k (hence they are underscores).
36 | 
37 | 38 |

Example 2:

39 | 40 |
Input: nums = [0,1,2,2,3,0,4,2], val = 2
41 | Output: 5, nums = [0,1,4,0,3,_,_,_]
42 | Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
43 | Note that the five elements can be returned in any order.
44 | It does not matter what you leave beyond the returned k (hence they are underscores).
45 | 
46 | 47 |

 

48 |

Constraints:

49 | 50 |
    51 |
  • 0 <= nums.length <= 100
  • 52 |
  • 0 <= nums[i] <= 50
  • 53 |
  • 0 <= val <= 100
  • 54 |
55 |
-------------------------------------------------------------------------------- /278/ First Bad Version/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstBadVersion(int n) { 4 | int l = 1, r = n; 5 | while (l < r) { 6 | int mid = l + (r - l) / 2; 7 | if (isBadVersion(mid)) { 8 | r = mid; 9 | } else { 10 | l = mid + 1; 11 | } 12 | } 13 | return r; 14 | } 15 | }; 16 | 17 | -------------------------------------------------------------------------------- /278/ First Bad Version/solution.kt: -------------------------------------------------------------------------------- 1 | package `278`.` First Bad Version` 2 | 3 | class Solution: VersionControl() { 4 | override fun firstBadVersion(n: Int) : Int { 5 | if (n == 1) { 6 | return 1 7 | } 8 | var begin = 1 9 | var end = n 10 | while (begin < end) { 11 | val mid = begin + (end - begin) / 2 12 | if (isBadVersion(mid)) { 13 | end = mid 14 | } else if (!isBadVersion(mid) && isBadVersion(mid + 1)) { 15 | return mid + 1 16 | } else 17 | begin = mid + 1 18 | } 19 | 20 | if (begin!=n && isBadVersion(begin)) { 21 | return begin 22 | } 23 | return -1 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /28-implement-strstr/28-implement-strstr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | if (needle == null || needle.length() == 0) { 4 | return 0; 5 | } 6 | 7 | if(haystack == null || haystack.length() == 0) { 8 | return -1; 9 | } 10 | 11 | for(int i = 0; i < haystack.length() - needle.length() + 1; i++ ) { 12 | int j; 13 | for(j=0; j < needle.length(); j++) { 14 | if (haystack.charAt(i+ j) != needle.charAt(j)) { 15 | break; 16 | } 17 | } 18 | if(j == needle.length()) { 19 | return i; 20 | } 21 | } 22 | return -1; 23 | } 24 | } -------------------------------------------------------------------------------- /28-implement-strstr/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /28-implement-strstr/README.md: -------------------------------------------------------------------------------- 1 |

28. Implement strStr()

Easy


Implement strStr().

2 | 3 |

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

4 | 5 |

Clarification:

6 | 7 |

What should we return when needle is an empty string? This is a great question to ask during an interview.

8 | 9 |

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

10 | 11 |

 

12 |

Example 1:

13 | 14 |
Input: haystack = "hello", needle = "ll"
15 | Output: 2
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: haystack = "aaaaa", needle = "bba"
21 | Output: -1
22 | 
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • 1 <= haystack.length, needle.length <= 104
  • 29 |
  • haystack and needle consist of only lowercase English characters.
  • 30 |
31 |
-------------------------------------------------------------------------------- /283/ Move Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void moveZeroes(int[] nums) { 3 | int k = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] != 0) { 6 | if (k != 0) { 7 | nums[i - k] = nums[i]; 8 | nums[i] = 0; 9 | } 10 | } else { 11 | k++; 12 | } 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /283/ Move Zeroes/Solution.kt: -------------------------------------------------------------------------------- 1 | package `283`.` Move Zeroes` 2 | 3 | class Solution { 4 | fun moveZeroes(nums: IntArray): Unit { 5 | var zeroes = 0 6 | nums.indices.forEach { 7 | when (nums[it]) { 8 | 0 -> zeroes++ 9 | else -> { 10 | if (zeroes != 0) { 11 | nums[it - zeroes] = nums[it] 12 | nums[it] = 0 13 | } 14 | } 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /29-divide-two-integers/29-divide-two-integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int divide(int dividend, int divisor) { 3 | //check if negative answer 4 | boolean isNeg = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0); 5 | 6 | //use long to take care of overflow 7 | long ldividend = Math.abs((long)dividend); 8 | long ldivisor = Math.abs((long)divisor); 9 | 10 | long res = 0, curr = 1; 11 | long sub = ldivisor; 12 | 13 | while (ldividend >= ldivisor) { 14 | if (ldividend >= sub) { 15 | res += curr; 16 | ldividend -= sub; 17 | sub = sub << 1; //sub = sub * 2 18 | curr = curr << 1; //curr = curr * 2 19 | } 20 | else { 21 | sub = sub >> 1; 22 | curr = curr >> 1; 23 | } 24 | } 25 | 26 | res = isNeg ? -res : res; 27 | 28 | return (int) (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? Integer.MAX_VALUE : res); 29 | } 30 | } -------------------------------------------------------------------------------- /29-divide-two-integers/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /3/ Longest Substring Without Repeating Characters/Solution.kt: -------------------------------------------------------------------------------- 1 | package `3`.` Longest Substring Without Repeating Characters` 2 | 3 | /////old version .toInt() 4 | class Solution { 5 | fun lengthOfLongestSubstring(s: String): Int { 6 | val freq = IntArray(256) { 0 } 7 | var l = 0 8 | var r = -1 9 | var res = 0 10 | while (l < s.length) { 11 | if (r + 1 < s.length && freq[s[r + 1].toInt()] == 0) freq[s[++r].toInt()]++ 12 | else freq[s[l++].toInt()]-- 13 | 14 | res = maxOf(res, r - l + 1) 15 | } 16 | return res 17 | } 18 | } 19 | 20 | 21 | ////////////// For Kotlin 1.5 new version 22 | //class Solution { 23 | // fun lengthOfLongestSubstring(s: String): Int { 24 | // val freq = IntArray(256) { 0 } 25 | // var l = 0 26 | // var r = -1 27 | // var res = 0 28 | // while (l < s.length) { 29 | // if (r + 1 < s.length && freq[s[r + 1].code] == 0) freq[s[++r].code]++ 30 | // else freq[s[l++].code]-- 31 | // 32 | // res = maxOf(res, r - l + 1) 33 | // } 34 | // return res 35 | // } 36 | //} 37 | -------------------------------------------------------------------------------- /33/ Search in Rotated Sorted Array/Solution.kt: -------------------------------------------------------------------------------- 1 | package `33`.` Search in Rotated Sorted Array` 2 | 3 | class Solution { 4 | fun search(nums: IntArray, target: Int): Int { 5 | if (nums.isEmpty()) { 6 | return -1 7 | } 8 | var left = 0 9 | var right = nums.size - 1 10 | while (left + 1 < right) { 11 | val mid = left + (right - left) / 2 12 | when { 13 | nums[mid] == target -> return mid 14 | nums[mid] >= nums[0] -> { 15 | if (nums[left] <= target && target <= nums[mid]) { 16 | right = mid 17 | } else { 18 | left = mid 19 | } 20 | } 21 | 22 | nums[mid] <= nums[nums.size - 1] -> { 23 | if (nums[mid] <= target && target <= nums[right]) { 24 | left = mid 25 | } else { 26 | right = mid 27 | } 28 | } 29 | } 30 | } 31 | return when (target) { 32 | nums[left] -> left 33 | nums[right] -> right 34 | else -> -1 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /34/ Find First and Last Position of Element in Sorted Array/Solution.kt: -------------------------------------------------------------------------------- 1 | package `34`.` Find First and Last Position of Element in Sorted Array` 2 | 3 | class Solution { 4 | fun searchRange(nums: IntArray, target: Int): IntArray { 5 | 6 | if (nums.size == 0) return intArrayOf(-1, -1) 7 | 8 | var l: Int = 0 9 | var r: Int = nums.size - 1 10 | var mid = 0 11 | var res = IntArray(2) 12 | 13 | while (l < r) { 14 | mid = (l + r) / 2 15 | if (nums[mid] < target) { 16 | l = mid + 1 17 | } else { 18 | r = mid 19 | } 20 | } 21 | 22 | if (nums[l] != target) return intArrayOf(-1, -1) 23 | res[0] = l 24 | 25 | r = nums.size - 1 26 | 27 | while (l < r) { 28 | mid = (l + r) / 2 + 1 29 | if (nums[mid] == target) { 30 | l = mid 31 | } else { 32 | r = mid - 1 33 | } 34 | } 35 | res[1] = l 36 | return res 37 | } 38 | } -------------------------------------------------------------------------------- /344/ Reverse String/Solution.kt: -------------------------------------------------------------------------------- 1 | package `344`.` Reverse String` 2 | 3 | class Solution { 4 | private fun swap(s: CharArray, left: Int, right: Int) { 5 | var temp = s[left] 6 | s[left] = s[right] 7 | s[right] = temp 8 | } 9 | 10 | fun reverseString(s: CharArray): Unit { 11 | var left = 0 12 | var right = s.size - 1 13 | 14 | while (left < right) { 15 | swap(s, left, right) 16 | 17 | left++ 18 | right-- 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /35/ Search Insert Position/Solution.kt: -------------------------------------------------------------------------------- 1 | package `35`.` Search Insert Position` 2 | 3 | class Solution { 4 | fun searchInsert(nums: IntArray, target: Int): Int { 5 | var low = 0 6 | var high = nums.size - 1 7 | while (low <= high) { 8 | val mid = (low + high) ushr 1 9 | when { 10 | target < nums[mid] -> high = mid - 1 11 | target > nums[mid] -> low = mid + 1 12 | else -> return mid 13 | } 14 | } 15 | return low 16 | } 17 | } -------------------------------------------------------------------------------- /350-Intersection of Two Arrays II/350-Intersection of Two Arrays II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] intersect(int[] nums1, int[] nums2) { 3 | HashMap map = new HashMap<>(); 4 | ArrayList arr = new ArrayList<>(); 5 | for (int num : nums1) { 6 | if (map.containsKey(num)) { 7 | map.put(num, map.get(num) + 1); 8 | } else { 9 | map.put(num, 1); 10 | } 11 | } 12 | for (int num : nums2) { 13 | if (map.containsKey(num) && map.get(num) > 0) { 14 | arr.add(num); 15 | map.put(num, map.get(num) - 1); 16 | } 17 | } 18 | int[] res = new int[arr.size()]; 19 | int k = 0; 20 | for (Integer num : arr) { 21 | res[k++] = num; 22 | } 23 | return res; 24 | } 25 | } -------------------------------------------------------------------------------- /350/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector &nums1, vector &nums2) { 4 | sort(nums1.begin(), nums1.end()); 5 | sort(nums2.begin(), nums2.end()); 6 | vector solution; 7 | int index = 0; 8 | bool finished = false; 9 | for (int i = 0; i < nums1.size() && !finished; i++) { 10 | while (index < nums2.size() && nums1[i] > nums2[index]) { 11 | index++; 12 | } 13 | if (index == nums2.size()) { 14 | finished = true; 15 | } else if (nums1[i] == nums2[index]) { 16 | solution.push_back(nums1[i]); 17 | index++; 18 | } 19 | } 20 | return solution; 21 | } 22 | }; -------------------------------------------------------------------------------- /438/ Find All Anagrams in a String/Solution.kt: -------------------------------------------------------------------------------- 1 | package `438`.` Find All Anagrams in a String` 2 | 3 | class Solution { 4 | fun findAnagrams(s: String, p: String): List { 5 | if (s.isEmpty() || s.length < p.length) { 6 | return emptyList() 7 | } 8 | 9 | val result = mutableListOf() 10 | val hashArray = IntArray(26) 11 | for (index in p.indices) { 12 | ++hashArray[p[index] - 'a'] 13 | } 14 | 15 | var left = 0 16 | var count = 0 17 | 18 | for (index in s.indices) { 19 | if (--hashArray[s[index] - 'a'] >= 0) { 20 | ++count 21 | } 22 | if (index >= p.length) { 23 | if (hashArray[s[left++] - 'a']++ >= 0) { 24 | --count 25 | } 26 | } 27 | if (count == p.length) { 28 | result.add(left) 29 | } 30 | } 31 | return result 32 | } 33 | } -------------------------------------------------------------------------------- /46/ Permutations/Solution.kt: -------------------------------------------------------------------------------- 1 | package `46`.` Permutations` 2 | 3 | class Solution { 4 | private val res = ArrayList>() 5 | fun permute(nums: IntArray): List> { 6 | permutation(nums, 0, nums.size - 1) 7 | return res 8 | } 9 | 10 | private fun permutation(list: IntArray, start: Int, length: Int) { 11 | if (start == length) res.add(list.toMutableList()) 12 | else (start..length).forEach { i -> 13 | swap(list, start, i) 14 | permutation(list, start + 1, length) 15 | swap(list, start, i) 16 | } 17 | } 18 | 19 | private fun swap(nums: IntArray, i: Int, j: Int) { 20 | val temp = nums[i] 21 | nums[i] = nums[j] 22 | nums[j] = temp 23 | } 24 | } -------------------------------------------------------------------------------- /462-minimum-moves-to-equal-array-elements-ii/462-minimum-moves-to-equal-array-elements-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minMoves2(int[] nums) { 3 | int res = 0; 4 | if (nums == null || nums.length <= 1) return res; 5 | int start = 0; 6 | int end = nums.length -1 ; 7 | Arrays.sort(nums); 8 | while(start < end) { 9 | res += nums[end] - nums[start]; 10 | start++; 11 | end--; 12 | } 13 | return res; 14 | } 15 | } -------------------------------------------------------------------------------- /462-minimum-moves-to-equal-array-elements-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /53-Maximum-Subarray/53-Maximum-Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int total = 0, max = Integer.MIN_VALUE; 4 | for (int i = 0; i < nums.length; i++) { 5 | total += nums[i]; 6 | if (max < total) 7 | max = total; 8 | if (total <= 0) 9 | total = 0; 10 | } 11 | return max; 12 | } 13 | } -------------------------------------------------------------------------------- /53/ Maximum Subarray/Solution.kt: -------------------------------------------------------------------------------- 1 | package `53`.` Maximum Subarray` 2 | 3 | class Solution { 4 | fun maxSubArray(nums: IntArray): Int { 5 | var sum = 0 6 | var maxa = -2147483647 7 | 8 | nums.forEach { a -> 9 | if (sum < 0) { 10 | sum = a 11 | } else { 12 | sum += a 13 | } 14 | maxa = Math.max(sum, maxa) 15 | } 16 | return maxa 17 | } 18 | } -------------------------------------------------------------------------------- /542/ 01 Matrix/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public final int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 3 | 4 | public int[][] updateMatrix(int[][] mat) { 5 | int rowCount = mat.length; 6 | int colCount = mat[0].length; 7 | int[][] res = new int[rowCount][colCount]; 8 | 9 | //Initialize 10 | for (int i = 0; i < rowCount; ++i) { 11 | for (int j = 0; j < colCount; ++j) { 12 | res[i][j] = Integer.MAX_VALUE; 13 | } 14 | } 15 | 16 | 17 | // Update from top-left 18 | for (int i = 0; i < rowCount; ++i) { 19 | for (int j = 0; j < colCount; ++j) { 20 | update(mat, res, rowCount, colCount, i, j); 21 | } 22 | } 23 | 24 | 25 | // Update from bottom-right 26 | for (int i = rowCount - 1; i > -1; --i) { 27 | for (int j = colCount - 1; j > -1; --j) { 28 | update(mat, res, rowCount, colCount, i, j); 29 | } 30 | } 31 | 32 | 33 | return res; 34 | 35 | } 36 | 37 | public void update(int[][] src, int[][] out, int rowCount, int colCount, int i, int j) { 38 | if (src[i][j] == 0) { 39 | out[i][j] = 0; 40 | return; 41 | } 42 | 43 | for (int[] d : directions) { 44 | int x = i + d[0]; 45 | int y = j + d[1]; 46 | if (0 <= x && x < rowCount && 0 <= y && y < colCount && out[x][y] != Integer.MAX_VALUE && out[x][y] + 1 < out[i][j]) { 47 | out[i][j] = out[x][y] + 1; 48 | } 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /547/ Number of Provinces/Solution.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public int findCircleNum(int[][] isConnected) { 5 | int n = isConnected.length; 6 | boolean[] visited = new boolean[n]; 7 | int components = 0; 8 | for (int vertex = 0; vertex < n; vertex++) { 9 | if (!visited[vertex]) { 10 | visited[vertex] = true; 11 | components++; 12 | visitNeighbors(vertex, isConnected, visited); 13 | } 14 | } 15 | return components; 16 | } 17 | 18 | private void visitNeighbors(int vertex, int[][] isConnected, boolean[] visited) { 19 | for (int v = 0; v < isConnected.length; v++) { 20 | if (isConnected[vertex][v] == 1 && !visited[v]) { 21 | visited[v] = true; 22 | visitNeighbors(v, isConnected, visited); 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /557/ Reverse Words in a String III/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseWords(String s) { 3 | if (s == null || s.length() <= 1) { 4 | return s; 5 | } 6 | 7 | char[] str = s.toCharArray(); 8 | int start = 0; 9 | for (int i = 0; i < str.length; i++) { 10 | if (str[i] == ' ') { 11 | reverse(str, start, i - 1); 12 | start = i + 1; 13 | } else if (i == str.length - 1) { 14 | reverse(str, start, i); 15 | } 16 | }//end for 17 | return String.valueOf(str); 18 | } 19 | 20 | public void reverse(char[] s, int start, int end) { 21 | while (start < end) { 22 | char temp = s[start]; 23 | s[start] = s[end]; 24 | s[end] = temp; 25 | start++; 26 | end--; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /566-Reshape the Matrix/566-Reshape the Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] matrixReshape(int[][] mat, int r, int c) { 3 | int numberOfElement = mat.length * mat[0].length; 4 | if (numberOfElement != r * c) 5 | return mat; 6 | 7 | int[] expandedArrary = new int[numberOfElement]; 8 | int k = 0; 9 | for (int i = 0; i < mat.length; i++) { 10 | for (int j = 0; j < mat[i].length; j++) { 11 | expandedArrary[k] = mat[i][j]; 12 | k++; 13 | } 14 | } 15 | 16 | int[][] answer = new int[r][c]; 17 | int i = 0; 18 | int j = 0; 19 | for (k = 0; k < numberOfElement; k++) { 20 | answer[i][j] = expandedArrary[k]; 21 | j++; 22 | if (j == c){ 23 | j = 0; 24 | i++; 25 | } 26 | 27 | } 28 | return answer; 29 | } 30 | } -------------------------------------------------------------------------------- /567/ Permutation in String/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | int m = s1.size(), n = s2.size(); 5 | if (m > n) return false; 6 | 7 | vector cnt1(26); 8 | vector cnt2(26); 9 | for (int i = 0; i < m; ++i) { 10 | cnt1[s1[i] - 'a']++; 11 | cnt2[s2[i] - 'a']++; 12 | } 13 | 14 | if (cnt1 == cnt2) return true; 15 | 16 | for (int i = m; i < n; ++i) { 17 | cnt2[s2[i - m] - 'a']--; 18 | cnt2[s2[i] - 'a']++; 19 | if (cnt1 == cnt2) { 20 | return true; 21 | } 22 | } 23 | return false; 24 | } 25 | }; -------------------------------------------------------------------------------- /567/ Permutation in String/Solution.kt: -------------------------------------------------------------------------------- 1 | package `567`.` Permutation in String` 2 | 3 | class Solution { 4 | fun checkInclusion(s1: String, s2: String): Boolean { 5 | if (s1.length > s2.length) return false 6 | val slide = IntArray(26) { 0 } 7 | s1.indices.forEach { slide[s1[it] - 'a']++ } 8 | (0 until s2.length).forEach { 9 | slide[s2[it] - 'a']-- 10 | if (it >= s1.length) slide[s2[it - s1.length] - 'a']++ 11 | if (slide.none { it != 0 }) return true 12 | } 13 | return false 14 | } 15 | } -------------------------------------------------------------------------------- /572/ Subtree of Another Tree/Solution.kt: -------------------------------------------------------------------------------- 1 | package `572`.` Subtree of Another Tree` 2 | 3 | 4 | var ti = TreeNode(5) 5 | var v = ti.`val` 6 | 7 | class TreeNode(var `val`: Int) { 8 | var left: TreeNode? = null 9 | var right: TreeNode? = null 10 | } 11 | 12 | class Solution { 13 | fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean { 14 | if (null == root || null == subRoot) return root == subRoot 15 | return isSame(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) 16 | } 17 | 18 | private fun isSame(node: TreeNode?, t: TreeNode?): Boolean { 19 | if (node == null || t == null) return node == t 20 | return node.`val` == t.`val` && isSame(node.left, t.left) && isSame(node.right, t.right) 21 | } 22 | } -------------------------------------------------------------------------------- /58-length-of-last-word/58-length-of-last-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | if (s == null || s.length() == 0) { 4 | return 0; 5 | } 6 | s = s.trim(); 7 | for(int i = s.length() - 1; i >= 0; i--) { 8 | if(s.charAt(i) == ' ') { 9 | return s.length() - i - 1; 10 | } 11 | } 12 | 13 | return s.length(); 14 | } 15 | } -------------------------------------------------------------------------------- /58-length-of-last-word/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /58-length-of-last-word/README.md: -------------------------------------------------------------------------------- 1 |

58. Length of Last Word

Easy


Given a string s consisting of words and spaces, return the length of the last word in the string.

2 | 3 |

A word is a maximal substring consisting of non-space characters only.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: s = "Hello World"
 9 | Output: 5
10 | Explanation: The last word is "World" with length 5.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: s = "   fly me   to   the moon  "
16 | Output: 4
17 | Explanation: The last word is "moon" with length 4.
18 | 
19 | 20 |

Example 3:

21 | 22 |
Input: s = "luffy is still joyboy"
23 | Output: 6
24 | Explanation: The last word is "joyboy" with length 6.
25 | 
26 | 27 |

 

28 |

Constraints:

29 | 30 |
    31 |
  • 1 <= s.length <= 104
  • 32 |
  • s consists of only English letters and spaces ' '.
  • 33 |
  • There will be at least one word in s.
  • 34 |
35 |
-------------------------------------------------------------------------------- /617/ Merge Two Binary Trees/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 3 | TreeNode node; 4 | if (t1 == null && t2 == null) { 5 | node = null; 6 | } else if (t1 == null) { 7 | node = new TreeNode(t2.val); 8 | node.left = mergeTrees(null, t2.left); 9 | node.right = mergeTrees(null, t2.right); 10 | } else if (t2 == null) { 11 | node = new TreeNode(t1.val); 12 | node.left = mergeTrees(t1.left, null); 13 | node.right = mergeTrees(t1.right, null); 14 | } else { 15 | node = new TreeNode(t1.val + t2.val); 16 | node.left = mergeTrees(t1.left, t2.left); 17 | node.right = mergeTrees(t1.right, t2.right); 18 | } 19 | return node; 20 | } 21 | } -------------------------------------------------------------------------------- /66-plus-one/66-plus-one.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | int n = digits.size(); 5 | int pos = n -1; 6 | while(pos >= 0 && digits[pos] == 9) { 7 | digits[pos] = 0; 8 | pos--; 9 | } 10 | 11 | if(pos < 0) { 12 | digits.insert(digits.begin(), 1); 13 | }else { 14 | digits[pos]++; 15 | } 16 | 17 | return digits; 18 | } 19 | }; -------------------------------------------------------------------------------- /66-plus-one/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /66-plus-one/README.md: -------------------------------------------------------------------------------- 1 |

66. Plus One

Easy


You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

2 | 3 |

Increment the large integer by one and return the resulting array of digits.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: digits = [1,2,3]
 9 | Output: [1,2,4]
10 | Explanation: The array represents the integer 123.
11 | Incrementing by one gives 123 + 1 = 124.
12 | Thus, the result should be [1,2,4].
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: digits = [4,3,2,1]
18 | Output: [4,3,2,2]
19 | Explanation: The array represents the integer 4321.
20 | Incrementing by one gives 4321 + 1 = 4322.
21 | Thus, the result should be [4,3,2,2].
22 | 
23 | 24 |

Example 3:

25 | 26 |
Input: digits = [9]
27 | Output: [1,0]
28 | Explanation: The array represents the integer 9.
29 | Incrementing by one gives 9 + 1 = 10.
30 | Thus, the result should be [1,0].
31 | 
32 | 33 |

 

34 |

Constraints:

35 | 36 |
    37 |
  • 1 <= digits.length <= 100
  • 38 |
  • 0 <= digits[i] <= 9
  • 39 |
  • digits does not contain any leading 0's.
  • 40 |
41 |
-------------------------------------------------------------------------------- /67-add-binary/67-add-binary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | int N = max(a.size(), b.size()) + 1; 5 | 6 | //padding 7 | a.insert(a.begin(), N-a.size(), '0'); 8 | b.insert(b.begin(), N-b.size(), '0'); 9 | 10 | reverse(a.begin(), a.end()); 11 | reverse(b.begin(), b.end()); 12 | 13 | int i = 0, carry = 0; 14 | //add b to a 15 | for(int i = 0; i < N; i++) { 16 | int ai = a[i] - '0', bi = b[i] - '0'; 17 | int sumi = ai + bi + carry; 18 | switch(sumi) { 19 | case 3: 20 | a[i] = '1'; 21 | carry = 1; 22 | break; 23 | case 2: 24 | a[i] = '0'; 25 | carry = 1; 26 | break; 27 | case 1: 28 | a[i] = '1'; 29 | carry = 0 ; 30 | break; 31 | } 32 | } 33 | 34 | if(a[N-1] == '0') a.resize(N-1); 35 | reverse(a.begin(), a.end()); 36 | return a; 37 | } 38 | }; -------------------------------------------------------------------------------- /67-add-binary/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /67-add-binary/README.md: -------------------------------------------------------------------------------- 1 |

67. Add Binary

Easy


Given two binary strings a and b, return their sum as a binary string.

2 | 3 |

 

4 |

Example 1:

5 |
Input: a = "11", b = "1"
 6 | Output: "100"
 7 | 

Example 2:

8 |
Input: a = "1010", b = "1011"
 9 | Output: "10101"
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= a.length, b.length <= 104
  • 16 |
  • a and b consist only of '0' or '1' characters.
  • 17 |
  • Each string does not contain leading zeros except for the zero itself.
  • 18 |
19 |
-------------------------------------------------------------------------------- /695. Max Area of Island/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxAreaOfIsland(vector > &grid) { 4 | int m = grid.size(); 5 | int n = grid[0].size(); 6 | int res = 0; 7 | for (int i = 0; i < m; i++) 8 | for (int j = 0; j < n; j++) 9 | if (grid[i][j] == 1) 10 | res = max(res, dfs(grid, i, j)); 11 | return res; 12 | } 13 | 14 | int dfs(vector > &grid, int i, int j) { 15 | int m = grid.size(); 16 | int n = grid[0].size(); 17 | 18 | if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) 19 | return 0; 20 | grid[i][j] = 0; 21 | 22 | return dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + dfs(grid, i, j + 1) + dfs(grid, i, j - 1) + 1; 23 | } 24 | }; -------------------------------------------------------------------------------- /7-reverse-integer/7-reverse-integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | int res = 0; 4 | 5 | while (x != 0) { 6 | int tail = x % 10; 7 | int newRes = res * 10 + tail; 8 | if ((newRes - tail) / 10 != res) { 9 | return 0; 10 | } 11 | res = newRes; 12 | x = x / 10; 13 | } 14 | return res; 15 | } 16 | } -------------------------------------------------------------------------------- /7-reverse-integer/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /7-reverse-integer/README.md: -------------------------------------------------------------------------------- 1 |

7. Reverse Integer

Medium


Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

2 | 3 |

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: x = 123
 9 | Output: 321
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: x = -123
15 | Output: -321
16 | 
17 | 18 |

Example 3:

19 | 20 |
Input: x = 120
21 | Output: 21
22 | 
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • -231 <= x <= 231 - 1
  • 29 |
30 |
-------------------------------------------------------------------------------- /70/ Climbing Stairs/Solution.kt: -------------------------------------------------------------------------------- 1 | package `70`.` Climbing Stairs` 2 | 3 | class Solution { 4 | fun climbStairs(n: Int): Int { 5 | val arr = MutableList(n + 2) { 0 } 6 | arr[1] = 1 7 | arr[2] = 2 8 | return (3..n).forEach { arr[it] = arr[it - 1] + arr[it - 2] }.let { arr[n] } 9 | } 10 | 11 | } -------------------------------------------------------------------------------- /704/ Binary Search/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | 4 | int lo = 0, hi = nums.length-1; 5 | 6 | while (lo <= hi) { 7 | int mid = lo + (hi - lo) /2; 8 | if (nums[mid] == target) { 9 | return mid; 10 | } 11 | if (nums[mid] > target) { 12 | hi = mid -1; 13 | }else{ 14 | lo = mid + 1; 15 | } 16 | } 17 | return -1; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /704/ Binary Search/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector &nums, int target) { 4 | int lo = 0, hi = nums.size() - 1; 5 | while (lo <= hi) { 6 | int mid = lo + ((hi - lo) >> 1); 7 | if (nums[mid] == target) { 8 | return mid; 9 | } else if (nums[mid] > target) { 10 | hi = mid - 1; 11 | } else { 12 | lo = mid + 1; 13 | } 14 | } 15 | return -1; 16 | } 17 | }; -------------------------------------------------------------------------------- /704/ Binary Search/solution.kt: -------------------------------------------------------------------------------- 1 | package `704`.` Binary Search` 2 | 3 | internal class Solution { 4 | fun search(nums: IntArray, target: Int): Int { 5 | var lo = 0 6 | var hi = nums.size - 1 7 | while (lo <= hi) { 8 | val mid = lo + (hi - lo) / 2 9 | if (nums[mid] == target) { 10 | return mid 11 | } 12 | if (nums[mid] > target) { 13 | hi = mid - 1 14 | } else { 15 | lo = mid + 1 16 | } 17 | } 18 | return -1 19 | } 20 | } -------------------------------------------------------------------------------- /713/ Subarray Product Less Than K/Solution.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public int numSubarrayProductLessThanK(int[] nums, int k) { 5 | int n = nums.length; 6 | int res = 0; 7 | for (int i = 0; i < n; i++) { 8 | long t = 1; 9 | for (int j = i; j < n; j++) { 10 | t *= nums[j]; 11 | if (t < k) { 12 | res++; 13 | }else break; 14 | } 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /733/ Flood Fill/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] dx = {1, -1, 0, 0}; 3 | int[] dy = {0, 0, 1, -1}; 4 | boolean[][] visited; 5 | 6 | public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { 7 | int m = image.length, n = image[0].length; 8 | visited = new boolean[m][n]; 9 | dfs(image, sr, sc, image[sr][sc], newColor); 10 | return image; 11 | } 12 | 13 | private void dfs(int[][] image, int sr, int sc, int original, int newColor) { 14 | image[sr][sc] = newColor; 15 | visited[sr][sc] = true; 16 | 17 | for (int i = 0; i < 4; i++) { 18 | int x = sr + dx[i], y = sc + dy[i]; 19 | if (validate(image, x, y, original)) { 20 | dfs(image, x, y, original, newColor); 21 | } 22 | } 23 | } 24 | 25 | private boolean validate(int[][] image, int x, int y, int original) { 26 | int m = image.length, n = image[0].length; 27 | return x >= 0 && x < m && y >= 0 && y < n && image[x][y] == original && !visited[x][y]; 28 | } 29 | } -------------------------------------------------------------------------------- /733/ Flood Fill/Solution.kt: -------------------------------------------------------------------------------- 1 | package `733`.` Flood Fill` 2 | 3 | class Solution { 4 | val direct = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) 5 | fun floodFill(image: Array, sr: Int, sc: Int, newColor: Int): Array { 6 | if (image[sr][sc] == newColor) return image 7 | dfs(image, sr, sc, image[sr][sc], newColor) 8 | return image 9 | } 10 | 11 | private fun dfs(image: Array, sr: Int, sc: Int, srcColor: Int, newColor: Int) { 12 | image[sr][sc] = newColor 13 | (0 until 4).forEach { i -> 14 | val newX = sr + direct[i][0] 15 | val newY = sc + direct[i][1] 16 | if (newX in (0 until image.size) && newY in (0 until image[0].size) 17 | && image[newX][newY] == srcColor 18 | ) { 19 | floodFill(image, newX, newY, newColor) 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /74/ Search a 2D Matrix/Solution.kt: -------------------------------------------------------------------------------- 1 | package `74`.` Search a 2D Matrix` 2 | 3 | class Solution { 4 | fun searchMatrix(matrix: Array, target: Int): Boolean { 5 | if (matrix.isNullOrEmpty() || matrix[0].isEmpty()) { 6 | return false 7 | } 8 | val targetRow = searchTargetRowIndex(matrix, target) 9 | if (targetRow == -1) { 10 | return false 11 | } 12 | 13 | return searchTargetIndex(matrix[targetRow], target) != -1 14 | } 15 | 16 | private fun searchTargetRowIndex(matrix: Array, target: Int): Int { 17 | var left = 0 18 | var right = matrix.size - 1 19 | 20 | while (left + 1 < right) { 21 | val mid = left + (right - left) / 2 22 | when { 23 | matrix[mid][0] <= target -> left = mid 24 | matrix[mid][0] > target -> right = mid 25 | } 26 | } 27 | 28 | return when { 29 | target >= matrix[right][0] -> right 30 | target >= matrix[left][0] -> left 31 | else -> -1 32 | } 33 | } 34 | 35 | 36 | private fun searchTargetIndex(nums: IntArray, target: Int): Int { 37 | if (nums.isEmpty()) { 38 | return -1 39 | } 40 | var left = 0 41 | var right = nums.size - 1 42 | while (left + 1 < right) { 43 | val mid = left + (right - left) / 2 44 | when { 45 | nums[mid] == target -> return mid 46 | nums[mid] < target -> left = mid 47 | nums[mid] > target -> right = mid 48 | } 49 | } 50 | return when (target) { 51 | nums[left] -> left 52 | nums[right] -> right 53 | else -> -1 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /77/ Combinations/Solution.kt: -------------------------------------------------------------------------------- 1 | package `77`.` Combinations` 2 | 3 | class Solution { 4 | private val res = ArrayList>() 5 | fun combine(n: Int, k: Int): List> { 6 | if (n < 1 || k < 1 || n < k) return res 7 | combination(n, k, 1, ArrayList()) 8 | return res 9 | } 10 | 11 | private fun combination(n: Int, k: Int, start: Int, list: ArrayList) { 12 | if (list.size == k) res.add(ArrayList(list)) 13 | else (start..n).forEach { 14 | list.add(it) 15 | combination(n, k, it + 1, list) 16 | list.remove(it) 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /784/ Letter Case Permutation/Solution.kt: -------------------------------------------------------------------------------- 1 | package `784`.` Letter Case Permutation` 2 | 3 | import java.util.* 4 | 5 | class Solution { 6 | fun letterCasePermutation(s: String): List { 7 | val res = mutableListOf() 8 | val que = LinkedList>() 9 | que.push(Pair(s, 0)) 10 | while (que.isNotEmpty()) { 11 | val per = que.peek().first 12 | val index = que.peek().second 13 | que.pop() 14 | 15 | if (!res.contains(per)) res.add(per) 16 | 17 | for (i in index until per.length) { 18 | per[i].let { 19 | if (it.isLetter()) { 20 | val newChar = if (it.isUpperCase()) it.toLowerCase() else it.toUpperCase() 21 | val new = StringBuilder(per).replace(i, i + 1, "$newChar").toString() 22 | que.push(Pair(new, i + 1)) 23 | } 24 | } 25 | } 26 | } 27 | return res 28 | } 29 | } -------------------------------------------------------------------------------- /797/ All Paths From Source to Target/Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class Solution { 5 | public List> allPathsSourceTarget(int[][] graph) { 6 | List> res = new ArrayList<>(); 7 | List path = new ArrayList<>(); 8 | 9 | path.add(0); 10 | deepSearch(graph, 0, path, res); 11 | 12 | return res; 13 | } 14 | 15 | public void deepSearch(int[][] graph, int index, List path, List> res) { 16 | if (index + 1 == graph.length) { 17 | res.add(new ArrayList<>(path)); 18 | return; 19 | } 20 | 21 | for (int node : graph[index]) { 22 | path.add(node); 23 | deepSearch(graph, node, path, res); 24 | path.remove(path.size() - 1); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /82/ Remove Duplicates from Sorted List II/Solution.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public ListNode deleteDuplicates(ListNode head) { 5 | if (head == null || head.next == null) { 6 | return head; 7 | } 8 | 9 | ListNode fakeHead = new ListNode(0, head); 10 | ListNode prev = fakeHead; 11 | ListNode curr = head; 12 | while (curr != null) { 13 | while (curr.next != null && curr.next.val == curr.val) { 14 | curr = curr.next; 15 | } 16 | 17 | if (prev.next == curr) { 18 | prev = prev.next; 19 | } else { 20 | prev.next = curr.next; 21 | } 22 | curr = curr.next; 23 | } 24 | return fakeHead.next; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /83-remove-duplicates-from-sorted-list/83-remove-duplicates-from-sorted-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode deleteDuplicates(ListNode head) { 13 | if(head==null || head.next==null) return head; 14 | ListNode first = head, second = first.next; 15 | while(second != null) { 16 | if(first.val == second.val) { 17 | second=second.next; 18 | first.next = second; 19 | }else{ 20 | first = second; 21 | second = second.next; 22 | } 23 | } 24 | return head; 25 | } 26 | } -------------------------------------------------------------------------------- /83-remove-duplicates-from-sorted-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /83-remove-duplicates-from-sorted-list/README.md: -------------------------------------------------------------------------------- 1 |

83. Remove Duplicates from Sorted List

Easy


Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,1,2]
 7 | Output: [1,2]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [1,1,2,3,3]
13 | Output: [1,2,3]
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • The number of nodes in the list is in the range [0, 300].
  • 21 |
  • -100 <= Node.val <= 100
  • 22 |
  • The list is guaranteed to be sorted in ascending order.
  • 23 |
24 |
-------------------------------------------------------------------------------- /844/ Backspace String Compare/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean backspaceCompare(String s, String t) { 3 | int i = s.length() - 1, j = t.length() - 1, back; 4 | while (true) { 5 | back = 0; 6 | while (i >= 0 && (back > 0 || s.charAt(i) == '#')) { 7 | back += s.charAt(i) == '#' ? 1 : -1; 8 | i--; 9 | } 10 | back = 0; 11 | while (j >= 0 && (back > 0 || t.charAt(j) == '#')) { 12 | back += t.charAt(j) == '#' ? 1 : -1; 13 | j--; 14 | } 15 | 16 | if (i >= 0 && j >= 0 && s.charAt(i) == t.charAt(j)) { 17 | i--; 18 | j--; 19 | } else { 20 | break; 21 | } 22 | } 23 | return i == -1 && j == -1; 24 | } 25 | } -------------------------------------------------------------------------------- /876/ Middle of the Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode middleNode(ListNode head) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | while (fast != null && fast.next != null) { 6 | slow = slow.next; 7 | fast = fast.next.next; 8 | } 9 | return slow; 10 | } 11 | } -------------------------------------------------------------------------------- /88/ Merge Sorted Array/Solution.kt: -------------------------------------------------------------------------------- 1 | package `88`.` Merge Sorted Array` 2 | 3 | class Solution { 4 | fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit { 5 | 6 | var i = m - 1 7 | var j = n - 1 8 | var k = m + n - 1 9 | while (j >= 0) 10 | nums1[k--] = if (i >= 0 && nums1[i] > nums2[j]) nums1[i--] else nums2[j--] 11 | nums1.forEach { print("$it ") }; println() 12 | } 13 | } -------------------------------------------------------------------------------- /9/ Palindrome Number/Solution.kt: -------------------------------------------------------------------------------- 1 | package `9`.` Palindrome Number` 2 | 3 | class Solution { 4 | fun isPalindrome(x: Int): Boolean { 5 | if (x < 0) { 6 | return false 7 | } 8 | 9 | var a = IntArray(20) 10 | var cnt = 0 11 | var n = x 12 | while (n > 0) { 13 | a[cnt++] = n % 10 14 | n /= 10 15 | } 16 | for (i in 0 until cnt / 2) { 17 | if (a[i] != a[cnt - i - 1]) return false 18 | } 19 | return true 20 | } 21 | } -------------------------------------------------------------------------------- /977. Squares of a Sorted Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector &nums) { 4 | int sz = nums.size(); 5 | vector ans(sz); 6 | for (int l = 0, r = sz - 1, idx = sz - 1; l <= r; --idx) { 7 | if (-nums[l] < nums[r]) { 8 | ans[idx] = nums[r] * nums[r]; 9 | --r; 10 | } else { 11 | ans [idx] = nums[l] * nums[l]; 12 | ++l; 13 | } 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /994/ Rotting Oranges/Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | 3 | class Solution { 4 | public int orangesRotting(int[][] grid) { 5 | LinkedList list = new LinkedList<>(); 6 | int r = grid.length, c = grid[0].length; 7 | int freshCount = 0; 8 | for (int i = 0; i < r; i++) { 9 | for (int j = 0; j < c; j++) { 10 | if (grid[i][j] == 2) list.add(new int[]{i, j}); 11 | if (grid[i][j] == 1) freshCount++; 12 | } 13 | } 14 | int res = 0; 15 | while (!list.isEmpty() && freshCount != 0) { 16 | res++; 17 | int size = list.size(); 18 | while (size > 0) { 19 | size--; 20 | int[] t = list.removeFirst(); 21 | if (t[0] > 0 && grid[t[0] - 1][t[1]] == 1) { 22 | freshCount--; 23 | grid[t[0] - 1][t[1]] = 2; 24 | list.add(new int[]{t[0] - 1, t[1]}); 25 | } 26 | if (t[0] + 1 < r && grid[t[0] + 1][t[1]] == 1) { 27 | freshCount--; 28 | grid[t[0] + 1][t[1]] = 2; 29 | list.add(new int[]{t[0] + 1, t[1]}); 30 | } 31 | if (t[1] > 0 && grid[t[0]][t[1] - 1] == 1) { 32 | freshCount--; 33 | grid[t[0]][t[1] - 1] = 2; 34 | list.add(new int[]{t[0], t[1] - 1}); 35 | } 36 | if (t[1] + 1 < c && grid[t[0]][t[1] + 1] == 1) { 37 | freshCount--; 38 | grid[t[0]][t[1] + 1] = 2; 39 | list.add(new int[]{t[0], t[1] + 1}); 40 | } 41 | } 42 | } 43 | return freshCount == 0 ? res : -1; 44 | } 45 | } -------------------------------------------------------------------------------- /LeetCode.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /out/production/LeetCode/189. Rotate Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector &nums, int k) { 4 | int sz = nums.size(); 5 | int step = k % sz; 6 | for (int i = 0; i < (sz - step) / 2; ++i) { 7 | swap(nums[i], nums[sz - step - 1 - i]); 8 | } 9 | for (int i = 0; i < step / 2; ++i) { 10 | swap(nums[sz - step + i], nums[sz - 1 - i]); 11 | } 12 | for (int i = 0; i < sz / 2; ++i) { 13 | swap(nums[i], nums[sz - 1 - i]); 14 | } 15 | } 16 | }; -------------------------------------------------------------------------------- /out/production/LeetCode/278/ First Bad Version/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstBadVersion(int n) { 4 | int l = 1, r = n; 5 | while (l < r) { 6 | int mid = l + (r - l) / 2; 7 | if (isBadVersion(mid)) { 8 | r = mid; 9 | } else { 10 | l = mid + 1; 11 | } 12 | } 13 | return r; 14 | } 15 | }; 16 | 17 | -------------------------------------------------------------------------------- /out/production/LeetCode/567/ Permutation in String/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | int m = s1.size(), n = s2.size(); 5 | if (m > n) return false; 6 | 7 | vector cnt1(26); 8 | vector cnt2(26); 9 | for (int i = 0; i < m; ++i) { 10 | cnt1[s1[i] - 'a']++; 11 | cnt2[s2[i] - 'a']++; 12 | } 13 | 14 | if (cnt1 == cnt2) return true; 15 | 16 | for (int i = m; i < n; ++i) { 17 | cnt2[s2[i - m] - 'a']--; 18 | cnt2[s2[i] - 'a']++; 19 | if (cnt1 == cnt2) { 20 | return true; 21 | } 22 | } 23 | return false; 24 | } 25 | }; -------------------------------------------------------------------------------- /out/production/LeetCode/695. Max Area of Island/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxAreaOfIsland(vector > &grid) { 4 | int m = grid.size(); 5 | int n = grid[0].size(); 6 | int res = 0; 7 | for (int i = 0; i < m; i++) 8 | for (int j = 0; j < n; j++) 9 | if (grid[i][j] == 1) 10 | res = max(res, dfs(grid, i, j)); 11 | return res; 12 | } 13 | 14 | int dfs(vector > &grid, int i, int j) { 15 | int m = grid.size(); 16 | int n = grid[0].size(); 17 | 18 | if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) 19 | return 0; 20 | grid[i][j] = 0; 21 | 22 | return dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + dfs(grid, i, j + 1) + dfs(grid, i, j - 1) + 1; 23 | } 24 | }; -------------------------------------------------------------------------------- /out/production/LeetCode/704/ Binary Search/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector &nums, int target) { 4 | int lo = 0, hi = nums.size() - 1; 5 | while (lo <= hi) { 6 | int mid = lo + ((hi - lo) >> 1); 7 | if (nums[mid] == target) { 8 | return mid; 9 | } else if (nums[mid] > target) { 10 | hi = mid - 1; 11 | } else { 12 | lo = mid + 1; 13 | } 14 | } 15 | return -1; 16 | } 17 | }; -------------------------------------------------------------------------------- /out/production/LeetCode/977. Squares of a Sorted Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector &nums) { 4 | int sz = nums.size(); 5 | vector ans(sz); 6 | for (int l = 0, r = sz - 1, idx = sz - 1; l <= r; --idx) { 7 | if (-nums[l] < nums[r]) { 8 | ans[idx] = nums[r] * nums[r]; 9 | --r; 10 | } else { 11 | ans [idx] = nums[l] * nums[l]; 12 | ++l; 13 | } 14 | } 15 | return ans; 16 | } 17 | }; --------------------------------------------------------------------------------