
- Главная
- Каталог
- Интернет технологии
- Kotlin | LeetCode
Статистика канала
Input: s = "aab"
Output: "aba"{}
import java.util.PriorityQueue
class Solution {
fun reorganizeString(s: String): String {
val charCounts = IntArray(26)
for (c in s) {
charCounts[c - 'a']++
}
val pq = PriorityQueue(compareByDescending<Pair<Int, Char>> { it.first })
for (i in 0 until 26) {
if (charCounts[i] > 0) {
pq.add(Pair(charCounts[i], 'a' + i))
}
}
val result = StringBuilder()
while (pq.isNotEmpty()) {
val first = pq.poll()
if (result.isEmpty() || first.second != result.last()) {
result.append(first.second)
if (first.first > 1) {
pq.add(Pair(first.first - 1, first.second))
}
} else {
if (pq.isEmpty()) {
return ""
}
val second = pq.poll()
result.append(second.second)
if (second.first > 1) {
pq.add(Pair(second.first - 1, second.second))
}
pq.add(first)
}
}
return result.toString()
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Explanation: One way to obtain s3 is:
Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a".
Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac".{}
class Solution {
fun isInterleave(s1: String, s2: String, s3: String): Boolean {
if (s3.length != s1.length + s2.length) return false
val dp = Array(s1.length + 1) { BooleanArray(s2.length + 1) }
for (i in 0..s1.length) {
for (j in 0..s2.length) {
when {
i == 0 && j == 0 -> dp[i][j] = true
i == 0 -> dp[i][j] = dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]
j == 0 -> dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]
else -> dp[i][j] = (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1])
}
}
}
return dp[s1.length][s2.length]
}
}
// Example usage
fun main() {
val solution = Solution()
val s1 = "abc"
val s2 = "def"
val s3 = "adbcef"
println("Can s3 be formed by interleaving s1 and s2? ${solution.isInterleave(s1, s2, s3)}")
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]{}
class Solution {
fun sortColors(nums: IntArray) {
var p0 = 0
var curr = 0
var p2 = nums.size - 1
while (curr <= p2) {
when {
nums[curr] == 0 -> {
nums.swap(p0, curr)
p0++
curr++
}
nums[curr] == 2 -> {
nums.swap(curr, p2)
p2--
}
else -> curr++
}
}
}
private fun IntArray.swap(i: Int, j: Int) {
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [5,2,3,1]
Output: [1,2,3,5]{}
fun mergeSort(nums: IntArray) {
if (nums.size > 1) {
val mid = nums.size / 2
val left_half = nums.sliceArray(0 until mid)
val right_half = nums.sliceArray(mid until nums.size)
mergeSort(left_half)
mergeSort(right_half)
var i = 0
var j = 0
var k = 0
while (i < left_half.size && j < right_half.size) {
if (left_half[i] < right_half[j]) {
nums[k++] = left_half[i++]
} else {
nums[k++] = right_half[j++]
}
}
while (i < left_half.size) {
nums[k++] = left_half[i++]
}
while (j < right_half.size) {
nums[k++] = right_half[j++]
}
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).{}
class Solution {
fun islandPerimeter(grid: Array<IntArray>): Int {
val rows = grid.size
val cols = grid[0].size
var result = 0
for (r in 0 until rows) {
for (c in 0 until cols) {
if (grid[r][c] == 1) {
val up = if (r == 0) 0 else grid[r-1][c]
val left = if (c == 0) 0 else grid[r][c-1]
val down = if (r == rows-1) 0 else grid[r+1][c]
val right = if (c == cols-1) 0 else grid[r][c+1]
result += 4 - (up + left + right + down)
}
}
}
return result
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5] {}
dummyHead), который указывает на head, чтобы упростить удаление узлов, включая первый.
slow и fast), перемещая fast на n шагов вперед.
slow и fast, пока fast не достигнет конца списка, затем удалить n-й узел.
class Solution {
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
val dummyHead = ListNode(0).apply { next = head }
var slow = dummyHead
var fast = head
repeat(n) { fast = fast?.next }
while (fast != null) {
fast = fast.next
slow = slow.next!!
}
slow.next = slow.next?.next
return dummyHead.next
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input
["LogSystem", "put", "put", "put", "retrieve", "retrieve"]
[[], [1, "2017:01:01:23:59:59"], [2, "2017:01:01:22:59:59"], [3, "2016:01:01:00:00:00"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Year"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour"]]
Output
[null, null, null, null, [3, 2, 1], [2, 1]]{}
class LogSystem {
private val logs = mutableListOf<Pair<Int, String>>()
private val granularity = mapOf(
"Year" to 4,
"Month" to 7,
"Day" to 10,
"Hour" to 13,
"Minute" to 16,
"Second" to 19
)
fun put(id: Int, timestamp: String) {
logs.add(id to timestamp)
}
fun retrieve(start: String, end: String, granularity: String): List<Int> {
val length = this.granularity[granularity]!!
val start = start.substring(0, length)
val end = end.substring(0, length)
return logs.filter { (id, timestamp) ->
val ts = timestamp.substring(0, length)
start <= ts && ts <= end
}.map { it.first }
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]{}
class Solution {
fun transpose(A: Array<IntArray>): Array<IntArray> {
val R = A.size
val C = A[0].size
val ans = Array(C) { IntArray(R) }
for (r in 0 until R) {
for (c in 0 until C) {
ans[c][r] = A[r][c]
}
}
return ans
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.{}
class Solution {
fun shortestToChar(S: String, C: Char): IntArray {
val ans = IntArray(S.length)
var prev = -S.length
for (i in S.indices) {
if (S[i] == C) {
prev = i
}
ans[i] = i - prev
}
prev = 2 * S.length
for (i in S.length - 1 downTo 0) {
if (S[i] == C) {
prev = i
}
ans[i] = minOf(ans[i], prev - i)
}
return ans
}
}{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
Каталог Телеграм-каналов для нативных размещений
Kotlin | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 1.8K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.1, количество отзывов – 0, со средней оценкой 0.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 699.3 ₽, а за 1 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий