Цена за 48 часов в ленте | 400,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
Дополнительные условия рекламы | Отсутствуют |
Input
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
[[], [1], [1], [2], [], [1], []]
Output
[null, true, false, true, 2, true, 1]
import kotlin.random.Random
class RandomizedCollection {
private val dict = mutableMapOf>()
private val list = mutableListOf()
fun insert(val: Int): Boolean {
val exists = dict.containsKey(val)
if (!exists) {
dict[val] = mutableSetOf()
}
dict[val]?.add(list.size)
list.add(val)
return !exists
}
fun remove(val: Int): Boolean {
val indices = dict[val] ?: return false
val index = indices.first()
indices.remove(index)
val lastElement = list.removeAt(list.size - 1)
if (index < list.size) {
list[index] = lastElement
dict[lastElement]?.remove(list.size)
dict[lastElement]?.add(index)
}
if (indices.isEmpty()) {
dict.remove(val)
}
return true
}
fun getRandom(): Int {
return list[Random.nextInt(list.size)]
}
}
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
class Solution {
fun deleteNode(node: ListNode?) {
node?.`val` = node?.next?.`val` ?: return
node.next = node.next?.next
}
}
Input: nestedList = [1,[4,[6]]]
Output: 27
Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.
class Solution {
fun depthSum(nestedList: List): Int {
return dfs(nestedList, 1)
}
private fun dfs(list: List, depth: Int): Int {
var total = 0
for (nested in list) {
if (nested.isInteger()) {
total += nested.getInteger() * depth
} else {
total += dfs(nested.getList(), depth + 1)
}
}
return total
}
}
Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]
import kotlin.random.Random
class RandomizedSet {
private val dict = mutableMapOf()
private val list = mutableListOf()
fun insert(val: Int): Boolean {
if (dict.containsKey(val)) {
return false
}
dict[val] = list.size
list.add(val)
return true
}
fun remove(val: Int): Boolean {
val index = dict[val] ?: return false
val lastElement = list.removeAt(list.size - 1)
if (index < list.size) {
list[index] = lastElement
dict[lastElement] = index
}
dict.remove(val)
return true
}
fun getRandom(): Int {
return list[Random.nextInt(list.size)]
}
}
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
class Solution {
private var ans: TreeNode? = null
private fun recurseTree(currentNode: TreeNode?, p: TreeNode, q: TreeNode): Boolean {
if (currentNode == null) {
return false
}
val left = if (recurseTree(currentNode.left, p, q)) 1 else 0
val right = if (recurseTree(currentNode.right, p, q)) 1 else 0
val mid = if (currentNode == p || currentNode == q) 1 else 0
if (mid + left + right >= 2) {
ans = currentNode
}
return mid + left + right > 0
}
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode, q: TreeNode): TreeNode? {
recurseTree(root, p, q)
return ans
}
}
Input
["PhoneDirectory", "get", "get", "check", "get", "check", "release", "check"]
[[3], [], [], [2], [], [2], [2], [2]]
Output
[null, 0, 1, true, 2, false, null, true]
class PhoneDirectory(maxNumbers: Int) {
private val isSlotAvailable = BooleanArray(maxNumbers) { true }
fun get(): Int {
for (i in isSlotAvailable.indices) {
if (isSlotAvailable[i]) {
isSlotAvailable[i] = false
return i
}
}
return -1
}
fun check(number: Int): Boolean {
return isSlotAvailable[number]
}
fun release(number: Int) {
isSlotAvailable[number] = true
}
}
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
class Solution {
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode, q: TreeNode): TreeNode? {
val parentVal = root?.`val`
val pVal = p.`val`
val qVal = q.`val`
return if (pVal > parentVal!! && qVal > parentVal) {
lowestCommonAncestor(root.right, p, q)
} else if (pVal < parentVal && qVal < parentVal) {
lowestCommonAncestor(root.left, p, q)
} else {
root
}
}
}
Input: matrix = [[-5]], k = 1
Output: -5
import java.util.PriorityQueue
data class MyHeapNode(val value: Int, val row: Int, val column: Int) : Comparable{
override fun compareTo(other: MyHeapNode): Int {
return value - other.value
}
}
class Solution {
fun kthSmallest(matrix: Array, k: Int): Int {
val N = matrix.size
val minHeap = PriorityQueue()
for (r in 0 until minOf(N, k)) {
minHeap.offer(MyHeapNode(matrix[r][0], r, 0))
}
var element: MyHeapNode = minHeap.peek()
var k = k
while (k > 0) {
element = minHeap.poll()
val r = element.row
val c = element.column
if (c < N - 1) {
minHeap.offer(MyHeapNode(matrix[r][c + 1], r, c + 1))
}
k -= 1
}
return element.value
}
}
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
class Solution {
private fun dfs(word: String, length: Int, visited: BooleanArray, dictionary: Set): Boolean {
if (length == word.length) return true
if (visited[length]) return false
visited[length] = true
for (i in word.length - if (length == 0) 1 else 0 downTo length + 1) {
if (dictionary.contains(word.substring(length, i)) && dfs(word, i, visited, dictionary)) {
return true
}
}
return false
}
fun findAllConcatenatedWordsInADict(words: List): List {
val dictionary = words.toSet()
val answer = mutableListOf()
for (word in words) {
val visited = BooleanArray(word.length)
if (dfs(word, 0, visited, dictionary)) {
answer.add(word)
}
}
return answer
}
}
Input: n = 1
Output: [2]
class Solution {
fun rand10(): Int {
var row: Int
var col: Int
var idx: Int
do {
row = rand7()
col = rand7()
idx = col + (row - 1) * 7
} while (idx > 40)
return 1 + (idx - 1) % 10
}
}
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
class Solution {
fun countBits(num: Int): IntArray {
val ans = IntArray(num + 1)
for (x in 1..num) {
ans[x] = ans[x and (x - 1)] + 1
}
return ans
}
}
Input: queryIP = "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
class Solution {
fun validateIPv4(IP: String): String {
val nums = IP.split(".")
for (x in nums) {
if (x.length == 0 || x.length > 3) return "Neither"
if (x[0] == '0' && x.length != 1) return "Neither"
for (ch in x) {
if (!ch.isDigit()) return "Neither"
}
if (x.toInt() > 255) return "Neither"
}
return "IPv4"
}
fun validateIPv6(IP: String): String {
val nums = IP.split(":")
val hexdigits = "0123456789abcdefABCDEF"
for (x in nums) {
if (x.length == 0 || x.length > 4) return "Neither"
for (ch in x) {
if (hexdigits.indexOf(ch) == -1) return "Neither"
}
}
return "IPv6"
}
fun validIPAddress(IP: String): String {
return when {
IP.count { it == '.' } == 3 -> validateIPv4(IP)
IP.count { it == ':' } == 7 -> validateIPv6(IP)
else -> "Neither"
}
}
}
Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
class Solution {
fun rob(root: TreeNode?): Int {
val answer = helper(root)
return maxOf(answer[0], answer[1])
}
private fun helper(node: TreeNode?): IntArray {
if (node == null) return intArrayOf(0, 0)
val left = helper(node.left)
val right = helper(node.right)
val rob = node.`val` + left[1] + right[1]
val notRob = maxOf(left[0], left[1]) + maxOf(right[0], right[1])
return intArrayOf(rob, notRob)
}
}
Input: transactions = [[0,1,10],[2,0,5]]
Output: 2
class Solution {
private val creditList = mutableListOf()
fun minTransfers(transactions: Array): Int {
val creditMap = mutableMapOf()
for (t in transactions) {
creditMap[t[0]] = creditMap.getOrDefault(t[0], 0) + t[2]
creditMap[t[1]] = creditMap.getOrDefault(t[1], 0) - t[2]
}
for (amount in creditMap.values) {
if (amount != 0) {
creditList.add(amount)
}
}
val n = creditList.size
return dfs(0, n)
}
private fun dfs(cur: Int, n: Int): Int {
var cur = cur
while (cur < n && creditList[cur] == 0) {
cur++
}
if (cur == n) {
return 0
}
var cost = Int.MAX_VALUE
for (nxt in (cur + 1) until n) {
if (creditList[nxt] * creditList[cur] < 0) {
creditList[nxt] += creditList[cur]
cost = minOf(cost, 1 + dfs(cur + 1, n))
creditList[nxt] -= creditList[cur]
}
}
return cost
}
}
Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"]
class Solution {
fun palindromePairs(words: Array): List > {
val pairs = mutableListOf>()
for (i in words.indices) {
for (j in words.indices) {
if (i == j) continue
val combined = words[i] + words[j]
if (combined == combined.reversed()) {
pairs.add(listOf(i, j))
}
}
}
return pairs
}
}
Input: nums = [9], target = 3
Output: 0
class Solution {
private val memo = mutableMapOf()
fun combinationSum4(nums: IntArray, target: Int): Int {
return combs(nums, target)
}
private fun combs(nums: IntArray, remain: Int): Int {
if (remain == 0) return 1
if (memo.containsKey(remain)) return memo[remain]!!
var result = 0
for (num in nums) {
if (remain - num >= 0) {
result += combs(nums, remain - num)
}
}
memo[remain] = result
return result
}
}