Skip to content

Commit 00a7df4

Browse files
authored
Added tasks 654, 655, 657, 658
1 parent 456c72b commit 00a7df4

File tree

13 files changed

+392
-0
lines changed

13 files changed

+392
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1344,6 +1344,7 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.9'
13441344

13451345
| <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- -->
13461346
|-|-|-|-|-|-
1347+
| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements/Solution.kt)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue | 375 | 95.16
13471348

13481349
#### Day 3
13491350

@@ -1674,6 +1675,10 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.9'
16741675
| 0864 |[Shortest Path to Get All Keys](src/main/kotlin/g0801_0900/s0864_shortest_path_to_get_all_keys/Solution.kt)| Hard | Breadth_First_Search, Bit_Manipulation | 176 | 100.00
16751676
| 0763 |[Partition Labels](src/main/kotlin/g0701_0800/s0763_partition_labels/Solution.kt)| Medium | Top_100_Liked_Questions, String, Hash_Table, Greedy, Two_Pointers, Data_Structure_II_Day_7_String | 235 | 84.75
16761677
| 0739 |[Daily Temperatures](src/main/kotlin/g0701_0800/s0739_daily_temperatures/Solution.kt)| Medium | Top_100_Liked_Questions, Array, Stack, Monotonic_Stack, Programming_Skills_II_Day_6 | 936 | 80.54
1678+
| 0658 |[Find K Closest Elements](src/main/kotlin/g0601_0700/s0658_find_k_closest_elements/Solution.kt)| Medium | Array, Sorting, Binary_Search, Two_Pointers, Heap_Priority_Queue, Binary_Search_II_Day_2 | 375 | 95.16
1679+
| 0657 |[Robot Return to Origin](src/main/kotlin/g0601_0700/s0657_robot_return_to_origin/Solution.kt)| Easy | String, Simulation | 186 | 100.00
1680+
| 0655 |[Print Binary Tree](src/main/kotlin/g0601_0700/s0655_print_binary_tree/Solution.kt)| Medium | Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree | 176 | 100.00
1681+
| 0654 |[Maximum Binary Tree](src/main/kotlin/g0601_0700/s0654_maximum_binary_tree/Solution.kt)| Medium | Array, Tree, Binary_Tree, Stack, Monotonic_Stack, Divide_and_Conquer | 271 | 90.00
16771682
| 0653 |[Two Sum IV - Input is a BST](src/main/kotlin/g0601_0700/s0653_two_sum_iv_input_is_a_bst/Solution.kt)| Easy | Hash_Table, Depth_First_Search, Breadth_First_Search, Tree, Binary_Tree, Two_Pointers, Binary_Search_Tree, Data_Structure_I_Day_14_Tree | 231 | 96.08
16781683
| 0652 |[Find Duplicate Subtrees](src/main/kotlin/g0601_0700/s0652_find_duplicate_subtrees/Solution.kt)| Medium | Hash_Table, Depth_First_Search, Tree, Binary_Tree | 266 | 76.00
16791684
| 0650 |[2 Keys Keyboard](src/main/kotlin/g0601_0700/s0650_2_keys_keyboard/Solution.kt)| Medium | Dynamic_Programming, Math | 115 | 100.00
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package g0601_0700.s0654_maximum_binary_tree
2+
3+
// #Medium #Array #Tree #Binary_Tree #Stack #Monotonic_Stack #Divide_and_Conquer
4+
// #2023_02_13_Time_271_ms_(90.00%)_Space_37.8_MB_(95.00%)
5+
6+
import com_github_leetcode.TreeNode
7+
8+
/*
9+
* Example:
10+
* var ti = TreeNode(5)
11+
* var v = ti.`val`
12+
* Definition for a binary tree node.
13+
* class TreeNode(var `val`: Int) {
14+
* var left: TreeNode? = null
15+
* var right: TreeNode? = null
16+
* }
17+
*/
18+
class Solution {
19+
fun constructMaximumBinaryTree(nums: IntArray): TreeNode? {
20+
return mbt(nums, 0, nums.size - 1)
21+
}
22+
23+
private fun mbt(nums: IntArray, l: Int, r: Int): TreeNode? {
24+
if (l > r || l >= nums.size || r < 0) {
25+
return null
26+
}
27+
if (l == r) {
28+
return TreeNode(nums[r])
29+
}
30+
var max = Int.MIN_VALUE
31+
var maxidx = 0
32+
for (i in l..r) {
33+
if (nums[i] > max) {
34+
max = nums[i]
35+
maxidx = i
36+
}
37+
}
38+
val root = TreeNode(max)
39+
root.left = mbt(nums, l, maxidx - 1)
40+
root.right = mbt(nums, maxidx + 1, r)
41+
return root
42+
}
43+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
654\. Maximum Binary Tree
2+
3+
Medium
4+
5+
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm:
6+
7+
1. Create a root node whose value is the maximum value in `nums`.
8+
2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value.
9+
3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value.
10+
11+
Return _the **maximum binary tree** built from_ `nums`.
12+
13+
**Example 1:**
14+
15+
![](https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg)
16+
17+
**Input:** nums = [3,2,1,6,0,5]
18+
19+
**Output:** [6,3,5,null,2,0,null,null,1]
20+
21+
**Explanation:** The recursive calls are as follow:
22+
23+
- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
24+
25+
- The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
26+
27+
- Empty array, so no child.
28+
29+
- The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
30+
31+
- Empty array, so no child.
32+
33+
- Only one element, so child is a node with value 1.
34+
35+
- The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
36+
37+
- Only one element, so child is a node with value 0.
38+
39+
- Empty array, so no child.
40+
41+
**Example 2:**
42+
43+
![](https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg)
44+
45+
**Input:** nums = [3,2,1]
46+
47+
**Output:** [3,null,2,null,1]
48+
49+
**Constraints:**
50+
51+
* `1 <= nums.length <= 1000`
52+
* `0 <= nums[i] <= 1000`
53+
* All integers in `nums` are **unique**.
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package g0601_0700.s0655_print_binary_tree
2+
3+
// #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree
4+
// #2023_02_13_Time_176_ms_(100.00%)_Space_36_MB_(80.00%)
5+
6+
import com_github_leetcode.TreeNode
7+
import java.util.LinkedList
8+
import kotlin.math.pow
9+
10+
/*
11+
* Example:
12+
* var ti = TreeNode(5)
13+
* var v = ti.`val`
14+
* Definition for a binary tree node.
15+
* class TreeNode(var `val`: Int) {
16+
* var left: TreeNode? = null
17+
* var right: TreeNode? = null
18+
* }
19+
*/
20+
class Solution {
21+
fun printTree(root: TreeNode?): List<MutableList<String>> {
22+
val result: MutableList<MutableList<String>> = LinkedList()
23+
val height = if (root == null) 1 else getHeight(root)
24+
val columns = (2.0.pow(height.toDouble()) - 1).toInt()
25+
val row: MutableList<String> = ArrayList()
26+
for (i in 0 until columns) {
27+
row.add("")
28+
}
29+
for (i in 0 until height) {
30+
result.add(ArrayList(row))
31+
}
32+
populateResult(root, result, 0, height, 0, columns - 1)
33+
return result
34+
}
35+
36+
private fun populateResult(
37+
root: TreeNode?,
38+
result: List<MutableList<String>>,
39+
row: Int,
40+
totalRows: Int,
41+
i: Int,
42+
j: Int
43+
) {
44+
if (row == totalRows || root == null) {
45+
return
46+
}
47+
result[row][(i + j) / 2] = root.`val`.toString()
48+
populateResult(root.left, result, row + 1, totalRows, i, (i + j) / 2 - 1)
49+
populateResult(root.right, result, row + 1, totalRows, (i + j) / 2 + 1, j)
50+
}
51+
52+
private fun getHeight(root: TreeNode?): Int {
53+
return if (root == null) {
54+
0
55+
} else 1 + getHeight(root.left).coerceAtLeast(getHeight(root.right))
56+
}
57+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
655\. Print Binary Tree
2+
3+
Medium
4+
5+
Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules:
6+
7+
* The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`.
8+
* The number of columns `n` should be equal to <code>2<sup>height+1</sup> - 1</code>.
9+
* Place the **root node** in the **middle** of the **top row** (more formally, at location `res[0][(n-1)/2]`).
10+
* For each node that has been placed in the matrix at position `res[r][c]`, place its **left child** at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its **right child** at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.
11+
* Continue this process until all the nodes in the tree have been placed.
12+
* Any empty cells should contain the empty string `""`.
13+
14+
Return _the constructed matrix_ `res`.
15+
16+
**Example 1:**
17+
18+
![](https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg)
19+
20+
**Input:** root = [1,2]
21+
22+
**Output:**
23+
24+
[["","1",""],
25+
["2","",""]]
26+
27+
**Example 2:**
28+
29+
![](https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg)
30+
31+
**Input:** root = [1,2,3,null,4]
32+
33+
**Output:**
34+
35+
[["","","","1","","",""],
36+
["","2","","","","3",""],
37+
["","","4","","","",""]]
38+
39+
**Constraints:**
40+
41+
* The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.
42+
* `-99 <= Node.val <= 99`
43+
* The depth of the tree will be in the range `[1, 10]`.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package g0601_0700.s0657_robot_return_to_origin
2+
3+
// #Easy #String #Simulation #2023_02_13_Time_186_ms_(100.00%)_Space_35.9_MB_(100.00%)
4+
5+
class Solution {
6+
fun judgeCircle(moves: String): Boolean {
7+
val map = IntArray(26)
8+
for (c in moves.toCharArray()) {
9+
map[c.code - 'A'.code]++
10+
}
11+
return map['U'.code - 'A'.code] == map['D'.code - 'A'.code] &&
12+
map['L'.code - 'A'.code] == map['R'.code - 'A'.code]
13+
}
14+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
657\. Robot Return to Origin
2+
3+
Easy
4+
5+
There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves.
6+
7+
You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its <code>i<sup>th</sup></code> move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down).
8+
9+
Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_.
10+
11+
**Note**: The way that the robot is "facing" is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
12+
13+
**Example 1:**
14+
15+
**Input:** moves = "UD"
16+
17+
**Output:** true
18+
19+
**Explanation:**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
20+
21+
**Example 2:**
22+
23+
**Input:** moves = "LL"
24+
25+
**Output:** false
26+
27+
**Explanation:**: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
28+
29+
**Constraints:**
30+
31+
* <code>1 <= moves.length <= 2 * 10<sup>4</sup></code>
32+
* `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package g0601_0700.s0658_find_k_closest_elements
2+
3+
// #Medium #Array #Sorting #Binary_Search #Two_Pointers #Heap_Priority_Queue #Binary_Search_II_Day_2
4+
// #2023_02_13_Time_375_ms_(95.16%)_Space_37.8_MB_(98.39%)
5+
6+
class Solution {
7+
fun findClosestElements(arr: IntArray, k: Int, x: Int): List<Int> {
8+
var left = 0
9+
var right = arr.size - k
10+
val answer: MutableList<Int> = ArrayList()
11+
while (left < right) {
12+
val mid = left + (right - left) / 2
13+
if (x - arr[mid] > arr[mid + k] - x) {
14+
left = mid + 1
15+
} else {
16+
right = mid
17+
}
18+
}
19+
for (i in left until left + k) {
20+
answer.add(arr[i])
21+
}
22+
return answer
23+
}
24+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
658\. Find K Closest Elements
2+
3+
Medium
4+
5+
Given a **sorted** integer array `arr`, two integers `k` and `x`, return the `k` closest integers to `x` in the array. The result should also be sorted in ascending order.
6+
7+
An integer `a` is closer to `x` than an integer `b` if:
8+
9+
* `|a - x| < |b - x|`, or
10+
* `|a - x| == |b - x|` and `a < b`
11+
12+
**Example 1:**
13+
14+
**Input:** arr = [1,2,3,4,5], k = 4, x = 3
15+
16+
**Output:** [1,2,3,4]
17+
18+
**Example 2:**
19+
20+
**Input:** arr = [1,2,3,4,5], k = 4, x = -1
21+
22+
**Output:** [1,2,3,4]
23+
24+
**Constraints:**
25+
26+
* `1 <= k <= arr.length`
27+
* <code>1 <= arr.length <= 10<sup>4</sup></code>
28+
* `arr` is sorted in **ascending** order.
29+
* <code>-10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup></code>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package g0601_0700.s0654_maximum_binary_tree
2+
3+
import com_github_leetcode.TreeNode
4+
import org.hamcrest.CoreMatchers.equalTo
5+
import org.hamcrest.MatcherAssert.assertThat
6+
import org.junit.jupiter.api.Test
7+
8+
internal class SolutionTest {
9+
@Test
10+
fun constructMaximumBinaryTree() {
11+
val expected = TreeNode.create(listOf(6, 3, 5, null, 2, 0, null, null, 1))
12+
assertThat(
13+
Solution().constructMaximumBinaryTree(intArrayOf(3, 2, 1, 6, 0, 5)).toString(),
14+
equalTo(expected.toString())
15+
)
16+
}
17+
18+
@Test
19+
fun constructMaximumBinaryTree2() {
20+
val expected = TreeNode.create(listOf(3, null, 2, null, 1))
21+
assertThat(
22+
Solution().constructMaximumBinaryTree(intArrayOf(3, 2, 1)).toString(),
23+
equalTo(expected.toString())
24+
)
25+
}
26+
}

0 commit comments

Comments
 (0)