Skip to content

Commit eaa74f5

Browse files
authored
Merge pull request neetcode-gh#768 from Raven1233/main
Added 295-Find-Median-From-Data-Stream.kt and 79-Word-Search.kt
2 parents 39f0dda + 8acfc53 commit eaa74f5

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class MedianFinder() {
2+
3+
/** initialize your data structure here. */
4+
val smaller = PriorityQueue<Int>(Comparator { a, b -> b - a })
5+
val larger = PriorityQueue<Int>()
6+
7+
fun addNum(num: Int) {
8+
if (smaller.isEmpty() || num <= smaller.peek()) smaller.offer(num)
9+
else larger.offer(num)
10+
if (smaller.size > larger.size + 1) larger.offer(smaller.poll())
11+
else if (larger.size > smaller.size) smaller.offer(larger.poll())
12+
}
13+
14+
fun findMedian(): Double {
15+
val even = (larger.size + smaller.size) % 2 == 0
16+
return if (even) (larger.peek() + smaller.peek()) / 2.0
17+
else smaller.peek().toDouble()
18+
}
19+
}

kotlin/79-Word-Search.kt

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
var ROWS: Int = 0
3+
var COLS: Int = 0
4+
5+
6+
fun exist(board: Array<CharArray>, word: String): Boolean {
7+
8+
ROWS = board.count()
9+
COLS = board[0].count()
10+
11+
for (row in 0 until ROWS) {
12+
for (col in 0 until COLS) {
13+
if (dfs(board, row, col, word, 0))
14+
return true
15+
}
16+
}
17+
18+
19+
return false
20+
}
21+
22+
fun dfs(board: Array<CharArray>, row: Int, col: Int, word: String, indx: Int): Boolean {
23+
/* Step 1). check the bottom case. */
24+
if (indx == word.count())
25+
return true
26+
/* Step 2). Check the boundaries. */
27+
if (row < 0 || row == ROWS || col < 0 || col == COLS || board[row][col] != word[indx])
28+
return false
29+
30+
// mark the path before the next exploration
31+
board[row][col] = '#'
32+
var found = false
33+
val rowOffsets = intArrayOf(0, 1, 0, -1)
34+
val colOffsets = intArrayOf(1, 0, -1, 0)
35+
36+
for (i in 0..3) {
37+
found = dfs(board, row + rowOffsets[i], col + colOffsets[i], word, indx + 1)
38+
if (found)
39+
break
40+
41+
}
42+
/* Step 4). clean up and return the result. */
43+
board[row][col] = word[indx]
44+
45+
return found
46+
}
47+
48+
49+
50+
}

0 commit comments

Comments
 (0)